Spring-data-jpa n + 1 issues

Spring-data-jpa problem of n + 1

When we use the JPA available to find our way out if the query object associated with 10 other objects, JPA will send 1 + 10 queries (the object itself to query once, and then each associated object query again )

 

solution:

1. FetchType.EAGER + FetchMode.JOIN form, so that the SQL statement can be automatically generated with a LEFT OUTER JOIN (provided: there must be a foreign key associated master, otherwise invalid)

 

 

E.g:

 

 

In this case, even if set FetchType.EAGER + FetchMode.JOIN, the same problems exist in the N + 1.

2. Use JPA2.1 characteristics @NamedEntityGraph notes, which is specifically optimized to address the introduction of JPA JPA annotations efficiency. Used as follows.

First make a statement on the entity classes:

 

 

Then use the interface in the Repository reference @EntityGraph

 

 

 

<Note> according to different problem scenarios, different definitions @NamedEntityGraph, remember not to be associated with non-business related objects, as it will be to JOIN table will cause unnecessary performance loss.

 

 

When used on Hibernate Predicate in Spring-data-jpa frame N + 1 to resolve the problem

Solutions with Spring-data-jpa, difference is that, in the Hibernate Predicate call is in JpaSpecificationExecutor findAll, it is necessary to cover the corresponding method in the Repository findAll, then add annotations EntiryGraph corresponding, e.g.

 

 

 

3. batchSize (size = 10) for batch

 

4. Use lazy loading

 

 

Guess you like

Origin www.cnblogs.com/ymqj520/p/11589934.html