批量更新和删除

Hibernate3.0 采用新的基于ANTLR的HQL/SQL查询翻译器,在Hibernate的配置文件中,hibernate.query.factory_class属性用来选择查询翻译器。
(1)选择Hibernate3.0的查询翻译器:
hibernate.query.factory_class= org.hibernate.hql.ast.ASTQueryTranslatorFactory
(2)选择Hibernate2.1的查询翻译器
hibernate.query.factory_class= org.hibernate.hql.classic.ClassicQueryTranslatorFactory
为了使用3.0的批量更新和删除功能,只能选择(1)否则不能解释批量更新的语句。选择(2)但没法解释批量更新语句了。

Hibernate3.0 采用新的基于ANTLR的HQL/SQL查询翻译器,在Hibernate的配置文件中,hibernate.query.factory_class属性用来选择查询翻译器。
(1)选择Hibernate3.0的查询翻译器:
hibernate.query.factory_class= org.hibernate.hql.ast.ASTQueryTranslatorFactory
(2)选择Hibernate2.1的查询翻译器
hibernate.query.factory_class= org.hibernate.hql.classic.ClassicQueryTranslatorFactory
为了使用3.0的批量更新和删除功能,只能选择(1)否则不能解释批量更新的语句。选择(2)但没法解释批量更新语句了。

举个例子,使用Query.executeUpdate()方法执行一个HQL UPDATE语句:

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();
执行一个HQL DELETE,同样使用 Query.executeUpdate() 方法 (此方法是为 那些熟悉JDBC PreparedStatement.executeUpdate() 的人们而设定的)

执行一个HQL DELETE,同样使用 Query.executeUpdate() 方法 (此方法是为 那些熟悉JDBC PreparedStatement.executeUpdate() 的人们而设定的)

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();
由Query.executeUpdate()方法返回的整型值表明了受此操作影响的记录数量。 注意这个数值可能与数据库中被(最后一条SQL语句)影响了的“行”数有关,也可能没有。一个大批量HQL操作可能导致多条实际的SQL语句被执行, 举个例子,对joined-subclass映射方式的类进行的此类操作。这个返回值代表了实际被语句影响了的记录数量。在那个joined-subclass的例子中, 对一个子类的删除实际上可能不仅仅会删除子类映射到的表而且会影响“根”表,还有可能影响与之有继承关系的joined-subclass映射方式的子类的表。

如果是使用hibernate2 的话, 那么可以在hibernate中调用jdbc 来完成操作,先看没有使用jdbc 的情况

tx = session.beginTransaction();

  Iterator customers=session.find("from Customer c where c.age>0").iterator();

  while(customers.hasNext()){

  Customer customer=(Customer)customers.next();

  customer.setAge(customer.getAge()+1);

  }

  tx.commit();

  session.close();

  如果CUSTOMERS表中有1万条年龄大于零的记录,那么Session的find()方法会一下子加载1万个Customer对象到内存。当执行tx.commit()方法时,会清理缓存,Hibernate执行1万条更新CUSTOMERS表的update语句:

  update CUSTOMERS set AGE=? …. where ID=i;

  update CUSTOMERS set AGE=? …. where ID=j;

  ……

  update CUSTOMERS set AGE=? …. where ID=k;

  以上批量更新方式有两个缺点:

  (1) 占用大量内存,必须把1万个Customer对象先加载到内存,然后一一更新它们。

  (2) 执行的update语句的数目太多,每个update语句只能更新一个Customer对象,必须通过1万条update语句才能更新一万个Customer对象,频繁的访问数据库,会大大降低应用的性能。

为了迅速释放1万个Customer对象占用的内存 每更新100个立即释放它的内存和执行到数据库:

  tx = session.beginTransaction();

      int couut=0;

  Iterator customers=session.find("from Customer c where c.age>0").iterator();

  while(customers.hasNext()){

  Customer customer=(Customer)customers.next();

  customer.setAge(customer.getAge()+1);

      if (count%100) {

         session.flush();

      session.clear();

      }

   }

  tx.commit();

  session.close();

    但是只能稍微提高批量操作的性能,Hibernate都必须执行1万条update语句,才能更新1万个Customer对象,这是影响批量操作性能的重要因素。假如Hibernate能直接执行如下SQL语句:

update CUSTOMERS set AGE=AGE+1 where AGE>0;

  那么以上一条update语句就能更新CUSTOMERS表中的1万条记录。但是Hibernate并没有直接提供执行这种update语句的接口。应用程序必须绕过Hibernate API,直接通过JDBC API来执行该SQL语句:

  tx = session.beginTransaction();

  Connection con=session.connection();

  PreparedStatement stmt=con.prepareStatement("update CUSTOMERS set AGE=AGE+1 "

  +"where AGE>0 ");

  stmt.executeUpdate();

  tx.commit();

  以上程序演示了绕过Hibernate API,直接通过JDBC API访问数据库的过程。应用程序通过Session的connection()方法获得该Session使用的数据库连接,然后通过它创建PreparedStatement对象并执行SQL语句。值得注意的是,应用程序仍然通过Hibernate的Transaction接口来声明事务边界。

如果底层数据库(如Oracle)支持存储过程,也可以通过存储过程来执行批量更新。存储过程直接在数据库中运行,速度更加快。在Oracle数据库中可以定义一个名为batchUpdateCustomer()的存储过程,代码如下:

  create or replace procedure batchUpdateCustomer(p_age in number) as

  begin

  update CUSTOMERS set AGE=AGE+1 where AGE>p_age;

  end;

  以上存储过程有一个参数p_age,代表客户的年龄,应用程序可按照以下方式调用存储过程:

  tx = session.beginTransaction();

  Connection con=session.connection();

  String procedure = "{call batchUpdateCustomer(?) }";

  CallableStatement cstmt = con.prepareCall(procedure);

  cstmt.setInt(1,0); //把年龄参数设为0

  cstmt.executeUpdate();

  tx.commit();

  从上面程序看出,应用程序也必须绕过Hibernate API,直接通过JDBC API来调用存储过程。

Session的各种重载形式的update()方法都一次只能更新一个对象,而delete()方法的有些重载形式允许以HQL语句作为参数,例如:

  session.delete("from Customer c where c.age>0");

  如果CUSTOMERS表中有1万条年龄大于零的记录,那么以上代码能删除一万条记录。但是Session的delete()方法并没有执行以下delete语句:

  delete from CUSTOMERS where AGE>0;

  Session的delete()方法先通过以下select语句把1万个Customer对象加载到内存中:

  select * from CUSTOMERS where AGE>0;

  接下来执行一万条delete语句,逐个删除Customer对象:

  delete from CUSTOMERS where ID=i;

  delete from CUSTOMERS where ID=j;

  ……

  delete from CUSTOMERS where ID=k;

  由此可见,直接通过Hibernate API进行批量更新和批量删除都不值得推荐。而直接通过JDBC API执行相关的SQL语句或调用相关的存储过程,是批量更新和批量删除的最佳方式,这两种方式都有以下优点:

  (1) 无需把数据库中的大批量数据先加载到内存中,然后逐个更新或修改它们,因此不会消耗大量内存。

  (2) 能在一条SQL语句中更新或删除大批量的数据。

猜你喜欢

转载自joezheng123.iteye.com/blog/1861297