1

The @EntityGraph annotation will combine several SQL queries into a single query with JOIN if the target entity has other entity references.

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

class City {
  int id;
  String name;
}

If I call method hotelDao.findAllByName("hotelname"), it will generate 2 queries :

  • select hotel.id hotel.name hotel.city.id from hotel;
  • select city.id city.name from city where city.id={?}; // I think ? is the list of city id of the first query result

If I annotated the method above with @EntityGraph("city"), it will generate 1 query instead:

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

I wonder which choice is better? The latter one is suggested by a lot of articles but I noticed that the join table would grow exponentially if the two tables are getting bigger.

So when should I use one over another and why?

LunaticJape
  • 1,446
  • 4
  • 21
  • 39

1 Answers1

0

The goal is to let Hibernate generate as few SQL queries as possible.

So @EntityGraph is a way to provide this kind of optimization.

The problem with multiple SQL queries is called n+1 select problem.

There are a lot of articles about this and how to solve it. One is on SO: What is the solution for the N+1 issue in JPA and Hibernate?

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82