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 ?
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.
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.
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.
Although using Lombok to generate boilerplate code for entities is attractive, it does not work well with JPA and Hibernate entities.
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.
No, at least nothing standard (JPA)
But you can control what happens with these association using the cascade
attribute ot @*ToMany
and @*ToOne
annotations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With