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?