Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Saturday

JPA(Java Persistence API) Tutorial-How to delete an entity with relationships

How to delete an entity with relationships. Clarify
which relationships are raising the exception

When an entity is deleted from the database a constraint error may appear, something
like:“java.sql.SQLIntegrityConstraintViolationException”. This error might happen if we try to delete a Person entity that
is related to a Car entity and the CascadeType.REMOVE is not defined for the specific association (see the last

chapter about Cascade definition).

In order to perform the removal of the Person entity we could do:
•CascadeType.REMOVE => Once the entity is deleted its child entity (Car) will be deleted too.
Check the previous section to see how to do it.
•OrphanRemoval => Can be applied but have a different behavior than CascadeType.REMOVE.
Check the last chapter to see how to do it.
•Set the relationship to null before excluding it:
person.setCar(null);
entityManager.remove(person);
Unfortunately locating the actual entity that is the cause of the specific exception is not straightforward at all. What
can be done is catch the class name displayed in the error message of the exception and go on from there. This
solution is not accurate because the error message is a String with a long text containing the database table name.
Nevertheless this message may change by each distinct JPA implementation, JDBC driver, local database
language etc.

NEXT

No comments:

Post a Comment