from
DETAILTB detailtbs0_
where
detailtbs0_.MTID=
before getting detai set
after getting detai set
after getting detai set iterator
after getting detai info 2
after getting detai info 1
*如果将lazy设为true,fetch设为 select,在session关闭后在去访问set里的值,会出异常.
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.hb.Masttb.detailtbs, no session or session was closed
4,对主表进行多条记录查询的测试,当fetch设为subselect的时候,lazy是true的时候,hibernate先用一条SQL将主表的数据查出来,然后用id in 方式的SQL语句取子表的数据.
JAVA代码:
tx = sessionFactory.getCurrentSession().beginTransaction();
List mstlist = sessionFactory.getCurrentSession().createQuery("from com.test.hb.Masttb where id in (1,2)").list();
//下面的hql和上面的hql有同样的效果
//List mstlist = sessionFactory.getCurrentSession().createQuery("from com.test.hb.Masttb where id <3").list();
for (Iterator iter = mstlist.iterator(); iter.hasNext();) {
Masttb masttb = (Masttb) iter.next();
System.out.println("masttb.getMastinfo=" + masttb.getMastinfo());
Set set = masttb.getDetailtbs();
System.out.println(set.size());
if (set != null && !set.isEmpty()) {
for (Iterator itr = set.iterator(); itr.hasNext();) {
Detailtb detailtb = (Detailtb) itr.next();
System.out.println("detailtb.name=" + detailtb.getDetailinfo());
}
}
}
tx.commit();
运行结果:
Hibernate:
select
masttb0_.MID as MID1_,
masttb0_.MASTINFO as MASTINFO1_
from
MASTTB masttb0_
where
masttb0_.MID in (
1 , 2
)
masttb.getMastinfo=mastinfo
Hibernate:
select
detailtbs0_.MTID as MTID1_,
detailtbs0_.DTID as DTID1_,
detailtbs0_.DTID as DTID2_0_,
detailtbs0_.MTID as MTID2_0_,
detailtbs0_.DETAILINFO as DETAILINFO2_0_
from
DETAILTB detailtbs0_
where
detailtbs0_.MTID in (
select
masttb0_.MID
from
MASTTB masttb0_
where
masttb0_.MID in (
1 , 2
)
)
number in detail table: 2
detailtb.name=aaaa
detailtb.name=detailinfo2
masttb.getMastinfo=aaa
number in detail table: 1
detailtb.name=adfasdfa
如果fetch=select,lazy=true的话,运行结果为 1 + 2条SQL语句:
Hibernate:
select
masttb0_.MID as MID1_,
masttb0_.MASTINFO as MASTINFO1_
from
MASTTB masttb0_
where
masttb0_.MID in (
1 , 2
)
masttb.getMastinfo=mastinfo
Hibernate:
select
detailtbs0_.MTID as MTID1_,
detailtbs0_.DTID as DTID1_,
detailtbs0_.DTID as DTID2_0_,
detailtbs0_.MTID as MTID2_0_,
detailtbs0_.DETAILINFO as DETAILINFO2_0_
from
DETAILTB detailtbs0_
where
detailtbs0_.MTID=
number in detail table: 2
detailtb.name=aaaa
detailtb.name=detailinfo2
masttb.getMastinfo=aaa
Hibernate:
select
detailtbs0_.MTID as MTID1_,
detailtbs0_.DTID as DTID1_,
detailtbs0_.DTID as DTID2_0_,
detailtbs0_.MTID as MTID2_0_,
detailtbs0_.DETAILINFO as DETAILINFO2_0_
from
DETAILTB detailtbs0_
where
detailtbs0_.MTID=
number in detail table: 1
detailtb.name=adfasdfa