hibernate批量删除和更新数据
转载自:http://blog.csdn.net/yuhua3272004/article/details/2909538
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)但没法解释批量更新语句了。
大批量更新/删除(Bulk update/delete)
就像已经讨论的那样,自己主动和透明的 对象/关系 映射(object/relational mapping)关注于管理对象的状态。 这就意味着对象的状态存在于内存,因此直接更新或者删除 (使用 SQL 语句 UPDATE 和 DELETE) 数据库中的数据将不会影响内存中的对象状态和对象数据。 只是,Hibernate提供通过Hibernate查询语言来运行大批 量SQL风格的(UPDATE)和(DELETE) 语句的方法。
UPDATE 和 DELETE语句的语法为: ( UPDATE | DELETE ) FROM? ClassName (WHERE WHERE_CONDITIONS)?。 有几点说明:
在FROM子句(from-clause)中,FROMkeyword是可选的
在FROM子句(from-clause)中仅仅能有一个类名,而且它不能有别名
不能在大批量HQL语句中使用连接(显式或者隐式的都不行)。只是在WHERE子句中能够使用子查询。
整个WHERE子句是可选的。
举个样例,使用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() 的人们而设定的)
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映射方式的子类的表。
------------------------------------------------------------------------------------------------
我在 spring + hibernate 中 使用
String sql = "delete PlanPackageRelations where ppfId = "+ppfId;
int a = this.getHibernateTemplate().getSessionFactory().openSession().createQuery(sql).executeUpdate();
结果控制台输出一下信息:
在本地事务包括边界中使用的资源 jdbc/cnas 的可分享连接 MCWrapper id 19911991 Managed connectioncom.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl@12781278 State:STATE_TRAN_WRAPPER_INUSE
-------------------------------------------------------------------------------------------------
调用jdbc 处理依据非主键删除。
/**
* 依据ppfId ,删除PlanPackageRelations。
* @param ppfId
*/
public void deletePlanPackageRelations(String ppfId){
final String ppfIdFinal = ppfId;
try {
this.getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException, SQLException {
List result = new ArrayList();
String sql = "delete PlanPackageRelations where ppfId = :ppfId";
Query query = session.createQuery(sql).setString("ppfId",ppfIdFinal);
result.add(new Integer(query.executeUpdate()));
return result;
}
});
// String sql = "delete PlanPackageRelations where ppfId = "+ppfId;
// int a = this.getHibernateTemplate().getSessionFactory().openSession().createQuery(sql).executeUpdate();
//
}catch(DataAccessException t){
t.printStackTrace();
throw t;
}catch (Exception e) {
e.printStackTrace();
}
}
--------------------------------------------------------------------------------------------
使用HibernateTemplate批量删除数据
使用spring + hibernate框架中,一般使用hibernateTemplate来使用Hibernate,但hibernateTemplate
的 bulkUpdate()不能实现动态的批量删除,即使用bulkUplate时要事先确定下占位符”?“的个数,然后再使用其重载方法 bulkUpdate(queryString, Object[]),此时,Object[]内的元素个数就要跟queryString中的占位符“?”的个数相等,使用十分麻烦,因此能够使用 HibernateCallback回调函数来进行动态批量删除,即能够不考虑要删除元素的个数。详细用法例如以下例:
public void bulkDelete(final Object[] ids) throws Exception {
final String queryString = "delete PersistentModel where id in (:ids) ";
super.execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createQuery(queryString);
query.setParameterList("ids", ids);
return query.executeUpdate();
}
});
}
注:标红处的占位符要加上(),否则会抛出语法错误异常。
-----------------------------------------------------------------------------------------
bulkUpdate 使用:
String updateSql = "update Rsceref ref set ref.rulecode = ? where ref.rscerefcode = ?";
getHibernateTemplate().bulkUpdate(updateSql, new Object[]{chkObj.getBmcrcode(),listExistRuleSql.get(0)});
this.getHibernateTemplate().bulkUpdate(sql);
hibernate批量删除和更新数据的更多相关文章
- 通过时间戳批量删除hbase的数据
如何通过时间戳批量删除hbase的数据 我们使用hive关联hbase插入数据时,有时会写错数据,此时hbase中的数据量已经很大很大了(上亿).此时,我们要修改错误的数据,只需要删除写错的那部分数据 ...
- 批量删除redis的数据
批量删除redis的数据 # redis-cli -h 192.168.1.17 -p 6379 keys "xiaolang_*"|xargs redis-cli -h 192. ...
- 如何通过PhpMyAdmin批量删除MYSQL数据库数据表
使用这个方法前,强烈建议先备份整个数据库.至于怎么备份?你不会么?在本文下方留言吧. 具体方法:复制下面的php执行语句,保存为sql.php文件(注意配置数据库名称.密码.数据表头),通过ftp上传 ...
- hibernate批量删除写法
1.批量删除正常写法,此方式在海量数据删除时可能有效率问题 private static final String DELETE_USER_NAME= "DELETE FROM User x ...
- SQL server 批量插入和更新数据
批量插入数据 insert into A表数据库名.[dbo].A(a,b,c) (select a,b,c from B表数据库名.[dbo].B) 批量更新数据 根据身份证第二位更新性别 upda ...
- mybatis 注解的方式批量插入,更新数据
一,当向数据表中插入一条数据时,一般先检查该数据是否已经存在,如果存在更新,不存在则新增 使用关键字 ON DUPLICATE KEY UPDATE zk_device_id为主键 model ...
- sequelize 批量添加和更新数据 bulkCreate
sequelize提供了批量插入数据的方法:Model.bulkCreate([…object]). 例如: let updatePhone = [{userName: '李白‘},{userNam ...
- hibernate 级联删除报更新失败的问题(org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update)
首先hibernate级联删除的前提是,首先需要在映射文件中配置,配置多表之间的关联关系: 下面以部门表(Dept)和员工表(Emp)为例: 1.在Emp.hbm.xml映射文件中配置many-to- ...
- .Net中DataAdapter批量插入和更新数据总结
前言 前段时间一直在忙着项目上线,在做项目的同时遇到了一些之前不曾碰到的问题,因为没有经验,只能从网上找一些相关的解决方案,但是网上提供的资料实在是太杂,有的根本不能用,耗时又耗力. 我希望把我这段时 ...
随机推荐
- AngularJS学习-初识
angularJS定义和特点 1.google前端开源框架 2.MVVM(model view view-model)设计模式 : Model将和ViewModel互动(通过$scope对象),将监听 ...
- Android特效--粒子效果之雨
1. 单个雨点的行为 2. 完善雨点的行为和构造下雨场景 3. 在XML中定义可以控制下雨的属性 --------------------------------------------------- ...
- UIActionViewController 详解 iOS8
iOS8推出了几个新的“controller”,主要是把类似之前的UIAlertView变成了UIAlertController,这不经意的改变,貌似把我之前理解的“controller”一下子推翻了 ...
- 原生js实现吸顶导航和回到顶部特效
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- C++结构简介
结构是一种比数组更灵活的数据格式,因为同一个结构可以储存多种类型的数据,这使得能够将篮球运动员的信息放在一个结构中,从而将数据的表示的合并到一起. 结构也是C++堡垒OOP(类)的基石.结构是用户定义 ...
- Codeforces 712C Memory and De-Evolution
Description Memory is now interested in the de-evolution of objects, specifically triangles. He star ...
- Reactor Cooling
sgu194:http://acm.sgu.ru/problem.php?contest=0&problem=194 题意:题目大意:给n个点,及m根pipe,每根pipe用来流躺液体的,单向 ...
- 一些记录查询的SQL语句
-- ======================== 第三天 =========================== CREATE DATABASE php0408 CHARSET utf8 ;CR ...
- Static Classes and Static Class Members
Static Classes and Static Class Members A static class is basically the same as a non-static class, ...
- [LeetCode#212]Word Search II
Problem: Given a 2D board and a list of words from the dictionary, find all words in the board. Each ...