gpt4 book ai didi

java - Hibernate hsql 删除的 MySQLIntegrityConstraintViolationException。无法删除或更新父行

转载 作者:行者123 更新时间:2023-11-29 21:15:17 24 4
gpt4 key购买 nike

我有家长 Filter实体和一个方向List<Ad>ads作为 @OneToMany 的 child 关系。我尝试使用 Hibernate hql 删除超过一周的广告查询但得到:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (gecars.filters_ads, CONSTRAINT FK_gcri6h0918u8o2ybd6yfquk79 FOREIGN KEY (ads_id) REFERENCES ads (id))

用户:

@Entity
@Table(name="users")
public class User {
...
@OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="user")
@OrderBy("id")
private Set<Filter> filters = new HashSet<Filter>(0);
...

过滤器:

@Entity
@Table(name="filters")
public class Filter {
...
// I also tried use @OneToMany(CascadeType.REMOVE, orphanremoval=true)
// or @OneToMany(cascade=CascadeType.ALL,orphanRemoval=true)
@OneToMany
private Set<Ad> ads;
...

广告:

@Entity
@Table(name="ads")
public class Ad {
...
private Date insertTime = new Date();
...

DAO删除方法:

public void deleteOldAds(Date date){
String hql = "delete from Ad where insertTime < :date";
session.createQuery(hql).setParameter("date", date).executeUpdate();
}

最佳答案

问题的原因是,如果 @OneToMany 关联方是关系的所有者,则使用联接表。

要指定使用 ads 表中的联接列(外键)而不是单独的联接表进行关联,只需将关联映射到 @JoinColumn:

@OneToMany
@JoinColumn
private Set<Ad> ads;

关于java - Hibernate hsql 删除的 MySQLIntegrityConstraintViolationException。无法删除或更新父行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36003389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com