Hibernate cascading delete issues

This question has been asked many times before, but since then I have not found a satisfactory answer, so I ask it again.

Imagine the following situation:

public class User { ... @Cascade(value= {CascadeType.DELETE}) @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name="followerId") public List<LocationFollower> followedLocations; ... } public class LocationFollower { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false) public Long id; @ManyToOne @JoinColumn(name="locationId") public Location followedLocation; @ManyToOne @JoinColumn(name="followerId") public User follower; @Column(name = "followerSince") public Timestamp followerSince; } public class Location { ... @Cascade(value = {CascadeType.DELETE}) @OneToMany(fetch= FetchType.LAZY) @JoinColumn(name="locationId") public List<LocationFollower> followers; ... } 

All I wanted to do was delete the user. Logically, it is assumed that all related "follower" entries connecting the user and location will be deleted. The same assumption should remain valid if I delete the location record.

In fact, it happens that Hibernate is trying to update (?!?) The table containing the followers, and since the related object (User or location) was sent for deletion, it tries to set a foreign key, for example followerId with a zero value. This throws an exception and splits all subsequent operations.

The error I get: An unhandled failure occurred on the server. Failed to perform JDBC batch update; SQL [update locationstofollowers set followerId = null, where followerId =?]; restriction [null]; The nested exception is org.hibernate.exception.ConstraintViolationException: Failed to perform JDBC batch update

PS I heard that there is another version of the DELETE_ORPHAN cascade. It seems outdated, and although I tried it, the effect was the same.

+7
source share
2 answers

Since you did bidirectional mapping, you need to remove the object from both places. This should work:

 user.followedLocations.remove(aLocation); session.update(user); session.delete(aLocation); 
+1
source

You must set @JoinColumn (name = "followerId", insertable = false, updatable = false)

0
source

All Articles