Hibernate常用的四种抓取策略(fetching strategies):
*查询抓取(select fetching)
*连接抓取(join fetching)
*子查询抓取(subselect fetching)
*批量抓取(batch fetching)
查询抓取:
例:<many-to-one name="classes" column="classesid" fetch="select"/>,一般为默认选项,采用延时加载
连接抓取:
例:<many-to-one name="classes" column="classesid" fetch="join"/>,一般采用连接的方式把普通属性连带关联实体或实体集合加载上来,作用同HQL中的连接查询
子查询抓取:
例:<set name="students" inverse="true" cascade="all" fetch="subselect">
<key column="classesid"/>
<one-to-many class="Student"/>
</set>
测试用例:
public void testFetch() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
//发出sql语句
List classesList = session.createQuery("select c from Classes c where c.id in(1, 2, 3)").list();
for (Iterator iter=classesList.iterator(); iter.hasNext();) {
Classes classes = (Classes)iter.next();
//发出如下sql语句
/**
* Hibernate:
* select
* students0_.classesid as classesid1_,
* students0_.id as id1_,
* students0_.id as id1_0_,
* students0_.name as name1_0_,
* students0_.classesid as classesid1_0_
* from
* t_student students0_
* where
* students0_.classesid in (
* select classes0_.id
* from t_classes classes0_
* where classes0_.id in (1 , 2 , 3))
*/
System.out.println("classes.name=" + classes.getName());
for (Iterator iter1=classes.getStudents().iterator(); iter1.hasNext();) {
Student student = (Student)iter1.next();
System.out.println("student.name=" + student.getName());
}
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}
批量抓取:
例:<class name="Classes" table="t_classes" batch-size="5">
测试用例:
public void testFetch() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
List students = session.createQuery("select s from Student s where s.id in(:ids)")
.setParameterList("ids", new Object[]{1, 11, 21, 31, 41, 51, 61, 71, 81, 91})
.list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println("student.name=" + student.getName());
//select classes.name from classes where classes.id in (?,?,?,?,?)
// select classes.name from classes where classes.id in (?,?,?,?,?)
System.out.println("classes.name=" + student.getClasses().getName());
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}