gpt4 book ai didi

hibernate - JPA, hibernate : Persist through multiple levels

转载 作者:行者123 更新时间:2023-12-04 05:10:14 24 4
gpt4 key购买 nike

是否可以在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com