JPA+Hibernate Junit4做批量删除时出错:
批量删除方法如下:
(private EntityManager em)
/**
* 批量删除实体
* 可实体批量删除操作,在一个transaction中完成
* 任何Exception发生,全部更新操作回滚
* @param entityClass 实体类
* @param entityids 实体id数组
*/
public void batchDelete(List<T> entities){
for(int i = 0; i<entities.size(); i++){
em.remove(entities.get(i));
}
}
junit测试出现以下错误:
java.lang.IllegalArgumentException: Removing a detached instance com.agiliti.bean.person.Person#47
..................
原因:
em调用remove时,Hibernate仍然还处于“detach”状态,在Hibernate文档中关于detach叙述:
Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again.
此时,Session已经关闭,但引用仍然存在(换句话说,heap里的对象没有了)。所以此时必须再次产生一个Session(在heap里产生对象):
解决方法之一——在删除之前把这个Detached instance绑定到当前的Sesssion,在用当前Sesssion删除此instance。getEntityManager()提供merge方法实现:
public void batchDelete(List<T> entities){
for(int i = 0; i<entities.size(); i++){
em.remove(em.merge(entities.get(i)));
}
}
请注意:如果写成:
仍然错误写法
public void batchDelete(List<T> entities){
for(int i = 0; i<entities.size(); i++){
em.merge(entities.get(i));
em.remove(entities.get(i));
}
}
原因是执行完merge还是detached, merge后返回的新对象才是允许删除的。
分享到:
相关推荐
仓库管理系统,SpringBoot+Spring Data JPA+.....
管理系统系列--仓库管理系统,SpringBoot+Spring Data JPA+.....
用SpringBoot + Spring Data JPA操作数据库 项目启动的时候 报了一个错 SpringBoot的版本是2.2.6.RELEASE org.springframework.beans.factory.BeanCreationException: Error creating bean with name '...
测试通过,集成了spirng MVC4+data jpa+spring Security pom.xml
搭建一个JPA+hibernate实例
标签:hibernate、javax、persistence、jpa、api、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,...
【资源介绍】毕设项目:基于springboot+jpa+thymeleaf的网络点餐系统.zip毕设项目:基于springboot+jpa+thymeleaf的网络点餐系统.zip毕设项目:基于springboot+jpa+thymeleaf的网络点餐系统.zip毕设项目:基于...
仓库管理系统,SpringBoot+Spring Data JPA.zip仓库管理系统,SpringBoot+Spring Data JPA.zip仓库管理系统,SpringBoot+Spring Data JPA.zip仓库管理系统,SpringBoot+Spring Data JPA.zip仓库管理系统,SpringBoot...
Spring2.5.5+Struts2.0.11.2+JPA+Hibernate3.3实战
基础框架,可满足开发需要
jpa和hibernate的一个简单例子
jpa + hibernate 简单列子实现和junit测试 完整jar包都已测试过。
Hibernate+JPA注解教程.docHibernate+JPA注解教程.docHibernate+JPA注解教程.docHibernate+JPA注解教程.doc
Flex 是一个高效、免费的开源框架,可用于构建具有表现力的 Web应用程序,这些应用... 本课程主要是讲解Flex 4.6和ActionScript 3.0使用方法和技巧,并结合BlazDS/Spring /JPA/Hibernate等技术实现在线书店的开发过程。
1、基于SpringBoot+Thymeleaf+JPA的博客系统源码.zip 2、该资源包括项目的全部源码,下载可以直接使用! 3、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 ...
本资源后台使用Java,前端使用angular5,后台是springdata JPA+springmvc+hibernate写的一个小例子,数据库表自动生成,注意修改MySQL 配置及angular地址访问路径