Enjoying Life ...... !
If u can look into my eyes, u will see how beautiful the life is.
posts - 4,comments - 12,trackbacks - 0

本文中的功能仅存在于hibernate3中。参考文件hibernate3源代码中的org.hibernate.test.hql包下的BulkManipulationTest.java

hibernate2中对于批量操作的处理方法是,查询得到所有符合条件的数据库数据的主键,然后对根据主键对每条数据进行操作。这样感觉既费时又费力。最新Hibernate3中提供批量更新操作功能。例如:

String hqlUpdate = “ UPDATE user u “+
“ SET u.username
=:newUsername, u.password=:newPassword ”+
“ WHERE u.username
=:username and u.password=:password “;
Query query 
= session.createQuery(hqlUpdate);
query.setString(
"username",”hfm”);
query.setString(
"password",”1”);
query.setString(
"newUsername",”ps”);
query.setString(
"newPassword",”123”);
int num = query.executeUpate();
ts.commit();

String hqlDelete = “ DELETE FROM user u “+
“ WHERE u.username
=:username and u.password=:password “;
query.setString(
"username",”ps”);
query.setString(
"password",”123”);
int num = query.executeUpate();
ts.commit();

变量session的类型为org.hibernate.Session;ts的类行为为org.hibernate.Transaction;返回值num表示有几条数据被操作了。以上两段代码执行后在控制台中打出来的SQL分别是:

Hibernate: update CUSTOMER user0_ set user0_.USERNAME=?, user0_.PASSWORD=? where (user0_.USERNAME=? and user0_.PASSWORD=?)

Hibernate: delete from CUSTOMER user0_ where (user0_.USERNAME=? and user0_.PASSWORD=?)

以上是我认为比较好的方法。但是注意,产生的第二条语句不能在MySql中执行,但是hql仍然可以被编译成sql,不知道是我语法写错了还是bug?有谁了解可以给我maillippea@sohu.com。另外在参考文件BulkManipulationTest.java中有一个方法:

public QueryTranslatorImpl assertTranslation(String hql) throws QueryException, MappingException;

这个方法我不知道是干嘛的,但是我尝试了按照这种形式进行批量操作:

String hqlDelete = “ DELETE FROM user u “+
“ WHERE u.username
=:username and u.password=:password “;
 Object[] objects 
= new Object[]{“hfm”,”1”}
 Type[] types
=new Type[]{(Type)Hibernate.STRING,(Type)Hibernate.STRING};
QueryParameters queryParas 
= new QueryParameters(types,objects);
QueryTranslatorFactory ast 
= new ASTQueryTranslatorFactory();
QueryTranslator newQueryTranslator 
= 
     ast.createQueryTranslator(hqlDelete, Collections.EMPTY_MAP,
     (SessionFactoryImplementor)sf );
newQueryTranslator.compile( Collections.EMPTY_MAP, 
false );
int num = newQueryTranslator.executeUpdate(queryParas,
               (SessionImplementor)session);

sf的类型为org.hibernate.SessionFactorysession的类型为org.hibernate.Session。使用这种方法的结果与上面那种方法的结果相同,但是在对hql中变量进行赋值很不方便,我也没发现这种方法有什么更广泛的用处。或许有别的方法赋值,或者其它用处?

posted on 2005-05-27 17:36 lippea'blog 阅读(1406) 评论(1)  编辑  收藏 所属分类: Hibernate

FeedBack:
# re: 使用hibernate进行批量更新和删除操作
2006-03-05 02:06 | zhaoce
我也使用了SessionImplementor接口去强制转换Session session
以便我更方便地使用Dialect对象去包装我的sql语句
但是我总担心,这样操作会不会哪一天出什么问题
万一哪天SessionImpl extends AbstractSession implements SessionImplementor不再有效
那就完蛋了  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: