Is there a more elegant way of avoiding javax.persistence.EntityNotFoundException
when calling EntityManager.remove()
on an object that may or may not currently exist in persistent state? I am trying to avoid a situation where I need to make 2 queries to remove an object. Currently I am cheating with:
void remove(String id) {
T model = entityManager.getReference(type, id);
开发者_运维技巧 entityManager.remove(model);
}
But this will throw an exception if the model does not exist.
I could:
void remove(String id) {
T model = retrieve(id);
if(model != null)
entityManager.remove(model);
}
But that would involve 2 queries (setting aside the notion of a cache for now).
The only possibility is to use a Query with a DELETE and a WHERE clause. Works fine, EXCEPT that JPA will not call any @PreDelete or @PostDelete operations on the object to delete. I assume you don't want that anyway, so go with the Query. If you want to call the listeners, the object (obviously) has to be loaded prior deletion.
You can do a select count(*) from ENTITY where id = :id
before remove you entity and then check if the entity exists in database. So you can remove without exception. If you are using a generic DAO with common methods like find()
, persist()
, remove()
... you can add the count(*)
query in remove()
method.
Hope it helps.
精彩评论