我尝试了线程中提到的许多事情。但是似乎没有人能解决我的问题。请告诉我我要去哪里了。
楷模
@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;
}
在我的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.
首先,我从数据库中获取MySession对象,对其进行更新并将其设置在新创建的MyRequest对象中。当我尝试保留MyRequest对象时,它给了我PersistentObjectException。请让我知道是否需要其他信息。
最佳答案
通过在瞬时MyRequest实例上调用Merge进行修复。
之前:
mrh.persist(mr);
后:
mrh.merge(mr);
如果这样做有任何弊端,请告诉我。
关于java - Hibernate:org.hibernate.PersistentObjectException:分离的实体传递给持久化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14659332/