hibernate4中使用Session doWork()方法进行jdbc操作

import org.hibernate.jdbc.Work;
public class TestDoWork(){
public void testSessionDowork() throws Exception {
        Session session = getSession();
        final String sql="select * from t_cp_user";
        try{
             session.beginTransaction();
             session.doWork(
//定义一个匿名类,实现了Work接口
                     new Work() {
                         public void execute(Connection connection) throws SQLException {
//经由过程JDBC API执行SQL语句
                             PreparedStatement ps = connection.prepareStatement( sql );
                             ResultSet rs = ps.executeQuery();
                             try {
                                 ResultSetMetaData metadata = rs.getMetaData();
                             }
                             finally {
                                 doClose(null,ps,rs);
                             }
                         }
                     }
             );
             session.getTransaction().commit();
             //session.close();
        }catch(Exception ex){
            log.error(ex,ex);
        }
        finally{
            this.doClose(session, null, null);
        }
      }
     //释放数据资源 by rhine
     
    protected void doClose(Session session, Statement stmt, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
                rs=null;
            } catch (Exception ex) {
                rs=null;
                log.error(ex,ex);
                ex.printStackTrace();
            }
        }
        // Statement对象关闭时,会自动释放其管理的一个ResultSet对象
        if(stmt != null){
            try {
                stmt.close();
                stmt=null;
            } catch (Exception ex) {
                stmt=null;
                log.error(ex,ex);
                ex.printStackTrace();
            }
        }
//      当Hibernate的事务由Spring接管时,session的关闭由Spring管理.不用手动关闭
//      if(session != null){
//          session.close();
//      }
    }

猜你喜欢

转载自15271926049.iteye.com/blog/2176048