1、获取session
Session hibernateSession = this.getSession();
2、开启事务
Transaction transaction = hibernateSession.beginTransaction();
3、执行数据库操作 try{}catch(){},正常程序在try{}中,事务执行
transaction.commit();
4、catch(){}块中 事务回滚
transaction.rollback();
5、finally{}释放session
releaseSession(hibernateSession);
完整的:
public <T> boolean Save(Object obj,List<T> entitys) {
Session hibernateSession = this.getWriteSession();
// 开启事物
Transaction transaction = hibernateSession.beginTransaction();
Boolean tag = true;
try {
if (obj != null) {
// 判断是否保存或更新该实体
hibernateSession.save(obj);
for (int i = 0; i < entitys.size(); i++) {
//保存子集
hibernateSession.save(entitys.get(i));
if (i % 100 == 0) {
// 100个对象批量写入数据库,清理缓存
hibernateSession.flush();
hibernateSession.clear();
}
}
//最后页面的数据,手工清理
hibernateSession.flush();
hibernateSession.clear();
transaction.commit();
}
} catch (Exception e) {
tag=false;
e.printStackTrace();
// 回滚事物
transaction.rollback();
//加入日志
logger.error(e.getMessage());
} finally {
try {
releaseSession(hibernateSession);
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}