如何在 JPA 中初始化几层深处的 LAZY 实体?



>我有几个层次的深度关系:

class Person {
@Id
@Column(name = "PERSON_ID")
private Long personId;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "person")
private Set<Parameter> parameters;
[... various other attributes omitted]
} 
class Parameter {
@Id
@Column(name = "PARAMETER_ID")
private Long personId;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "GAME_ID", nullable = false)
private Game game;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PERSON_ID")
@JsonIgnore
private Person person;
[... various other attributes omitted]
} 
class Game {
@Id
@Column(name = "GAME_ID")
private Long gameId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "game") // this is the attribute, that sometimes is required sometimes is not
private Set<GameRule> gameRules;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "game")
@JsonIgnore
private Set<Parameter> parameters;
[... various other attributes omitted]
}
class GameRule {
@Id
@Column(name = "GAME_RULE_ID")
private Long gameRuleId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="GAME_ID", nullable = false)
@JsonIgnore
private Game game;
[... various other attributes omitted]
}

谁能告诉我在查询person时如何使用game.gameRules"加入获取"? 我尝试在game上创建一个@NamedEntityGraph(使用gameRules属性), 并在person的存储库中使用它,findAll@EntityGraph一起使用,但使用person存储库中的实体图导致异常 Hibernate 无法在person中找到gameRules属性(不足为奇)。

那么,有人如何在成员级别上初始化一个懒惰实体呢? 谢谢

由于在这种情况下您的关系是嵌套的,因此您需要使用如下所示的subgraph和@NamedSubgraph。

在存储库方法中使用graph.person.parameters作为图形名称。

@NamedEntityGraph(name = "graph.person.parameters", attributeNodes = {
@NamedAttributeNode(value = "parameters", subgraph = "parameters.game") }, subgraphs = {
@NamedSubgraph(name = "parameters.game", attributeNodes = {
@NamedAttributeNode(value = "game", subgraph = "game.gameRules") }),
@NamedSubgraph(name = "GameRule ", attributeNodes = {
@NamedAttributeNode(value = "GameRule ") }) })

最新更新