Posts

Showing posts with the label Hibernate

Transient, Persistent and Detached Objects.

A new  instance of a a persistent class which is not associated with a Session , has no representation in the database and no identifier value is considered  transient  by Hibernate: Person person = new Person(); person.setName("Foobar"); // person is in a transient state A  persistent  instance has a representation in the database, an identifier value and is associated with a session . You can make a transient instance  persistent  by associating it with a Session : Long id = (Long) session.save(person); // person is now in a persistent state Now, if we close  the Hibernate session , the persistent instance will become a  detached  instance: it isn't attached to a Session  anymore (but can still be modified and reattached to a new Session later  though). All this is clearly explained is the whole  Chapter 10. Working with objects  of the Hibernate documentation . Definitely a must read. Sourc...

Hibernate Merge and Persist

Persist and merge are for two different purposes (they aren't alternatives at all). (edited to expand differences information) persist : Insert a new register to the database Attach the object to the entity manager. merge : Find an attached object with the same id and update it. If exists update and return the already attached object. If doesn't exist insert the new register to the database. persist() efficiency: It could be more efficient for inserting a new register to a database than merge(). It doesn't duplicates the original object. persist() semantics: It makes sure that you are inserting and not updating by mistake. Example: {     AnyEntity newEntity;     AnyEntity nonAttachedEntity;     AnyEntity attachedEntity;     // Create a new entity and persist it             newEntity = new AnyEntity();     em.persist(newEntity);     // Save 1 to the database at ...