繁体   English   中英

如何用冬眠持久化新创建的父实体和子实体?

[英]How persist new created parent and child entities with hibernate?

这是实体:

@Entity
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent" ,cascade = CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    private Collection<Child> children;
}

@Entity
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    private Parent parent;

}

为了管理这个实体,我使用spring数据(rest)。 我需要保存这样的实体:

Parent parent = new Parent();
Child child = new Child()
parent.setChildren(Arrays.asList(child))
springDataRepository.save(parent);

并且只有父对象是持久的。

另外,当我发现parentchild没有id创建时。 所以我应该只坚持parent ,然后将其设置为child并坚持child吗? 可以通过一项parent保存操作来完成这些操作吗?

查看此回复: https : //stackoverflow.com/a/7428143

代替:

parent.setChildren(Arrays.asList(child))

您应该使用:

parent.setChildren(new ArrayList<>(Arrays.asList(child)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM