Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...