Modifying detached objects by R4R Team

When we use the Hibernate that time we found the many applications need to retrieve an object in one transaction, send it to the UI layer for manipulation, then save the changes in a new transaction. Applications that use this kind of approach in a high-concurrency environment usually use versioned data to ensure isolation for the "long" unit of work.

Hibernate supports this model by providing for reattachment of detached instances using the Session.update() or Session.merge() methods:

// When we go through the first session
Student student = (Student) firstSession.load(Student.class, studentId);
Student potentialMate = new Student();
firstSession.save(potentialMate);

// We found in a higher layer of the application
student.setMate(potentialMate);

// and then the later, in a new session
secondSession.update(student);  // update student
secondSession.update(mate); // update mate

In the given code as we do the Student with identifier studentId had already been loaded by secondSession when the application tried to reattach it, an exception would have been thrown.

So we can Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. Use merge() if you want to merge your modifications at any time without consideration of the state of the session. In other words, update() is usually the first method you would call in a fresh session, ensuring that the reattachment of your detached instances is the first operation that is executed.

So at that time the application should individually update() detached instances that are reachable from the given detached instance only if it wants their state to be updated. 

So The lock() method also allows an application to reassociate an object with a new session. However, the detached instance has to be unmodified.

//just reassociate:
sess.lock(fritz, LockMode.NONE);

//do a version check, then reassociate:
sess.lock(izi, LockMode.READ);

//do a version check, using SELECT ... FOR UPDATE, then reassociate:
sess.lock(pk, LockMode.UPGRADE);

Note that lock() can be used with various LockModes. See the API documentation and the chapter on transaction handling for more information. Reattachment is not the only usecase for lock().
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!