使用NamedEntityGraph

时间:2018-05-14 18:55:46

标签: hibernate jpa spring-data-jpa

我有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

1 个答案:

答案 0 :(得分: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