EhmKah EhmKah - 6 months ago 17
Java Question

How to I tell a Springdata-repository's delete method to not throw an exception if an entity does not exists?

I am using SpringData's repository. If I try to delete an entity via an ID which does not exist or never existed it throws an exception. Since I do not want to check whether the entity exists before I delete it, it would be nice that it would fail silently. It would make it easier because the observable behavior is the same - after the call the entity does not exists anymore. Whether it has been deleted or never existed, I do not care.

Is there a way to modify default behavior of

so it won't throw an exception, if entity does not exsist?

Documentation of SpringData's delete says that it will throw an exception if an entity does not exist.


JavaDocs says that an IllegalArgumentException will be thrown if the provided argument (id, entity, Iterable<T>) is null and not if entity does not exsits.

If you need to avoid the IllegalArgumentException you could implement a custom delete method that checks id != null:

public void customDelete(ID id) {
    if(id != null){

Take a look to this docs section if you don't know how to add "Custom implementations for Spring Data repositories"