JPA and DAO implement delete operation

I would like to know which implementation of the remove method is better:

public void remove(T t) {
   entityManager.remove(entityManager.merge(t));
}

public void remove(PK pk) {
   entityManager.remove(entityManager.getReference(entityType, pk));
}

I have read quite a few articles about this, and in almost all of them it looks like the first approach, which seems completely useless to me, since it can be performed without having to extract the entire object from the database (if it is not present in the context of persistence), and then delete it. Is something missing for me, and is the first approach really better?

+5
source share
1 answer

You can check if the object is being controlled by calling

boolean isManaged = entityManager.contains( t );

If true, just call

entityManager.remove(t);

, db - ( ). javadoc getReference : " , . , EntityNotFoundException, . ( EntityNotFoundException, getReference (java.lang.Class, java.lang.Object). , , , ."

, , :

em.remove(em.contains(r) ? r : em.merge(r));
+1

All Articles