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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.