2013-02-02 83 views
0

我嘗試了很多在線程中提到的東西。但似乎沒有解決我的問題。請告訴我我哪裏錯了。Hibernate:org.hibernate.PersistentObjectException:傳遞給persist的分離實體

模式

@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。請讓我知道是否需要其他信息。

+0

請參閱http://stackoverflow.com/questions/2441598/detached-entity-passed-to-persist-error-with-jpa-ejb-code和http://stackoverflow.com/questions/6378526/org-休眠-persistentobjectexception獨立式-實體傳遞到堅持 – Vadzim

回答

2

通過在瞬態MyRequest實例上調用Merge來修復。

前:

mrh.persist(mr); 

後:

mrh.merge(mr); 

請讓我知道是否有這樣做的任何缺點。

相關問題