测试时我使用三个类,类图如下
实体图如下:
@Entity
@Table(name = "location")
@NamedEntityGraphs({
@NamedEntityGraph(name = "default",attributeNodes = {
@NamedAttributeNode(value = "country",subgraph = "country")
},
subgraphs = {
@NamedSubgraph(name = "country",attributeNodes = {
@NamedAttributeNode(value = "region",subgraph = "region")
}),
@NamedSubgraph(name = "region",attributeNodes = {})
}),
@NamedEntityGraph(name = "noRegion",attributeNodes = {
@NamedAttributeNode(value = "country",subgraph = "country")
},
subgraphs = {
@NamedSubgraph(name = "country",attributeNodes = {})
})
})
可以在Repository 层指定 实体信息,
default 查询信息到region
@EntityGraph("default")
Optional<Location> findOneById(Long id);
查询sql:
Hibernate: select location0_.id as id1_6_0_, country1_.id as id1_0_1_, region2_.id as id1_7_2_, location0_.city as city2_6_0_, location0_.country_id as country_6_6_0_, location0_.postal_code as postal_c3_6_0_, location0_.state_province as state_pr4_6_0_, location0_.street_address as street_a5_6_0_, country1_.country_name as country_2_0_1_, country1_.region_id as region_i3_0_1_, region2_.region_name as region_n2_7_2_ from location location0_ left outer join country country1_ on location0_.country_id=country1_.id left outer join region region2_ on country1_.region_id=region2_.id where location0_.id=?
查询结果:
{
"id": 1,
"streetAddress": "Secured productize",
"postalCode": "schemas",
"city": "Octaviafurt",
"stateProvince": "olive Ghana Games",
"country": {
"id": 1,
"countryName": "content backing up Usability",
"region": {
"id": 1,
"regionName": "International Movies"
}
}
}
noRegion实体图查询的结果不包含region
查询sql:
Hibernate: select location0_.id as id1_6_0_, country1_.id as id1_0_1_, location0_.city as city2_6_0_, location0_.country_id as country_6_6_0_, location0_.postal_code as postal_c3_6_0_, location0_.state_province as state_pr4_6_0_, location0_.street_address as street_a5_6_0_, country1_.country_name as country_2_0_1_, country1_.region_id as region_i3_0_1_ from location location0_ left outer join country country1_ on location0_.country_id=country1_.id where location0_.id=?
查询结果:
{
"id": 1,
"streetAddress": "Secured productize",
"postalCode": "schemas",
"city": "Octaviafurt",
"stateProvince": "olive Ghana Games",
"country": {
"id": 1,
"countryName": "content backing up Usability",
"region": null
}
}
结果如我们所想。