Hi,
Hibernate encourages to write custom equals() and hashCode() methods, not based on the id (see
https://www.hibernate.org/109.html);
I can understand why, but it comes in conflict in the following scenario.
1) Suppose my DAO has a saveOrUpdate() method. As is its now, I just delegate to the hibernate's Session.saveOrUpdate().
So far, no problem.
2) suppose now a service that uses this dao. It has a method that takes a detached entity (changed) as argument (let's call this instance now instance A). The service call does first some checks and queries for checking existence, etc,. doing this, it loads also the persistent instance, whith the same Identifier as instance A.
3) the service wants to saveOrUpdate the instance A via the dao, but the doa gets an exception since there is 'already an object with the same identifier in the session'.
4) A solution would indeed be to use merge() instead of saveOrUpdate().
5) But, I want to use saveOrUpdate() when the object is not in the session, and use merge() when it IS in the session.
6) I thought I could use the Session.contains() method for this, but here comes the problem. Since the entity's equals() and hashCode() are implemented, using 'business fields' (as Hibernate encourages), the contains() returns always false. So, there is no way to see of an object is already in the session or not.
I would think a method like Session.contains(Class, Serializable id) would solve this, but unfortunately, this method does not exist..
Am I seeing this completely wrong, or is there a workaround for this?
Thanks!