以往做批量删除时,写法如下
@Autowired
private SessionFactory sessionFactory;
public Session getSession() {
return this.sessionFactory.openSession();
}
public Transaction geTransaction(){
return this.getSession().beginTransaction();
}
@Override
public void saveRoleMenuAuth(Role role, List<MenuAuthority> menuAuthoritys) {
for (int i = 0; i < menuAuthoritys.size(); i++) {
MenuAuthority ma = menuAuthoritys.get(i);
RoleMenuAuthority rma = new RoleMenuAuthority();
rma.setMenuAuthority(ma);
rma.setRole(role);
this.getSession().save(rma);
// 已50条数据作为一个单元
if (i % 50 == 0) {
this.getSession().flush();// 将hibernate缓存中数据提交到数据库
this.getSession().clear();// 清空缓存
}
}
this.geTransaction().commit();
this.getSession().close();
}
这种方法看似没什么问题,而且在我刚做完的时候确实是好使的,但是过了一段时间后,就开始报错了,报 org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction;错误,网上各种方法找遍了,结果都是无功而返。
最后自己思考,其他方法都好使,只有这个方法有问题,而且通过报错来看,问题是出在 session 上了,与其他类中的 session 相比,这个类的 session 采用了手动提交,虽然看代码没什么问题,但从目前结果来看,问题肯定出在这里了,然后将 session 获取为自动提交方式的 session,结果问题马上就解决了。修改后的代码如下
@Autowired
private SessionFactory sessionFactory;
public Session getSession() {
return this.sessionFactory.getCurrentSession();
}
@Override
public void saveRoleMenuAuth(Role role, List<MenuAuthority> menuAuthoritys) {
for (int i = 0; i < menuAuthoritys.size(); i++) {
MenuAuthority ma = menuAuthoritys.get(i);
RoleMenuAuthority rma = new RoleMenuAuthority();
rma.setMenuAuthority(ma);
rma.setRole(role);
this.getSession().save(rma);
// 已20条数据作为一个单元
// 这里的数字最好与 hibernate.jdbc.batch_size 相同
if (i % 50 == 0) {
this.getSession().clear();// 清空缓存
}
}
}
虽然采用了 session 自动提交的方式,但仍然需要定量清空 session 的缓存,否则会造成 session 内存溢出的