简体   繁体   中英

Hibernate Cascade DELETE OneToMany does not work. Referential integrity constraint violation

I have a class Webtoon that contains a list of Episode. It is a one direction relation.

@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@CollectionTable(name= "list_of_episodes")
List<Episode> listOfEpisodes = new ArrayList<>();

In my Unit test, I created a Webtoon object, then added an episode in the list listOfEpisodes. When I try to delete the Episode using the Episode repository

this.episodeRepo.delete(episode);

I got the error :

violation de contrainte: "FK50GHKTDAXMN68TBU6KAYVUX9S: PUBLIC.LIST_OF_EPISODES FOREIGN KEY(LIST_OF_EPISODES_ID) REFERENCES PUBLIC.EPISODE(ID) (3)" Referential integrity constraint violation: "FK50GHKTDAXMN68TBU6KAYVUX9S: PUBLIC.LIST_OF_EPISODES FOREIGN KEY(LIST_OF_EPISODES_ID) REFERENCES PUBLIC.EPISODE(ID) (3)"; SQL statement: delete from episode where id=? [23503-200]

Why hibernate can't remove this object and update the list in Webtoon class ?

尝试将 FetchType 从 EAGER 更改为 LAZY

Referential integrity is a property of data stating that all its references are valid. In the context of relational databases, it requires that if a value of one attribute (column) of a relation (table) references a value of another attribute (either in the same or a different relation), then the referenced value must exist.

From the error PUBLIC.LIST_OF_EPISODES FOREIGN KEY(LIST_OF_EPISODES_ID) REFERENCES PUBLIC.EPISODE(ID) you can clearly see that PUBLIC.EPISODE(ID) is referenced as a foreign key in PUBLIC.LIST_OF_EPISODES table so you cannot delete a parent unless you delete a child element.

Try using @JoinColumn instead of using @CollectionTable(name= "list_of_episodes")

To correct this issue, I first changed the uni-directional relation to bi-directional. In Webtoon I have :

@OneToMany(cascade = CascadeType.ALL, mappedBy="webtoon", orphanRemoval = true)
@CollectionTable(name= "list_of_episodes")
List<Episode> listOfEpisodes = new ArrayList<>();

In Episode, I added a webtoon attribute

@ManyToOne(fetch= FetchType.LAZY)
@JoinColumn(name="webtoon_id")
Webtoon webtoon;

Because, it is lazy...I could not get the list as if I'm using eager, so I added a join select in my repository. And also when I delete, I have the cascade delete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM