JPA,Hibernate:坚持多层次

时间:2013-02-20 07:28:49

标签: hibernate jpa

是否可以在JPA(或Hibernate)中持续多个级别?我有一个表“资源”,其中每个资源可以是另一个资源的“子”。这可以通过多个级别进行。我正在使用连接表来包含这种关系。

我想要实现的是这个。

resource                                        resource_relations
========                                        ==================
resource_type | resource_name                   parent   | child
------------------------------                  --------------------
type1         | P                               P        | C
type2         | C                               C        | G  
type3         | G

我的持久性实体看起来像这样。

资源

private String name;
private ResourceType resourceType;

public Resource(resourceType, name){ ... }   

@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
private Set<ResourceRelation> components = new HashSet<ResourceRelation>();

@OneToMany(mappedBy = "child", cascade = CascadeType.PERSIST)
private Set<ResourceRelation> parents = new HashSet<ResourceRelation>();

public void addComponent(Resource r) { /*add "r" to "components"*/ }

ResourceRelation

@ManyToOne (cascade = CascadeType.PERSIST)
private Resource parent;

@ManyToOne (cascade = CascadeType.PERSIST)
private Resource child;

现在,我执行以下语句:

parent = new Resource(type1, P);
child = new Resource(type2, C);
grandChild = new Resource(type3, G);
child.addComponent(grandChild);
parent.addComponent(child);
persist(parent);

但是,只有P和C会持久而不是G.我该怎么做呢?

1 个答案:

答案 0 :(得分:3)

您的映射是错误的,您不应该显式处理包含资源之间关系的表。 Hibernate会为你做的!这里只需要Resource类:

private String name;
private ResourceType resourceType;

@OneToMany(cascade = CascadeType.PERSIST)
private Set<Resource> components = new HashSet<Resource>();

@OneToMany(cascade = CascadeType.PERSIST)
private Set<Resource> parents = new HashSet<Resource>();