这一篇我们就切入 JPA 中的 N+1 Query 来做探讨
什么是 JPA 中的 N+1 Query
本可以使用一句 SQL 就完成查询的需求,但因为其余 Related Association 没有跟着被查询出来,而导致被迫多执行 N 次查询所导致的现象。
为何这样的行为,会降低查询的效能
查询本身是非常简单的,但是往返资料库之间的时间,却远远超过查询本身所需要的成本。
如何判断是不是遇到 N+1 Query 了呢?
Entity Relation,作家(author) 和 书(book) 有着 OneToMany 的关係,并使用 Spring Data JPA (JpaRepository)
@Repositorypublic interface AuthorRepository extends JpaRepository<City, Long> {}
执行下方程式码的时候
authorRepository.findAll().forEach(Author::getBooks);
Console Log
select * from author;select * from book where author_id = ?;select * from book where author_id = ?;...select * from book where author_id = ?;
上述对于 book 的查询次数会相等于 select * from author;
所查询到的数量。
因为这些 author record 被查询出来的时候,都并未携带所属的 book records
,会发生这样的情况,主要是因为 JPA 定义中的 OneToMany
关係中 FetchType 属于 LAZY
,并不会跟着 Parent Entity
一起被查询出来,都得等到需要使用的时候才会进资料库进行查询。
预告
下一篇将会在针对 FetchType LAZY and EAGER 做分享。