简体   繁体   English

Hibernate @ManyToOne @OneToMany为同一个实体

[英]Hibernate @ManyToOne @OneToMany for the same entity

I am trying to create an Entity that has a Parent and children from the same type as he is (like a tree). 我正在尝试创建一个实体,该实体具有父类和与他相同类型的子项(如树)。

here is the code: 这是代码:

@Entity @Table(name = "areas") public class Area { @Entity @Table(name =“areas”)公共类区域{

@Id
@Column(name = "id")
@GeneratedValue
private int id;

@Column(name = "name")
private String name;

@Column(name = "area_type", nullable = true)
private int areaType;

@ManyToOne
@JoinColumn(name="parent_area_id")
private Area parentArea;

@OneToMany (fetch = FetchType.EAGER, mappedBy = "parentArea")
@Cascade({CascadeType.ALL})
private Collection<Area> childAreas = new ArrayList<Area>();

i have seen this code in a few posts in stack overflow first of all when i try to save such entity to the database i get: 我首先在堆栈溢出的几个帖子中看到这个代码,当我尝试将这样的实体保存到数据库时,我得到:

nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

furthermore, there is something i don't understand fully about this design. 此外,我对这个设计还有一些不完全了解的东西。

if the children areas are mapped by the parent areas. 如果子区域由父区域映射。 wont it mean that "this" area will be among the children fached? 这不就意味着“这个”区域将成为孩子们的一部分吗? i other words... wont the children areas be the children of the parent area of "this" class. 换句话说......儿童区域不是“这个”类的父母区域的孩子。

thanks. 谢谢。

This seems like a similar problem. 似乎是一个类似的问题。 You should try: 你应该试试:

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany (mappedBy = "parentArea")
@Cascade({CascadeType.ALL})
private Collection<Area> childAreas = new ArrayList<Area>();

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

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