将子实体的持久操作级联到其父实体



我与使用Hibernate注释设置的两个实体有一个OneToMany关联。该关联的Child实体具有复合主键,该复合主键由外键parent列和另一标识符childName组成。当我试图通过保存子实体将提交级联到父实体时,这似乎会导致"引用完整性约束冲突"。

我已经创建了一个简单的问题工作示例,该示例从我用这种关系建模的实际场景中抽象出来,但这意味着我知道问题是由于这种关联和使用复合主键造成的。

为什么我不能通过保存子实体来提交这两个实体?为什么它违反了外键约束?

主要测试方法*:

// Create some detached entities
Parent p = new Parent();
p.setName("Fooson");
// New child id
Child.ChildPK pk = new Child.ChildPK();
pk.setParentName(p);
pk.setChildName("Barty");     
// Set id to new Child
Child c = new Child();
c.setChildPK(pk);
// Add child to parent
p.getChildren().add(c);
// Saving the parent
// service.parentDao.save(p); // if this is uncommented, it works fine
// Cascade child and associated parents in one transaction
service.childDao.save(c); // ConstraintViolationException

Child.java

@Entity
@Table(name="Child")
public class Child implements Serializable {
    @EmbeddedId
    private ChildPK id;
    public ChildPK getChildPK() {
        return id;
    }
    public void setChildPK(ChildPK childPK) {
        this.id = childPK;
    }
    @Embeddable
    public static class ChildPK implements Serializable 
    {
        @ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name="name")
        Parent parent;
        @Column(name="childName")
        String childName;
        public Parent getParentName() {
            return parent;
        }
        public void setParentName(Parent parentName) {
            this.parent = parentName;
        } 
        public String getChildName() {
            return childName;
        }
        public void setChildName(String childName) {
            this.childName = childName;
        }
        @Override
        public int hashCode() {
            int hash = 5;
            hash = 67 * hash + Objects.hashCode(this.parent);
            hash = 67 * hash + Objects.hashCode(this.childName);
            return hash;
        }
        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final ChildPK other = (ChildPK) obj;
            if (!Objects.equals(this.parent, other.parent)) {
                return false;
            }
            return Objects.equals(this.childName, other.childName);
        }
        @Override
        public String toString() {
            return "ChildPK{" + "parentName=" + parent.getName() + ", childName=" + childName + '}';
        }
    }
    @Override
    public String toString() {
        return "Child{" + "id=" + id + '}';
    }
}

Parent.java

@Entity
@Table(name="Parent")
public class Parent implements Serializable {
    @Id
    @Column(name="name")
    private String name;
    @OneToMany(mappedBy="id.parentName", cascade=CascadeType.ALL)
    Set<Child> children = new HashSet<>(0);
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Child> getChildren() {
        return children;
    }
    public void setChildren(Set<Child> children) {
        this.children = children;
    }
    @Override
    public int hashCode() {
        int hash = 3;
        hash = 73 * hash + Objects.hashCode(this.name);
        return hash;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Parent other = (Parent) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return "Parent{" + "name=" + name + ", children=" + children + '}';
    }
}

完整的异常消息是:

Exception in thread "main" org.hibernate.exception.ConstraintViolationException: 
Could not execute JDBC batch update
...
Caused by: org.h2.jdbc.JdbcBatchUpdateException: 
Referential integrity constraint violation: 
"FK3E104FCBA07683D: PUBLIC.CHILD FOREIGN KEY(NAME) REFERENCES 
PUBLIC.PARENT(NAME) ('Fooson')"; SQL statement:
insert into Child (childName, name) values (?, ?)
...

*main方法引用了我在这里没有显示的DAO和ServiceLayer对象,因为我认为它与问题无关。不过,如果需要的话,我可以发布这些。

将保存操作从子实体级联到父实体是没有意义的,相反。

这是因为操作将是:

  • 拯救孩子
  • 将保存操作传播到父级

但是Child依赖Parent.id来设置其FK.

您还需要从数据库的角度来可视化此操作流。是否可以保存引用不存在的父级的子级?当然不是。

想想当您删除一个子实体时会发生什么。级联将传播到父级,然后传播到其所有子级。

因此,您必须从Embeddable类中删除级联:

@ManyToOne(cascade=CascadeType.ALL)

并取消注释工作正常的代码:

// Saving the parent
service.parentDao.save(p); // if this is uncommented, it works fine

最新更新