0

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:

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. When I try to persist the MyRequest object it gives me the PersistentObjectException. Please let me know if any other information is required.

Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
  • See http://stackoverflow.com/questions/2441598/detached-entity-passed-to-persist-error-with-jpa-ejb-code and http://stackoverflow.com/questions/6378526/org-hibernate-persistentobjectexception-detached-entity-passed-to-persist – Vadzim Dec 01 '13 at 13:15

1 Answers1

2

Fixed by calling Merge on the transient MyRequest instance.

Before:

mrh.persist(mr);

After:

mrh.merge(mr);

Please let me know if there are any drawbacks in doing in this way.

Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62