hibernate4 批量删除
来源:互联网 发布:手机淘宝一键秒杀在哪? 编辑:程序博客网 时间:2024/06/05 20:57
以往做批量删除时,写法如下
@Autowiredprivate SessionFactory sessionFactory;public Session getSession() { return this.sessionFactory.openSession();}public Transaction geTransaction(){ return this.getSession().beginTransaction();}@Overridepublic 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,结果问题马上就解决了。修改后的代码如下
@Autowiredprivate SessionFactory sessionFactory;public Session getSession() { return this.sessionFactory.getCurrentSession();}@Overridepublic 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
- hibernate4 批量删除
- Hibernate4 更新删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- 批量删除
- PS快捷键
- 基于 Django1.10 文档的深入学习(14)—— Request and response objects 之 HttpResponse objects
- springmvc(二)---controller中方法的三种返回值形式
- 分布式业务系统的一致性
- [BZOJ1177][Apio2009]Oil(暴力模拟)
- hibernate4 批量删除
- Adapter 适配器模式
- 电路原理实验八:受控源特性测试
- vue百度下拉框
- equals()
- egret游戏进度条实现
- hibernate+atomikos分布式事务配置
- 《大数据挑战与NoSQL数据库技术》读后感&读书笔记
- 性能优化二十之数据传输效率优化-FlatBuffers