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

Hibernate3.3.2版本中getSession().connection()已被弃用,hibernate4中官方推荐使用Session doWork()方法进行jdbc操作

首先看看Work接口类的定义

public interface Work {
//Execute the discrete work encapsulated by this work instance using the supplied connection.
//@param connection The connection on which to perform the work.
// @throws SQLException Thrown during execution of the underlying JDBC interaction.
// @throws HibernateException Generally indicates a wrapped SQLException.
public void execute(Connection connection) throws SQLException;
}

具体代码如下:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement; import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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();
while (rs.next()) {
user.setUserId(rs.getLong("USER_ID"));
user.setUsername(rs.getString("USERNAME"));
}
}
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();
// }
}
上一篇:PL/SQL快速选中一行并执行


下一篇:redis存储session配制方法