Automatic state detection by R4R Team

Hibernate users have requested a general purpose method that either saves a transient instance by generating a new identifier or updates/reattaches the detached instances associated with its current identifier. Int the Hibernate we saw the saveOrUpdate() method implements this functionality.

// When we make to the first session
Student student = (Student) firstSession.load(Student.class, studentID);

// When we go through the higher tier of the application
Student mate = new Student();
student.setMate(mate);

// When we found later, in a new session
secondSession.saveOrUpdate(student);   // update existing state (student has a non-null id)
secondSession.saveOrUpdate(mate);  // save the new instance (mate has a null id)

In the Hibernate when the usage and semantics of saveOrUpdate() seems to be confusing for new users. Firstly, so long as you are not trying to use instances from one session in another new session, you should not need to use update(), saveOrUpdate(), or merge(). Some whole applications will never use either of these methods.

Basically we found the update() or saveOrUpdate() are used in the following scenario:

1. the application loads an object in the first session

2. the object is passed up to the UI tier

3. some modifications are made to the object

4. the object is passed back down to the business logic tier

5. the application persists these modifications by calling update() in a second session

6. saveOrUpdate() does the following:

a. if the object is already persistent in this session, do nothing

b. if another object associated with the session has the same identifier, throw an exception

c. if the object has no identifier property, save() it

d. if the object's identifier has the value assigned to a newly instantiated object, save() it

e. if the object is versioned by a <version> or <timestamp>, and the version property value is the same value assigned to a newly instantiated object, save() it

f. otherwise update() the object

g. and merge() is very different:

(i). if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance

(j). if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent insUsuallytance

(k). the persistent instance is returned

(l).the given instance does not become associated with the session, it remains detached
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!