是否可以在 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"*/ }
资源关系
@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 没有。我该怎么办?
最佳答案
您的映射是错误的,您不应该显式处理包含资源之间关系的表。 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>();
关于hibernate - JPA、 hibernate : Persist through multiple levels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14974468/