[英]Hibernate: How to ensure that a parent is not deleted when all its child entities are?
[英]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);
并且只有父对象是持久的。
另外,当我发现parent
和child
没有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.