JPA:从父级删除子级,而无需在父级中以双向关系合并

时间:2018-11-16 11:42:57

标签: hibernate hibernate-envers jpa-2.1

我正在处理以下父子关系:

@Entity
@Audited
public class Parent implements Serializable {
    @Id
    private Long id;

    @OneToMany(mappedBy = "parent", cascade = {CascadeType.ALL}, orphanRemoval = true)
    private Set<Child> children;

    // Empty default constructor
    // Getters and setters
}

@Entity
@Audited
public class Child implements Serializable {
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(nullable = false)
    private Parent parent;

    // Empty default constructor
    // Getters and setters
}

我正在使用的用例预见到我将从其父中移除一个孩子,但是此时,我明确地不应该合并父实体。因此,我尝试如下:

Child childFromDb = entityManager.find(Child.class, child.getId());
childFromDb.setParent(null);
entityManager.remove();

这会导致Hibernate抛出java.sql.BatchUpdateException: (conn:1) Column 'parent_id' cannot be null

设置@JoinColumn(nullable = true)可解决此问题,但数据库架构在列上使用DEFAULT NULL,这是不希望的,因为没有相关child的情况下可能不存在任何parent对象。另外,我不能在HQL,JPQL,本机SQL或CriteriaDelete中使用delete语句,因为表是使用Envers(5.1.4)审核的。我记得Envers不支持批量语句(插入,更新,删除,https://hibernate.atlassian.net/browse/HHH-3554)或CriteraUpdate / CriteraDelete(https://hibernate.atlassian.net/browse/HHH-10318)。

如何在不合并child,保持parent列约束并且不使用其他删除选项的情况下仅删除NOT NULL?这有可能吗?

0 个答案:

没有答案