I have used a delete method of Spring Data JPA
in the service layer, but I wonder why neither the deleteById
method nor delete
method has any return values.
If we inspect the implementation of the delete method carefully, there is an if statement that when the entity to be deleted doesn't exist returns nothing.
public void delete(T entity) {
Assert.notNull(entity, "Entity must not be null!");
if (entityInformation.isNew(entity)) {
return;
}
Class<?> type = ProxyUtils.getUserClass(entity);
T existing = (T) em.find(type, entityInformation.getId(entity));
// if the entity to be deleted doesn't exist, delete is a NOOP
if (existing == null) {
return;
}
em.remove(em.contains(entity) ? entity : em.merge(entity));
}
Personally, I think returning a Boolean
value could be an adequate approach in this case because the controller layer will know about the deletion status, and the view layer can be provided with the far more reliable alert message.
delete
then everything is OK. Remember that you are operating JPQL not SQL. What reliable information do you expect?Query.executeUpdate():int
/+ catch exceptions:) ..this returns (reliably) the count of modified/updated/deleted rows.