Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA and DAO implementation of delete operation

Tags:

java

jpa

dao

I'd 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've read quite a lot of articles about this and in almost every one of them it's similar to the first approach, which appears to me quite needless since it can be done without the need to retrieve the whole entity from the database (if it's not present in the persistence context) and then remove it. Is there something I am missing and the first approach is really better ?

like image 467
VaclavDedik Avatar asked Nov 13 '22 14:11

VaclavDedik


1 Answers

You could check whether the entity is managed by invoking

boolean isManaged = entityManager.contains( t );

If true simply call

entityManager.remove(t);

otherwise your second approach seems better since merging could cause more db activity due to eager loading (if configured). The javadoc on getReference says "Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, throws EntityNotFoundException when the instance state is first accessed. (The persistence provider runtime is permitted to throw EntityNotFoundException when getReference(java.lang.Class, java.lang.Object) is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open."

In short the entity has to be managed therfore, I would suggest:

em.remove(em.contains(r) ? r : em.merge(r));
like image 149
stacker Avatar answered Jan 04 '23 15:01

stacker