0

Consider two related objects Bill and BillItem. All bills have several bill items. Bill class has getItems which is configured as a OneToMany with eager fetching.

If I select a set of bills (say for today for one customer) which returns 5 bills. Each bill has several bill items.

Would Hibernate use a join on tables Bill and BillItem to load the details in one shot? Or would hibernate use n+1 queries where n is the number of bills?

If using join queries is not the default behaviour, is there any way to configure Hibernate to use join in this case? Or would this require use of HQL and some custom coding to do the mapping?

Edit: I guess this has been covered here: JPA eager fetch does not join

Community
  • 1
  • 1
Teddy
  • 4,009
  • 2
  • 33
  • 55
  • 1
    You can enable sql logging in persistence.xml to see the actual query being executed – Fran Montero Sep 01 '15 at 12:13
  • I believe you can either go for EAGER loading, and the BillItems are brought every time, or you can LAZY load them, making a second (or third and so on) query only if/when you actually decide to use the field. Not sure how it works under the hood though, it might as well be that EAGER also perform multiple queries, just sooner -- which is odd, because would render de option pretty useless then. – Luan Nico Sep 01 '15 at 12:15
  • possible duplicate of [JPA eager fetch does not join](http://stackoverflow.com/questions/463349/jpa-eager-fetch-does-not-join) – Teddy Sep 02 '15 at 07:55

1 Answers1

0

The answer is "it depends". In a general case it's very easy to get the dreaded N+1 selects, when fetching entities carelessly. That's why you need to observe the performance of the queries and verify that they're doing what you're expecting.

There's plenty of discussion around about JPA/Hibernate performance optimization, including avoiding the N+1 selects with JOINs.

Kayaman
  • 72,141
  • 5
  • 83
  • 121