集合的延迟加载是在一对多和多对多中应用
- lazy为true时
@Test
public void TestQuery(){
Session session = HibernateUtils.getSession();
try {
//这里没有发出sql语句
Team team = (Team) session.load(Team.class, 1);
//因为这里只用到非集合属性,所以只是发出了搜索非集合属性的sql语句
System.out.println(team.gettName());
//这里没有发出sql语句
Set<Emp> sets = team.getSet();
//这里用到集合属性,发出搜索集合的sql语句
System.out.println(sets);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
- lazy为false
@Test
public void TestQuery3(){
Session session = HibernateUtils.getSession();
try {
//这里没有发出sql语句
Team team = (Team) session.load(Team.class, 1);
//因为这lazy为false,这就会发处所有的select语句
System.out.println(team.gettName());
//这里没有发出sql语句
Set<Emp> sets = team.getSet();
//这里不在发送sql语句
System.out.println(sets);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
- lazy为extra
@Test
public void TestQuery3(){
Session session = HibernateUtils.getSession();
try {
//这里没有发出sql语句
Team team = (Team) session.load(Team.class, 1);
//因为这里只用到非集合属性,所以只是发出了搜索非集合属性的sql语句
System.out.println(team.gettName());
//这里没有发出sql语句
Set<Emp> sets = team.getSet();
//发出一条正能高效的sql
System.out.println(sets.size());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出:
Hibernate: select team0_.ID as ID1_1_0_, team0_.TNAME as TNAME2_1_0_, team0_.LOC as LOC3_1_0_ from TEAM team0_ where team0_.ID=? meng Hibernate: select count(IMPNO) from EMP where ID =? 2 |
如上当lazy为extra时获取集合的数量就不会把所有的集合搜索出来再计算数量,这样效率会比较高
Note:
集合的延迟加载不受类的集合加载影响
如下类的lazy设置为:
<classname="com.yao.hibernate.model.Team" table="TEAM"lazy="false">
集合设置为:
<setname="set" table="EMP" cascade="save-update"inverse="true" lazy="extra">