使用NamedEntityGraph

问题描述 投票:1回答:1

我有3个级别的实体样本:年级 - >班级 - >学生,类似这样

@Entity
public class Year {
  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name="year_id")
  Set<Class> classes;
}

@Entity
public class Class {
  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name="class_id")
  Set<Student> students;
}

@Entity
public class Student {
  String name;
}

所以我在我的Year类中创建了一个entityGraph

@NamedEntityGraph(name = "Year.classes",
        attributeNodes = @NamedAttributeNode("classes"))

但是在我服务的某些方法中,我只想返回一个类,所以我放入了我的存储库

@EntityGraph(value = "Year.classes", type = EntityGraph.EntityGraphType.LOAD)
public List<Year> findOne(){
}

但在我服务的一些方法中,我想返回3个级别

在这种情况下,我也需要在我的类中创建一个@NameEntityGraph(并配置为返回学生)

@NamedEntityGraph(name = "Class.students",
        attributeNodes = @NamedAttributeNode("students"))

那么如何配置该方法来返回学生呢?

@EntityGraph(value = "Year.classes", type = EntityGraph.EntityGraphType.LOAD)
public List<Year> findTwo(){
}

TKS

hibernate jpa spring-data-jpa
1个回答
0
投票

您的Class.students图需要被定义并作为EntityGraph类的新Year中的子图引用。这样的事情应该有效:

@NamedEntityGraph(name = "Year.full",
    attributeNodes = @NamedAttributeNode(
        value = "classes", 
        subgraph = "Class.students"),
    subgraphs = @NamedSubgraph(
        name = "Class.students", 
        attributeNodes = @NamedAttributeNode("students")
    )
)

Here you can read more about this

© www.soinside.com 2019 - 2024. All rights reserved.