Code:
public class B {
private A a1;
private A a2;
public void setA1(A a) { this.a1 = a; }
public void setA2(A a) { this.a2 = a; }
}
I fetch an instance of class A with id of 1 from a hibernate session then close the session. I store the fetched instance of class A to a variable named aFromFirstSession.
I open a new session and retrieve an instance of class B whose a1 references the same record (id of 1) that was fetched in my first hibernate session and a2 is null and close the session.
I then call setA2 passing aFromFirstSession, open a hibernate session and call saveOrUpdate on b.
This give a NonUniqueObjectException. This makes sense, because b is referencing two seperate instances that represent the same record (id of 1) since they were retrieved in seperate hibernate sessions.
I thought I could solve this by turning on the second-level cache for class A. With this approach, the instance will be the same across the multiple hibernate sessions because it is being retrieved from the second-level cache.
I still get the NonUniqueObjectException on the saveOrUpdate even though the log says that it was retrieved from the second-level cache.
Am I correct to think that if the instance is retrieved from the second-level cache I shouldn't get the NonUniqueObjectException in the above scenario?