Show Table of Contents
10.2. Making objects persistent
Newly instantiated instances of a persistent class are considered transient by Hibernate. We can make a transient instance persistent by associating it with a session:
DomesticCat fritz = new DomesticCat(); fritz.setColor(Color.GINGER); fritz.setSex('M'); fritz.setName("Fritz"); Long generatedId = (Long) sess.save(fritz);
Cathas a generated identifier, the identifier is generated and assigned to the
save()is called. If
assignedidentifier, or a composite key, the identifier should be assigned to the
catinstance before calling
save(). You can also use
save(), with the semantics defined in the EJB3 early draft.
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
INSERTstatement 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 ( e.g. "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.
Alternatively, you can assign the identifier using an overloaded version of
DomesticCat pk = new DomesticCat(); pk.setColor(Color.TABBY); pk.setSex('F'); pk.setName("PK"); pk.setKittens( new HashSet() ); pk.addKitten(fritz);
If the object you make persistent has associated objects (e.g. the
kittenscollection in the previous example), these objects can be made persistent in any order you like unless you have a
NOT NULLconstraint upon a foreign key column. There is never a risk of violating foreign key constraints. However, you might violate a
NOT NULLconstraint 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 NULLconstraint violations do not occur - Hibernate will take care of everything. Transitive persistence is discussed later in this chapter.