Zulfi
Zulfi

Reputation: 586

How hibernate internally determines whether an object is in detached state

I have been looking around and searching to understand how hibernate internally determines whether an object is detached . Tried to see the code of hibernates but am not able to figure it out. Have seen some thread in stackoverflow but all of them talks about how we can determine in a program whether an object is detached or not.But what i am trying to understand is how does hibernate internally identifies a detached object.What is the algorithm behind the scene which does this identification??

Upvotes: 2

Views: 241

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

Of course, if the entity is managed (i.e. is attached to the current session, then it's not detached). The key part is to make the distinction between transient (i.e. entity instances which are not managed, and which don't exist in the database yet), and detached entities (i.e. entities which are not managed, but which are supposed to exist already in the database).

The main part of the algorithm to determine if an entity is detached or transient is in AbstractEntityPersister.isTransient().

Basically, if it has a null identifier, or a null optimistic-lock version attribute (i.e. attribute annotated with @Version), then it's considered transient.

There are other subtleties, but if you use auto-generated identifiers, and the identifier is not null, then Hibernate considers it as a detached entity. If you use assigned identifier, then it needs to check the database (unless you also have a version attribute). That is another good reason to use auto-generated identifiers.

Upvotes: 5

Related Questions