我有3个Java
Hibernate
个实体。 User
具有oneToMany
实体的单向Filter
实现Filter
。 manyToOne
实体与Model
实体具有单向Filter
关系。我只想删除MySQLIntegrityConstraintViolationException
个实体,但获取gecars
。
无法删除或更新父行:外键约束失败(
users_filters
。FK_oymjo03tkarckpfjfmaak99lj
,CONSTRAINTfilters_id
FOREIGN KEY(filters
)参考id
(@Entity @Table(name="users") public class User { ... //@OneToMany(fetch = FetchType.LAZY) // old @OneToMany(fetch = FetchType.LAZY,cascade=CascadeType.ALL) //edited but exception still occurs private Set<Filter> filters = new HashSet<Filter>(0);
))
用户:
@Entity
@Table(name="filters")
public class Filter {
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_model")
private Model model;
...
过滤器:
public void deleteFilter(int filterId){
String hql = "delete from Filter where id= :filterId";
session.createQuery(hql).setInteger("filterId", filterId).executeUpdate();
}
DAO类中的删除方法:
session.delete
或public void deleteFilter(int filterId){
try {
session.beginTransaction();
session.delete(getFilter(filterId));
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
:
final XSDResourceImpl rsrc = new XSDResourceImpl(URI.createFileURI(xsdFileWithPath));
rsrc.load(new HashMap());
final XSDSchema schema = rsrc.getSchema();
for (Object content : schema.getContents())
{
if (content instanceof XSDImport)
{
XSDImport xsdImport = (XSDImport) content;
xsdImport.resolveTypeDefinition(xsdImport.getNamespace(), "");
}
}
答案 0 :(得分:1)
您正在使用连接表进行一对多关联。我假设您已从映射中自动生成了架构,因此您可能没有意识到这一点。这样,当您通过批量Hibernate DML语句删除Filter
时,连接表中的记录将保留并导致外键约束违规。
最佳方法是在多方面定义连接列:
@Entity
@Table(name="filters")
public class Filter {
@ManyToOne
@JoinColumn(name = "user")
private User user;
}
@Entity
@Table(name="users")
public class User {
@OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.All, mappedBy="user")
private Set<Filter> filters = new HashSet<Filter>(0);
}
如果您不想使用双向关联,可以在User
实体中定义连接列:
@Entity
@Table(name="users")
public class User {
@OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.All)
@JoinColumn(name = "user")
private Set<Filter> filters = new HashSet<Filter>(0);
}
这样,连接列仍然在filters
表中,因此删除Filter
不会导致外键冲突。