hibernate - JPA、 hibernate : Persist through multiple levels

标签 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"*/ }

资源关系

@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/

相关文章:

java - java中mysql的Spring数据和hibernate错误

java - @SequenceGenerator 的架构属性在 Hibernate 中不起作用

java - Hibernate 中的最大并发事务数是否有限制?

database - hibernate : Foreign key has the wrong number of column. 应该是 0

hibernate - EntityManager Hibernate 没有持久性提供程序

java - spring 和 hibernate 的日志配置

database - 从 Hibernate 中的 java.sql.Blob 获取流

java - Spring Boot Jackson ResponseEntity 找不到类的序列化器

hibernate - 我们可以使用 JPA2 注释来缓存关联吗?

google-app-engine - 谷歌应用程序引擎的限制?