将子实体持久化操作与其父实体进行级联 [英] Cascading a Child entity persist operation to its Parent entity

查看:78
本文介绍了将子实体持久化操作与其父实体进行级联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与两个使用Hibernate批注设置的实体建立了OneToMany关联.此关联的Child实体具有一个复合主键,该主键由外键parent列和另一个标识符childName组成.当我尝试通过保存子实体将对父级的提交进行级联时,这似乎会导致违反参考完整性约束".

I have a OneToMany association with two entities that I have set up using Hibernate annotations. The Child entity of this association has a composite primary key that consists of the foreign key parent column and another identifier childName. This seems to cause a "Referential integrity constraint violation" when I attempt to cascade a commit to the parent by saving the child entity.

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

I have created a simple working example of the issue that abstracts away from the actual scenario that I am modelling with this relationship, but it means that I know the problem is due to this association and using a composite primary key.

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

Why can I not commit both entities by saving the child entity? Why does it violate foreign key constraints?

主要测试方法*:

// 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

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

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 (?, ?)
...


*主要方法引用的是我未在此处显示的DAO和ServiceLayer对象,因为我认为这与问题无关.但是,如果需要,我可以张贴这些.


* the main method refers to DAO and ServiceLayer objects that I have not shown here because I don't think it is relevant to the problem. I can, however, post these if asked for.

推荐答案

将保存操作从子级"转换为父级"实体并没有多大意义,反之亦然.

It doesn't make sense to cascade a save operation from a Child to a Parent entity, it's the other way around.

那是因为操作将是:

  • 救助孩子
  • 将保存操作传播给父级"

但子级取决于Parent.id来设置其FK.

but the Child depends on the Parent.id for setting its FK.

您还需要从数据库角度可视化此操作流程.您可以保存引用不存在的父母的孩子吗?当然不是.

You need to visualize this operation flow from the database perspective too. Can you save a Child who references a non-existing Parent? Of course, not.

请考虑删除子实体时会发生什么.级联将传播到父级,然后传播到其所有子级.

Think what will happen when you delete a Child entity. The cascade will propagate to the Parent and then to all its Children.

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

So, you have to remove the cascading from the Embeddable class:

@ManyToOne(cascade=CascadeType.ALL)

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

and uncomment the code that works fine:

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

这篇关于将子实体持久化操作与其父实体进行级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆