我何时应该在Spring Data JPA中使用@EntityGraph?

时间:2019-02-04 17:35:46

标签: hibernate spring-boot spring-data-jpa

如果目标实体具有其他实体引用,则@EntityGraph批注将使用JOIN将多个SQL查询合并为一个查询。

class Hotel {
   int id;
   String name;
   City city;
}

class City {
  int id;
  String name;
}

如果我调用方法hotelDao.findAllByName("hotelname"),它将生成2个查询:

  • select hotel.id hotel.name hotel.city.id from hotel;
  • select city.id city.name from city where city.id={?}; //我认为?是第一个查询结果的城市ID列表

如果我用@EntityGraph("city")注释了上面的方法,它将改为生成1个查询:

  • select hotel.id hotel.name city.id city.name from hotel join city where hotel.cityid = city.id;

我想知道哪个选择更好?很多文章都建议使用后一个表,但我注意到如果两个表变大,则联接表将成倍增长。

那我什么时候应该使用另一个,为什么呢?

1 个答案:

答案 0 :(得分:0)

目标是让Hibernate生成尽可能少的SQL查询。

因此@EntityGraph是提供这种优化的一种方式。

多个SQL查询的问题称为n + 1选择问题。

关于此问题以及如何解决的文章很多。一个是这样的: What is the solution for the N+1 issue in JPA and Hibernate?

相关问题