Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bypass "Entity not found" error with JPA

Tags:

hibernate

jpa

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 ?

like image 871
Jerome Cance Avatar asked Aug 22 '11 10:08

Jerome Cance


People also ask

How do I fix entity not found exception?

Combining @NotFound(action = NotFoundAction. IGNORE) with @ManyToOne annotation will stop the persistence provider from throwing the EntityNotFoundException, but we'll have to handle missing entity by hand to avoid NullPointerException.

Can we have an entity without @ID JPA?

If your object does not have an id, but its table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

Does JPA use getters?

If you use property-based access, you need to annotate the getter methods of your entity attributes with the required mapping annotations. Your JPA implementation then calls the getter and setter methods to access your entity attributes.

Does Lombok work with JPA?

Although using Lombok to generate boilerplate code for entities is attractive, it does not work well with JPA and Hibernate entities.


2 Answers

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.

like image 180
Augusto Avatar answered Oct 05 '22 22:10

Augusto


No, at least nothing standard (JPA)

But you can control what happens with these association using the cascade attribute ot @*ToMany and @*ToOne annotations.

like image 20
Bozho Avatar answered Oct 05 '22 22:10

Bozho