[英]Entity manager batch update gives org.hibernate.PersistentObjectException: detached entity passed to persist
I tried to follow this article because with batch updates I get unnecessary selects using merge:我尝试关注这篇文章,因为通过批量更新,我使用合并获得了不必要的选择:
for(int i = 0; i< elements.size(); i++){
Query q = em.createQuery("select p from Parent p join fetch p.child c where p.id=:id", Parent.class);
//parameter of :id from elements
Parent p = q.getSingleResult();
p.setName("aname"); //for simplicity just the name member
myList.add(p);
}
utx = com.arjuna.ats.jta.UserTransaction.userTransaction();
utx.begin();
em.joinTransaction();
for(int i = 0; i< myList.size(); i++){
if (i > 0 && i % Common.BATCH_SIZE == 0) { //BATCH_SIZE=50
em.flush();
em.clear();
}
Parent myObject = myList.get(i);
em.merge(myObject);
}
utx.commit();
This is my Entity definition:这是我的实体定义:
@Entity
@Table(name = "myparenttable", schema = "myschema", catalog = "mydb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Parent implements Serializable {
private Integer id_parent;
private String name;
@JsonManagedReference
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private List<Child> children;
//getters and setters
@JsonInclude(JsonInclude.Include.NON_NULL)
@OneToMany(mappedBy = "parent", targetEntity = Child.class, fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST, CascadeType.MERGE})
public Set<Child> getChildren() {
return this.children;
}
public void setChildren(Set<Child> children) {
this.children = children;
}
}
@Entity
@Table(name = "mychildtable", schema = "myschema", catalog = "mydb")
public class Child implements Serializable {
private Integer id_child;
private String description;
@JsonBackReference
private Parent parent;
//getters and setters
}
Following the mentioned article, I changed my code like this:在提到的文章之后,我像这样更改了我的代码:
utx = com.arjuna.ats.jta.UserTransaction.userTransaction();
utx.begin();
em.joinTransaction();
Session session = em.unwrap( Session.class );
for(int i = 0; i< myList.size(); i++){
if (i > 0 && i % Common.BATCH_SIZE == 0) { //BATCH_SIZE=50
em.flush();
em.clear();
}
Parent myObject = elements.get(i);
session.update(myObject);
}
utx.commit();
When the list is less than BATCH_SIZE (<50) the edits are made correctly, however, then the flush and clear statements are necessary, I get this error:当列表小于 BATCH_SIZE (<50) 时,编辑正确,但是,flush 和 clear 语句是必要的,我收到此错误:
detached entity passed to persist: Child
I also tried:我也试过:
session.flush();
session.clear();
With the exact same error.有完全相同的错误。 Is there something I'm missing?
有什么我想念的吗?
Have you checked if the list contains duplicate objects?您是否检查过列表是否包含重复的对象? If one batch would try to update an object with the same identifier twice, you could run into this issue.
如果一批尝试更新具有相同标识符的对象两次,您可能会遇到此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.