@EntityGraph使用详解

本文探讨了在Java持久化API(JPA)中如何利用实体图(Entity Graph)进行查询优化,通过具体示例展示了如何定义默认和特定的实体图,以减少数据库查询次数并提高应用程序性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试时我使用三个类,类图如下
在这里插入图片描述
实体图如下:

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

结果如我们所想。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值