Damian
Damian

Reputation: 3050

How does JPA know that entity is new or detached?

If entity is deleted or managed it is stored (or its hash) in current EntityManger's persistence context, so JPA know about its state. But how JPA implementation can get to know that given entity is new or detached? Checking if @ID is null will not always work. Is it JPA provider specific? In other words how JPA know that it need to throw javax.persistence.EntityExistsException during merging?

Upvotes: 1

Views: 1120

Answers (1)

JB Nizet
JB Nizet

Reputation: 692131

Here's how Hibernate does it:

  • if the identifier is generated, use the presence of the identifier
  • if not, and the entity is versioned (for optimistic locking), use the timestamp or version
  • if the above is not possible, query the second-level cache or the database to know if the identifier already exists or not.

Upvotes: 2

Related Questions