有几个需要注意的地方:
1 在xml配置中 是默认懒加载的(fetch=select),也就是在使用到懒加载对象的属性时候 才会发出SQL语句,不使用的话就发一个SQL即可,若遍历时使用关联对象的属性,那么会发出大量SQL,而这是我们不希望看见的
很多情况下 我们是要希望能使用fetch=Join 也就是实现全部加载 只发出一条SQL,即使没有显示的使用关联对象属性仍然全部加载,此SQL使用left join连接表。省的在遍历时调用关联对象属性的时候 再发出大量SQL 给数据库造成巨大压力(反正是要把数据都取出来的)
2 annatation中是默认对象fetchType=eager 也就是join 而不是select懒加载,即全部加载
3 这是加载多端对象 想要加载全部
默认在xml中会发出3条SQL语句 一条区student 一条取classroom 一条取special
通过设置student的xml中的<many-to-one name="classroom" column="cid" fetch="join"/>
同样要对classroom进行设置 join抓取special
可以完成对抓取的设置
session=HibernateUtil.openSession();
Student stu=(Student)session.load(Student.class,1);
System.err.println(stu.getName()+","+
stu.getClassroom().getName()+","+stu.getClassroom().getSpecial().getName());
4 使用fetch=join虽然可以把关联的对象全部抓取出来 但是如果不使用关联对象 也会一并查询出来
这样也会占用内存 数据库等资源
此时延迟加载就失效了
<span style="white-space:pre"> </span> session=HibernateUtil.openSession();
Student stu=(Student)session.load(Student.class,2);
System.err.println(stu.getName());
5 因为fetch=join仅仅对Load时候有用 对HQL没有作用 用到了再发SQL
所以此时使用默认方式fetch=select
从多端级联查询一端 解决方案2中:
1设置对象抓取的batch size在班级中设置 比如=20 表示加载student对象时一次取20个班 默认是一次一个班
相当于一下子把关联的很多班级都取了出来 功能上=fetch=join
<class name="Classroom" table="t_cla" batch-size="3">
但是占内存多 且session关闭额 就数据消失了
<span style="white-space:pre"> </span>List<Student> stus=session.createQuery("from Student").list();
for (Student student : stus)
{
System.out.println(student.getName()+student.getClassroom());
}
2 重要 :在HQL中使用fetch来指定抓取 可以做到只对关联对象查一次 完全类似join在Load中的功能
这是加载关联对象时候只会发出一条SQL 但是join fetch不能和count(*)同时使用 我们计数时候 把fetch去掉就是了
session=HibernateUtil.openSession();
List<Student> stus=session.createQuery("select stu from Student stu join fetch stu.classroom").list();
for (Student student : stus)
{
System.out.println(student.getName()+student.getClassroom());
}
6对于从一端加载的情况 从一端fetch的情况 默认延迟加载
<