10135 Query select teacher0_.id as id1_1_0_, teacher0_.name_ as name_2_1_0_ from teacher teacher0_ where teacher0_.id=1
10135 Query select students0_.teacher_id_ as teacher_3_0_0_, students0_.id as id1_0_0_, students0_.id as id1_0_1_, students0_.name_ as name_2_0_1_ from student students0_ where students0_.teacher_id_=1
Teacherteacher1=entityManager.createQuery("select t from Teacher as t join fetch t.students where t.id = 1",Teacher.class).getSingleResult();for(Studentstudent:teacher1.getStudents()){System.out.println(student);}
产生是 SQL 日志如下:
1
10152 Query select teacher0_.id as id1_1_0_, students1_.id as id1_0_1_, teacher0_.name_ as name_2_1_0_, students1_.name_ as name_2_0_1_, students1_.teacher_id_ as teacher_3_0_0__, students1_.id as id1_0_0__ from teacher teacher0_ inner join student students1_ on teacher0_.id=students1_.teacher_id_ where teacher0_.id=1
10181 Query select university0_.id as id1_2_0_, university0_.address_ as address_2_2_0_, university0_.name_ as name_3_2_0_ from university university0_ where university0_.id=3
10181 Query select teachers0_.university_id_ as universi3_1_0_, teachers0_.id as id1_1_0_, teachers0_.id as id1_1_1_, teachers0_.name_ as name_2_1_1_ from teacher teachers0_ where teachers0_.university_id_=3
10181 Query select students0_.teacher_id_ as teacher_3_0_0_, students0_.id as id1_0_0_, students0_.id as id1_0_1_, students0_.name_ as name_2_0_1_ from student students0_ where students0_.teacher_id_=3
上面的代码 1、2 行,我们首先构建了一个 JPA 的 hint,hint 用于告知底层的 JPA 实现类即 Hibernate 我们要使用某些特性了,请予以支持,如果不支持的话请忽略。hint的key我们指定为“javax.persistence.fetchgraph”,也可以指定为“javax.persistence.loadgraph”,前者作用是立即加载指定的节点,未指定的节点延迟加载;后者是立即加载指定的节点,未指定的节点按实体中定义的加载策略进行加载,hint 的 value 为实体图,我们通过 em.getEntityGraph() 方法来获取。第3行代码,我们调用查询时,将 hint 传给 find 方法,至此就完成了实体图的查询方式。
运行代码后,会产生如下日志:
1
10185 Query select university0_.id as id1_2_0_, university0_.address_ as address_2_2_0_, university0_.name_ as name_3_2_0_, teachers1_.university_id_ as universi3_1_1_, teachers1_.id as id1_1_1_, teachers1_.id as id1_1_2_, teachers1_.name_ as name_2_1_2_, students2_.teacher_id_ as teacher_3_0_3_, students2_.id as id1_0_3_, students2_.id as id1_0_4_, students2_.name_ as name_2_0_4_ from university university0_ left outer join teacher teachers1_ on university0_.id=teachers1_.university_id_ left outer join student students2_ on teachers1_.id=students2_.teacher_id_ where university0_.id=3