hibernate4 批量删除

以往做批量删除时,写法如下

@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 内存溢出的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值