[英]Hibernate: org.hibernate.PersistentObjectException: detached entity passed to persist
I have tried many things which were mentioned in the thread. 我尝试过很多线程中提到的东西。 But none seem to solve my problem.
但似乎没有一个能解决我的问题。 Please tell me where I am going wrong.
请告诉我哪里出错了。
Models 楷模
@Entity
public class MySession {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(unique=true)
private String sessionId;
@OneToMany(mappedBy="session")
private List<MyRequest> requestList;
}
@Entity
public class MyRequest{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
private MySession session;
}
In my servlet: 在我的servlet中:
SessionHome sh = new SessionHome(); //DAO Class
MyRequestHome mrh = new MyRequestHome(); //DAO Class
MySession session = sh.findBySessionId(sessionId); //Object is in the detached state
session.setUpdated(new Date()); //Update the Session update time stamp
session = sh.merge(session); //Update the database with the session. I was hoping merge would reattach the detached object
MyRequest mr = new MyRequest(hsrequest, newSessionToken);
mr.setSession(session);
mrh.persist(mr); //PersistentObjectException here. This is because of the MySession object I have set over here.
Firstly, I get the MySession Object from the database, update it and set it in the newly created MyRequest object. 首先,我从数据库中获取MySession对象,更新它并在新创建的MyRequest对象中设置它。 When I try to persist the MyRequest object it gives me the PersistentObjectException.
当我尝试持久化MyRequest对象时,它会给我PersistentObjectException。 Please let me know if any other information is required.
如果需要任何其他信息,请告诉我。
Fixed by calling Merge on the transient MyRequest instance. 通过在瞬态MyRequest实例上调用Merge来修复。
Before: 之前:
mrh.persist(mr);
After: 后:
mrh.merge(mr);
Please let me know if there are any drawbacks in doing in this way. 如果这样做有任何缺点,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.