I would like to know what's the real difference between em.detach(entity)
, em.remove(entity)
and using a JPQL
request like :
em.createQuery("DELETE FROM Country").exceuteUpdate();
thanks.
detach. Remove the given entity from the persistence context, causing a managed entity to become detached. Unflushed changes made to the entity if any (including removal of the entity), will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it.
If A is a detached entity, its state is copied into existing managed instance A' of the same entity identity, or a new managed copy of A is created. If A is a new entity, a new managed entity A' is created and the state of A is copied into A' . If A is an existing managed entity, it is ignored.
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).
void detach(java.lang.Object entity)
Remove the given entity from the persistence context, causing a managed entity to become detached. Unflushed changes made to the entity if any (including removal of the entity), will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it.
void remove(java.lang.Object entity)
Remove the entity instance. The database is affected right away.
em.createQuery("DELETE FROM Country").exceuteUpdate();
Does the Delete directly to database, if you have that object, for example, saved in any list or it is a simple referenced object, it wont get the changes, and surely raise an error if you try to merge, or do something with that. Trust me, don't do a delete like this, unless it is your last choice.
Hope this to be a clear answer!
Best regards!
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