What is the proper way to re-attach detached objects in Hibernate?

I have a situation in which I need to re-attach detached objects to a hibernate session, although an object of the same identity MAY already exist in the session, which will cause errors.

Right now, I can do one of two things.

  1. getHibernateTemplate().update( obj )
    This works if and only if an object doesn’t already exist in the hibernate session. Exceptions are thrown stating an object with the given identifier already exists in the session when I need it later.

  2. getHibernateTemplate().merge( obj )
    This works if and only if an object exists in the hibernate session. Exceptions are thrown when I need the object to be in a session later if I use this.

Given these two scenarios, how can I generically attach sessions to objects? I don’t want to use exceptions to control the flow of this problem’s solution, as there must be a more elegant solution…

17 Answers
17

Leave a Comment