Entity not found bypass error with JPA

Sometimes it’s quite difficult (or a performance problem) to delete all references to an object.

For example, I have a Person object that is related to other Person objects.

When I delete a Person, I do not want to delete this Person in all respects that it may have simply because sometimes this Person object does not know what it refers to. Therefore, if I want to remove all links, I have to do additional sql work, which can lead to performance problems.

In an ideal world, I would like to remove the Person object, and when another person made a reference to this Person (because it has its id in its relationship), just return null.

The fact is that the 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?

+6
source share
3 answers

You can use the @NotFound annotation with a value of NotFoundAction.IGNORE , which will return null if the associated object does not exist.

Warning: if you use this in collections, and hibernation does not find one of the entries, it will add a zero value to the collection, which is very annoying. To avoid this, you can wrap a collection in a collection that skips zeros.

+16
source

There is at least nothing standard (JPA)

But you can control what happens with these associations using the cascade attributes from @*ToMany and @*ToOne annotations.

+5
source

You use @NotFound (action = NotFoundAction.IGNORE) this will skip null objects. BUT (as Augusto said), if you use, for example, Primfaces Datatable and get 10 lines and missed 2, due to @NotFound (action = NotFoundAction.IGNORE) in your property, you will have 10 lines, not 8 (actually ghost lines).

 @NotFound(action=NotFoundAction.IGNORE) private Product p; 
0
source

Source: https://habr.com/ru/post/895579/


All Articles