I'm working with hibernate and running into some problems using join queries, for some reason it generates ALLOT of queries. The table structure is pretty standard as follows:
-----------------------------------
| invoice_product |
-----------------------------------
| invpro_inv_id int |
| invpro_pro_id int |
-----------------------------------
-----------------------------------
| invoice |
-----------------------------------
| inv_id int |
| ....etc... |
-----------------------------------
-----------------------------------
| product |
-----------------------------------
| pro_id int |
| ....etc... |
-----------------------------------
Code that grabs the object and maps it to my domain model:
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select f from " + Invoice.class.getName() + " f");
List<Factuur> factuurList = query.list();
session.flush();
And here the relevant code in the entity:
public class Invoice {
--- omitted -------
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany
@JoinTable(
name = "invoice_product",
joinColumns = @JoinColumn(name = "invpro_inv_id", referencedColumnName = "inv_id"),
inverseJoinColumns = @JoinColumn(name = "invpro_pro_id", referencedColumnName = "pro_id")
)
private Set<Product> productSet;
------- omitted ----------
}
As you can see i let hibernate handle pretty much everything. I didnt create some custom SQL query.
For some reason this generates ALLOT of queries to the database. It creates 1 query to grab the invoice as expected, then when it goes to the join table bit it generates about 300 select queries to get all the products for an invoice. As i see it this generally needs 2 queries per invoice (1 select the invoice, 2 create the join to grab the products).
So my question is why does hibernate create this much queries. How does hibernate interpret this? And, is the only way around this to handle the join yourself?
Thanks in advance
Edit: Resolved. For those wondering, adding @Fetch(FetchMode.SUBSELECT) annotations fixes the issue. This is just a case of me not reading the docs correctly!