iterate查询与N+1次查询的问题
test.java
执行结果:
Hibernate: insert into Users (ver, name, birthday) values (?, ?, ?)
Hibernate: insert into Users (ver, name, birthday) values (?, ?, ?)
Hibernate: insert into Users (ver, name, birthday) values (?, ?, ?)
Hibernate: select users0_.id as col_0_0_ from Users users0_
Hibernate: select users0_.id as id0_0_, users0_.ver as ver0_0_, users0_.name as name0_0_, users0_.birthday as birthday0_0_ from Users users0_ where users0_.id=?
pf1
Hibernate: select users0_.id as id0_0_, users0_.ver as ver0_0_, users0_.name as name0_0_, users0_.birthday as birthday0_0_ from Users users0_ where users0_.id=?
pf2
Hibernate: select users0_.id as id0_0_, users0_.ver as ver0_0_, users0_.name as name0_0_, users0_.birthday as birthday0_0_ from Users users0_ where users0_.id=?
pf3
可以发现红色那条语句,iterator查询是先查出记录的id号,在需要的时候再去查询,查询时候先从缓存里查找,再从数据库中读取。
由于我的Users是native方式生成主键,所以不会保存在缓存里,因为没访问数据库前不知道数据库生成的id号。
所有的select语句加起来是4条,包括查id的语句,所以一共是N+1次查询。所以缓存没命中的情况下查询效率极低。
同样懒加载的时候也会有N+1次查询的情况,第一次查询出所有当前对象,N次查询查询关联对象。