开发者

How can I store a tree structure in JPA?

开发者 https://www.devze.com 2023-02-10 18:06 出处:网络
I need to store a large amount of nodes with many-to-many relationship to eachother (through parents/childrens). How can I do that in JPA?

I need to store a large amount of nodes with many-to-many relationship to eachother (through parents/childrens). How can I do that in JPA?

I know I can use @ManyToMany on my parents/childrens list but then JPA will load the all parents and their parents and so on right? Is there any way I can do it and only load the parents or children one step away?

The non-working code I have now (the Node.java):

public String name;

@ManyToMany
@JoinTable(name = "NodeParent开发者_C百科")
public List<Node> parents;

@ManyToMany
@JoinTable(name = "NodeChilds")
public List<Node> childrens;


For this JPA has the concept op lazy loading.

While iterating over the collection when still within the persistence context, every time you reference a not previously loaded entity, it will be loaded on demand.

Additionally, if you know up-front which entities you need (how deep you want the tree to be fetched) you can write a projection query (JPQL) using the fetch join operator.

Finally, a hibernate specific solution that might be included in JPA 2.1 are so-called fetch profiles. See Fetch profiles and Fetch Profiles in Hibernate 3.5.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号