Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are detached, persistent and transient objects in hibernate?

What are detached, persistent and transient objects in hibernate? Please explain with an example.

like image 267
jmj Avatar asked Apr 04 '10 06:04

jmj


People also ask

What are detached objects in Hibernate?

A detached entity is just an ordinary entity POJO whose identity value corresponds to a database row. The difference from a managed entity is that it's not tracked anymore by any persistence context. An entity can become detached when the Session used to load it was closed, or when we call Session.

What is persistent object in Hibernate?

Persistent objects are instances of POJO classes that you create that represent rows in the table in the database. According to hibernate-doc an instance of POJO class representing table in database goes through 3 states of which persistent is one of them.

What is difference between persistent object and non persistent object?

Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object. A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.

What are the three types of Hibernate object states?

In the context of Hibernate's Session, objects can be in one of three possible states: transient, persistent, or detached.


1 Answers

A new instance of 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 in the whole Chapter 10. Working with objects of the Hibernate documentation that I'm only paraphrasing above. Definitely, a must-read.

like image 108
Pascal Thivent Avatar answered Oct 01 '22 00:10

Pascal Thivent