Spring Boot JPA休眠父母/子/孙

时间:2019-02-21 04:26:06

标签: hibernate spring-boot

将新的孙子代添加到父代的子代中时,我添加的对象似乎被集合中​​的新对象替换。属性值相同,并且可以正常使用,但是I new'd的原始对象不包含ID,并且已从集合中删除。即使在我通过设置this添加子项之后,再将孙子项添加到集合中。

我需要该对象来获取ID,以便我可以映射该ID并将其返回给调用者。

@Entity
@Table(name = "parents")
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @NotNull
    private long id;

    @NotNull
    private String name;


    @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<ChildA> childrenA;
}



@Entity
@Table(name = "children_a")
public class ChildA {
    @NotNull
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Id
    private long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "parent_id", nullable = false)
    private Parent parent;

    @OneToMany(mappedBy = "childA", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<ChildB> childrenB;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }


    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }

    public void addChildB(ChildB childb) {
        childb.setChildA(this);
        childrenB.add(childB);
    }

    public Set<ChildB> getChildrenB() {
        return childrenB;
    }

    public void setChildrenB(Set<ChildB> childrenB) {
        this.childrenB = childrenB;
    }
}


@Entity
@Table(name = "children_b")
public class ChildB implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id")
    private long id;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child_a_id")
    private ChildA chiuldA;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public ChildA getChildA() {
        return childA;
    }

    public void setChildA(ChildA childA) {
        this.childA = childA;
    }

}

1 个答案:

答案 0 :(得分:0)

我碰到我的子实体被视为合并,因为通过JPA存储库通过父项进行的保存是合并。这是设计使然出现的