Making objects persistent by R4R Team

In the Hibernate when we found the Newly instantiated instances of a persistent class that considered transient. We can make a transient instance persistent by associating it with a session:

DomesticStudent stud = new DomesticStudnet();
Long generatedId = (Long);

If Student has a generated identifier,then the identifier is generated and assigned to the student when save() is called. If Student has an assigned identifier, or a composite key, the identifier should be assigned to the student instance before calling save(). Then we can can also use persist() instead of save(), with the semantics defined in the EJB3 early draft.

Here we need to follow the some basic rules which is given below:

The persist() makes a transient instance persistent. However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

save() does guarantee to return an identifier. If an INSERT has to be executed to get the identifier 
( "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is problematic in a long-running conversation with an extended Session/persistence context. Otherwise we need to assign the identifier using an overloaded version of save().

DomesticStudent pk = new DomesticStudent();
pk.setKittens( new HashSet() );
pk.addKitten(fritz); pk, new Long(1234) );

If the object you make persistent has associated objects (like the kittens collection in the previous example), these objects can be made persistent in any order you like unless you have a NOT NULL constraint upon a foreign key column. There is never a risk of violating foreign key constraints. However, you might violate a NOT NULL constraint if you save() the objects in the wrong order.

Usually you do not bother with this detail, as you will normally use Hibernate's transitive persistence feature to save the associated objects automatically. Then, even NOT NULL constraint violations do not occur - Hibernate will take care of everything
Leave a Comment:
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on 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!