批量更新和删除
在HIBERNATE 3中,批量更新比2有了很大的改善。
以下是通过Hibernate3.0执行批量更新的程序代码:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
以下是通过Hibernate3.0执行批量删除的程序代码:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlDelete = "delete Customer where name = :oldName";
int deletedEntities = s.createQuery( hqlDelete )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
2 抓取策略
加载时一般都是一对多的关系中的,防止多次加载,默认lazy=true的,在hibernate 3中。
批量加载:在xxx.hbm.xml中,设置batchsize=n,设置每次加载的条数。
hibernate3的subselect新功能:
一个典型的场景是,比如一个class,一个student,一对多关系,比如如下
List classesList=session.createquery("select c from classes c where c.id in (1,2,3)");
for (Iterator iter=classeslist.iterator();iter.hasnext())
{
Classes classes=(Classes)iter.next();
for (Iterator iter1=classes.getStudents().iterator;iter1.hasnext())
Student student=(Student)iter1.next();
}
这样的话,会发出三条sql语句。如果用subselect的话,则只发出一条SQL语句,快了。
直接select .... from student where student.id in (select classid from ...where c.id in (1,2,3));
查询前面查询到的关联实体。
设置为<set name="students" fetch="subselect">