MySQLIntegrityConstraintViolationException用于Hibernate hsql的删除。无法删除或更新父行 [英] MySQLIntegrityConstraintViolationException for Hibernate hsql delete. Cannot delete or update a parent row
问题描述
我有父母过滤器
实体和一个方向列出< Ad>广告
作为 @OneToMany
关系。我尝试使用Hibernate hql
查询删除超过一周大的广告,但得到:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法删除或更新父行:外键约束失败(
gecars
。filters_ads
,CONSTRAINTFK_gcri6h0918u8o2ybd6yfquk79
FOREIGN KEY(ads_id
)参考文献ads
用户: / p>
@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 {
...
//我也尝试使用@OneToMany(CascadeType.REMOVE,orphanremoval = true)
//或@OneToMany(cascade = CascadeType.ALL,orphanRemoval = true)
@OneToMany
private Set< Ad>广告;
...
广告:
@Entity
@Table(name =ads)
public class Ad {
...
private日期insertTime =新日期();
...
DAO删除方法:
public void deleteOldAds(日期日期){
String hql =从插入时间<:date;
session.createQuery(hql).setParameter(date,date).executeUpdate();
}
解决方案如果
@OneToMany
关联侧是关系的所有者,则使用连接表。
要指定a
ads
表中的连接列(外键)用于关联而不是单独的连接表,只需将关联与@JoinColumn
:@OneToMany
@JoinColumn
私人设定< Ad>广告;
I have parent
Filter
entity and one directionList<Ad>ads
as children with@OneToMany
relation. I try delete ads where is more then one week old using Hibernatehql
query but get:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (
gecars
.filters_ads
, CONSTRAINTFK_gcri6h0918u8o2ybd6yfquk79
FOREIGN KEY (ads_id
) REFERENCESads
(id
))User:
@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); ...
Filter:
@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; ...
Ad:
@Entity @Table(name="ads") public class Ad { ... private Date insertTime = new Date(); ...
DAO delete method:
public void deleteOldAds(Date date){ String hql = "delete from Ad where insertTime < :date"; session.createQuery(hql).setParameter("date", date).executeUpdate(); }
解决方案The cause of the issue is that a join table is used if
@OneToMany
association side is the owner of the relationship.To specify that a join column (foreign key) in the
ads
table is used for the association instead of a separate join table, simply map the association with a@JoinColumn
:@OneToMany @JoinColumn private Set<Ad> ads;
这篇关于MySQLIntegrityConstraintViolationException用于Hibernate hsql的删除。无法删除或更新父行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!