利用hibernate执行jdbc中的事务处理

//此为更新的例子
try{
Session session = HibernateUtil.currentSession();
try{
Connection connection = session.connection();// 获取连接
PreparedStatement preparedStatement = null;
String deleteSQL = "delete from a where b=c";
//开始事务
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(deleteSQL);
preparedStatement.executeUpdate();
//提交JDBC事务
connection.commit();
// 恢复JDBC事务的默认提交方式
connection.setAutoCommit(true);
preparedStatement.close();
}catch (SQLException x) {
connection.rollback();
throw x;
}
}catch(HibernateException e){
e.printStackTrace();
throw e;
}finally{
HibernateUtil.closeSession();
}

//关于查询:
try{
Session session = HibernateUtil.currentSession();
try{
Connection conn = session.connection();
PreparedStatement prepstmt = conn.prepareStatement(query);
prepstmt.setLong(1,Long.parseLong(paperId));
ResultSet rs = prepstmt.executeQuery();
ArrayList rsl = new ArrayList();
while(rs.next()){
HashMap item = new HashMap();
item.put("××",Long.toString(rs.getLong("××")));
rsl.add(item);
}
//一定要养成好习惯用完就关,否则会报“游标超出最大值”的错误的
rs.close();
prepstmt.close();
}catch (SQLException x) {
connection.rollback();
throw x;
}
}catch(HibernateException e){
e.printStackTrace();
throw e;
}finally{
HibernateUtil.closeSession();
}

//调用存储过程:
try{
Session session = HibernateUtil.currentSession();
Connection conn = session.connection();
CallableStatement cstmt = conn.prepareCall("{call SAVE_AS_NEW_PAPER(?,?)}");
cstmt.setLong(1, new Long(newPid).longValue());
cstmt.setLong(2, new Long(oldPid).longValue());
cstmt.executeQuery();
cstmt.close();
}catch(HibernateException e){
throw e;
}catch(SQLException e){
throw e;
}finally{
HibernateUtil.closeSession();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值