Sometimes it’s quite difficult (or a performance problem) to clean delete all references to an entity.
For example, I’ve got a Person object which has relationships to another Person objects.
When I delete a Person, I don’t want to delete this Person in all relations she can have simply because sometimes this Person object does not know where it is referenced. So, if I would like to clean delete all references, I must do extra sql work that can result in performance problem.
In an ideal world, I would like to delete the Person object and when another Person do a reference to this Person (because it has its id in its relations), simply return null.
The fact is JPA complains that
javax.persistence.EntityNotFoundException: No row with the given identifier exists
Is there a way to force JPA to return a null reference and not an exception in this case ?
You can use the @NotFound annotation with the value
NotFoundAction.IGNORE, which will return null if an associated entity doesn’t exist.A word of caution: if you use this in a collections and hibernate doesn’t find one of the entries, it will add a null value in the collection, which is very annoying. To avoid this, you can wrap the collection in a Collection that skips nulls.