說說 Spring 的數(shù)據(jù)訪問模板

1 使用 JDBC 進行數(shù)據(jù)訪問

下面是一段典型的使用 JDBC 進行數(shù)據(jù)訪問操作的代碼,我們已經(jīng)盡可能地對代碼進行了精簡:

public void save(User user) throws SQLException {
        Connection con = null;
        PreparedStatement statement = null;

        try {
            //獲取數(shù)據(jù)連接
            con = getConnection();

            //設(shè)定為手工提交事務(wù)
            con.setAutoCommit(false);

            //處理數(shù)據(jù)
            statement = con.prepareStatement("insert into USER(ID,NAME) values(?,?)");
            statement.setLong(1, user.getId());
            statement.setString(2, user.getName());
            statement.execute();

            //提交事務(wù)
            statement.execute();
        } catch (SQLException e) {
            try {
                con.rollback();//回滾事務(wù)
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            throw e;
        } finally {//釋放資源
            try {
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

如以上所示, JDBC 執(zhí)行數(shù)據(jù)訪問操作的流程是這樣的:

  1. 準備資源;
  2. 啟動事務(wù);
  3. 在事務(wù)中執(zhí)行具體的數(shù)據(jù)訪問操作;
  4. 返回數(shù)據(jù)。
  5. 提交 / 回滾事務(wù);
  6. 關(guān)閉資源。
  7. 處理異常 。

2 使用 Spring 進行數(shù)據(jù)訪問

Spring 將這個數(shù)據(jù)訪問流程固化到模板類中,并將數(shù)據(jù)訪問中固定和變化的部分分開,同時保證模板類是線程安全,以便多個數(shù)據(jù)訪問線程可以共享同一個模板實例 。

這樣我們只需要編寫好回調(diào)接口,并調(diào)用相應(yīng)的模板類進行數(shù)據(jù)訪問,就可以啦。這樣既可以提高開發(fā)效率,也可以徹底消除因忽視資源釋放而引發(fā)的資源泄漏的問題 。

3 Spring 持久化技術(shù)模板類

Spring 為各種支持的持久化技術(shù)都提供了簡化操作的模板類和回調(diào)方法,我們可以在回調(diào)中編寫具體的數(shù)據(jù)操作邏輯,然后使用模板來執(zhí)行數(shù)據(jù)操作。

不同持久化技術(shù)所對應(yīng)的模板類與支持類:

ORM 持久化技術(shù) 模板類 支持類
JDBC org.springframework.jdbc.core.JdbcTemplate org.springframework.jdbc.core. JdbcDaoSupport
Hibernate X org.springframework.orm.hibernateX.HibernateTemplate org.springframework.orm.hibernateX.HibernateDaoSupport
JPA org.springframework.orm.jpa.JpaTemplate org.springframework.orm.jpa.JpaDaoSupport
JDO org.springframework.orm.jdo.JdoTemplate org.springframework.orm.jdo.JdoDaoSupport

這些支持類都繼承自 dao.support.DaoSupport 類, DaoSupport 實現(xiàn)了 InitializingBean 接口,在 afterPropertiesSet() 方法中檢查了模板對象和數(shù)據(jù)源是否已被正確設(shè)置,否則拋出異常 。 所有的支持類都是抽象類,其目的是希望被繼承使用。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容