Hibernate无法删除子进程(MySQLIntegrityConstraintViolationException)

时间:2016-02-10 12:37:20

标签: hibernate

我有3个Java Hibernate个实体。 User具有oneToMany实体的单向Filter实现FiltermanyToOne实体与Model实体具有单向Filter关系。我只想删除MySQLIntegrityConstraintViolationException个实体,但获取gecars

  

无法删除或更新父行:外键约束失败(users_filtersFK_oymjo03tkarckpfjfmaak99lj,CONSTRAINT filters_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(), "");
    }
}

1 个答案:

答案 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不会导致外键冲突。