Hibernate中session.connection()的替代方法

Hibernate中session.connection()的替代方法
     Hibernate3.3.2版本中getSession().connection()已被棄用,替代方法SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection()

來自類org.springframework.orm.hibernate3.SessionFactoryUtils

例子:

        java.sql.Connection c = null;
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;

public List   method(String sql) {
        List ret = new ArrayList();
        try {
        c = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
            ps = c.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()) {
                 .....
                }
                ret.add(ro);
            }
        } catch (Exception e) {
             e.printStackTrace();

       } finally {
           close();
        }
        return ret;
    }

Hibernate API中讓使用doWork(Work,work),描述如下:

() 
Deprecated. (scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use ; for opening a 'temporary Session' use (TBD).

         Work接口的execute()方法用於執行直接通過JDBC API來訪問數據庫的操作:
public interface Work {
//直接通過JDBC API來訪問數據庫的操作
public void execute(Connection connection) throws SQLException;
}
Session的doWork(Work work)方法用於執行Work對象指定的操作,即調用Work對象的execute()方法。Session會把當前使用的數據庫連接傳給execute()方法。

過程如下:

Transaction tx=session.beginTransaction();
//定義一個匿名類,實現了Work接口
Work work=new Work(){
public void execute(Connection connection)throws SQLException{
//通過JDBC API執行用於批量更新的SQL語句
PreparedStatement stmt=connection
.prepareStatement("update CUSTOMERS set AGE=AGE+1 "
+"where AGE>0 ");
stmt.executeUpdate();
}
};

發佈了14 篇原創文章 · 獲贊 17 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章