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.
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).
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.
Entities only become detached when you finally close the EntityManager (or when they are serialized).
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.
To check if the given entity is managed by the current PersistenceContext
you can use the EntityManager#contains(Object entity)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With