Hibernate N+1问题及解决办法

Hibernate的两个类设置了manyToOne(oneToMany)之后,在查询的时候,由于N 对1的一方默认的fetch=FetchType.EAGER,所以会把被关联的对象一起取出来

解决方法一:设置fetch=FetchType.LAZY,这种方法在合适的时候(具体使用到对象时)还是会发出select语句。

解决方法二:

//List<Student> students= (List<Student>)session.createCriteria(Student.class).list();
List<Student> students= (List<Student>)session.createQuery("from Student").list();

也就是用session.createCriteria()做查询,而不是用createQuery。

解决方法三:使用BatchSize(size=5)方法,他会发出1+N/5条select语句。

解决方法四:使用join fetch做外连接查询。

from Topic t left join fetch t.category c

原文地址:https://www.cnblogs.com/qwangwei/p/5029052.html