Hibernate n+1 Problems and Solutions
Why the problem occurred:
Hibernate often uses set, bag and other sets of 1-to-many relationship, when the entity can be obtained by the relationship between the associated object or object set out, you can also set Cacade for association update and delete. This has to say that Hibernate's ORM is doing very well, very close to Oo's usage habits.
But the database access still must consider the performance problem, after setting 1 to many this kind of relationship, the query will appear the legendary n+1 question.
One -to-many: in a side, find the N objects, then need to be n objects associated with the collection, so that an original SQL query into a n+1 bar;
many to one: in the multi-party, the query obtained M objects, then will also be M objects corresponding to the 1-side object out, also become m+1;
Ways to solve the problem:
1, using fetch crawl, Hibernate crawl strategy is divided into single-ended agent and collection agent crawl strategy.
Hibernate Crawl Strategy (single-ended agent crawl strategy):
Keeping the default is the following:
<many-to-one name= "Clazz" cascade= "save-update" fetch= "select"/>
fetch= "Select" is to send another SELECT statement to fetch the current object associated entity or set fetch= "join"
<many-to-one name= "Clazz" cascade= "save-update" fetch= "join"/>
Hibernate will use an outer join with the SELECT statement to correlate the entity live collection at this time, lazy will expire
Hibernate Crawl Strategy (collection agent's fetch strategy):
Keeping the default (fetch= "select") is the following:
<set name= "Students" inverse= "true" >
<key column= "Clazz"/>
<one-to-many class= "Com.june.hibernate.Student"/>
</set>
1) fetch= "Select" will issue a separate statement query collection
2) Set fetch= "join" with a lazy invalidation of the outer join set
3) This fetch= "Subselect" also emits a SELECT statement that fetches the associated collection of all the entity objects that were previously queried. Fetch only affects HQL queries.
2. Use map to search directly for required columns
such as: Product products and Product categories product_category two sheets, many-to-one relationship. When querying a product list
Select New Map (p.id as ID, p.name as name, P.category.name as CategoryName) from Product p