I tried below code:
Student s1 = (Student) s.load(Student.class, 5); // this records not there in DB
try {
s1.setName("Kaushik1");
} catch (ObjectNotFoundException e) {
s1 = new Student();
s1.setId(5);
s1.setName("trying1");
}
s.saveOrUpdate(s1);
Student s2 = (Student) s.load(Student.class, 5);
try {
s2.setName("Kaushik2");
} catch (ObjectNotFoundException e) {
//Why should it throw ObjectNotFoundException now
s2 = new Student();
s2.setId(5);
s2.setName("trying2");
}
s.saveOrUpdate(s2); //Why it throws NonUniqueObjectException
I used load to fetch record from DB with ID#5. Record does not exist. Then I tried calling setter on object, and it threw an exception. Agreed !!
Since the record did not exist I created a new object and called saveOrUpdate(). So now I assume that object with ID#5 is in session cache.
Now I try again to call load() method for ID#5 and call its setter. It throws ObjectNotFoundException again.
Question 1
Why it can not pick record from Session cache ?
When I create new object and try to call saveOrUpdate() it gives a NonUniqueObjectException
org.hibernate.NonUniqueObjectException: a different object with the
same identifier value was already associated with the session:
[com.cts.closr.Student#5]
It threw ObjectNotFoundException and now says “object already associated with the session”. Is that not contradictory?
Question 2
Does that mean load() method never checks the session context? It always fetches from DB?
Then in such case I must use get() method?
The documentation says:
So using
Session.load(), catching an exception, and continuing using the session is a big no-no.Session.load()must be used when you consider that the object MUST exist in the database, and an exception must be thrown if it doesn’t. If you’re not sure that the object exists, useSession.get(), test if the returned object is null, and act accordingly.