GionJh
GionJh

Reputation: 2894

jpa: detached vs transient definitions

In JPA:
is an instance of an Entity class with ID set considered detached even if it'has been just created ?

or similarly:

is an instance of an Entity class with ID not set always considered transient ?

I ask this beacause often jpa methods have different behaviour in the two cases.

Upvotes: 4

Views: 1240

Answers (1)

Ondro Mihályi
Ondro Mihályi

Reputation: 7710

The difference between transient and detached state is not determined by the entity itself. Given an instance of entity, it is not always possible to be 100% sure if it is transient or detached. The difference is only logical - entity instance is detached by definition when it was previously attached to a persistence context. It also means that there is a corresponding record in the backing database.

On the other hand, answer to the second question is yes - entity without an ID has not yet been persisted (attached), therefore it must be still transient. This is the only situation, when you can be sure about the state. As detached entity corresponds to a record in database, and because id is mandatory for persisted entities in JPA, detached entity must have id (either assigned in your code or assigned automatically by JPA provider).

Here is a thorough explanation of entity lifecycle states and valid actions which make transitions between the states: Entity lifecycle management

Despite the fact that entity is considered detached only when previously attached, it is possible to create a fake detached entity without being attached before. But this is mostly a hack and not supported by the spec. For most cases, it is enough to set a correct id. However, if you also use @Version column for optimistic locking, you must set the correct value for this column also. And it might happen, that you still get into some trouble, if you use other non-standard mechanisms of JPA providers.

Upvotes: 3

Related Questions