Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out whether an entity is detached in JPA / Hibernate?

Is there a way to query the JPA EntityManager whether a given entity is detached? This SO post is discussing a similar issue but does not indicate a way to query the JPA EntityManager on the detachment status of an entity. I would prefer a JPA way, otherwise Hibernate-specific.

like image 840
Marcus Junius Brutus Avatar asked Oct 30 '12 08:10

Marcus Junius Brutus


People also ask

What is detached entity in JPA?

A detached entity (a.k.a. a detached object) is an object that has the same ID as an entity in the persistence store but that is no longer part of a persistence context (the scope of an EntityManager session).

What is detached entity 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.

How does an entity become detached?

Entities only become detached when you finally close the EntityManager (or when they are serialized).

Can we have an entity without @ID JPA?

If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.


1 Answers

To check if the given entity is managed by the current PersistenceContext you can use the EntityManager#contains(Object entity).

like image 163
Piotr Nowicki Avatar answered Oct 15 '22 13:10

Piotr Nowicki