hibernate一对多删除列表

时间:2014-10-14 13:46:53

标签: java hibernate jpa

我有两个实体与oneToMany关联:

@Entity
@Table(name="FATHER")
@Audited(withModifiedFlag=true)
@XmlType
public class Father{

    @Column(name="FATHER_ID")
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "father", orphanRemoval = true, cascade =     {CascadeType.ALL})
    List<Son> childrens;
    //getter and setter for id, only getter for childrens.
}

@Table(name="CHILDREN")
@Entity
@Audited(withModifiedFlag=true)
public class Children{

    @Column(name="CHILDREN_ID")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "FATHER_ID", nullable = false, insertable = false, updatable = false)
    private Father father;
}

现在在父神DAO中我想删除所有使用它的孩子:

Father persistentFather = entityManager.find(Father.class, fatherId);
persistentFather.getChildrens().clear();
entityManager.merge(persistentFather);

我得到以下例外:

3:51:17 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/sample.web] threw exception         [Request processing failed; nested exception is     org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a];     constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could     not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into     ("MYDB"."CHILDREN_AUD"."FATHER_ID")

为什么hibernate不能从父对象中理解father_id?我应该在儿童中有一个father_id字段吗?

我知道这里没什么特别的,但是在搜索了几个小时后我找不到任何解决方案......

希望有人可以提供帮助

1 个答案:

答案 0 :(得分:1)

确切地说不确定,但这是我认为正在发生的事情。当您调用father.getChildren().clear()时,您只是打破了父亲及其子女之间的关系,这意味着FATHER_ID被设置为null,并且子项被更新。这应该是因为orphanRemoval = true而有效,但我认为Hibernate Envers(我假设您正在使用审计)会将其作为MarkupSubRule的更新,而不是(或之前)删除,并且尝试将NULL插入CHILDREN_AUD.FATHER_ID。要检查Envers是否真的导致此问题,您可以临时禁用它并重试。如果您没问题,可以在审计表FATHER_ID中更改CHILDREN_AUD以接受空值。