Is it possible with JPA to automatically nullify children when deleting the parent?
I have a Model Class Device, with sync statistics attached to it. When I remove the device I still want to keep the statistics, so put the field device in the Statistics class to ‘null’.
@OneToMany (mappedBy = "device", fetch= FetchType.LAZY)
public List<Statistic> syncStats;
and
@ManyToOne (fetch= FetchType.LAZY)
public Device device;
Is there an automatic way of obtaining this effect or do I have to do it manually?
Currently I use:
@PreRemove
protected void removeLinkToStats() {
syncStats.clear();
}
but this still gives a “A javax.persistence.PersistenceException has been caught, org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update”
No. With JPA it is the application’s responsibility to keep sync. Your application should call business logic before removing the entity using JPA.
Of course there are multiple ways of doing so. Using annotations like PreRemove or PreDestroy or (my personal favorite) do your pre removal things in a business container wich calls your data access to remove the entity from the database.
Short example: