hibernate批量删除和更新数据
轉(zhuǎn)載自:http://blog.csdn.net/yuhua3272004/article/details/2909538
Hibernate3.0 採(cǎi)用新的基于ANTLR的HQL/SQL查詢翻譯器,在Hibernate的配置文件里,hibernate.query.factory_class屬性用來(lái)選擇查詢翻譯器。
(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)否則不能解釋批量更新的語(yǔ)句。選擇(2)但沒(méi)法解釋批量更新語(yǔ)句了。
大批量更新/刪除(Bulk update/delete)
就像已經(jīng)討論的那樣,自己主動(dòng)和透明的 對(duì)象/關(guān)系 映射(object/relational mapping)關(guān)注于管理對(duì)象的狀態(tài)。 這就意味著對(duì)象的狀態(tài)存在于內(nèi)存,因此直接更新或者刪除 (使用 SQL 語(yǔ)句 UPDATE 和 DELETE) 數(shù)據(jù)庫(kù)中的數(shù)據(jù)將不會(huì)影響內(nèi)存中的對(duì)象狀態(tài)和對(duì)象數(shù)據(jù)。 只是,Hibernate提供通過(guò)Hibernate查詢語(yǔ)言來(lái)運(yùn)行大批 量SQL風(fēng)格的(UPDATE)和(DELETE) 語(yǔ)句的方法。
UPDATE 和 DELETE語(yǔ)句的語(yǔ)法為: ( UPDATE | DELETE ) FROM? ClassName (WHERE WHERE_CONDITIONS)?。 有幾點(diǎn)說(shuō)明:
在FROM子句(from-clause)中,FROMkeyword是可選的
在FROM子句(from-clause)中僅僅能有一個(gè)類名,而且它不能有別名
不能在大批量HQL語(yǔ)句中使用連接(顯式或者隱式的都不行)。只是在WHERE子句中能夠使用子查詢。
整個(gè)WHERE子句是可選的。
舉個(gè)樣例,使用Query.executeUpdate()方法運(yùn)行一個(gè)HQL UPDATE語(yǔ)句:?
?
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();
運(yùn)行一個(gè)HQL DELETE,相同使用 Query.executeUpdate() 方法 (此方法是為 那些熟悉JDBC PreparedStatement.executeUpdate() 的人們而設(shè)定的)
?
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()方法返回的整型值表明了受此操作影響的記錄數(shù)量。 注意這個(gè)數(shù)值可能與數(shù)據(jù)庫(kù)中被(最后一條SQL語(yǔ)句)影響了的“行”數(shù)有關(guān),也可能沒(méi)有。一個(gè)大批量HQL操作可能導(dǎo)致多條實(shí)際的SQL語(yǔ)句被運(yùn)行, 舉個(gè)樣例,對(duì)joined-subclass映射方式的類進(jìn)行的此類操作。這個(gè)返回值代表了實(shí)際被語(yǔ)句影響了的記錄數(shù)量。在那個(gè)joined-subclass的樣例中, 對(duì)一個(gè)子類的刪除實(shí)際上可能不只會(huì)刪除子類映射到的表并且會(huì)影響“根”表,還有可能影響與之有繼承關(guān)系的joined-subclass映射方式的子類的表。
?
------------------------------------------------------------------------------------------------
?
我在 spring + hibernate 中 使用
String sql = "delete PlanPackageRelations? where ppfId = "+ppfId;
int a = this.getHibernateTemplate().getSessionFactory().openSession().createQuery(sql).executeUpdate();
結(jié)果控制臺(tái)輸出一下信息:?
在本地事務(wù)包括邊界中使用的資源 jdbc/cnas 的可分享連接 MCWrapper id 19911991? Managed connectioncom.ibm.ws.rsadapter.spi.WSRdbManagedConnectionImpl@12781278?State:STATE_TRAN_WRAPPER_INUSE
?
-------------------------------------------------------------------------------------------------
?
調(diào)用jdbc 處理依據(jù)非主鍵刪除。
/**
? * 依據(jù)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批量刪除數(shù)據(jù)
? 使用spring + hibernate框架中,一般使用hibernateTemplate來(lái)使用Hibernate,但hibernateTemplate
的 bulkUpdate()不能實(shí)現(xiàn)動(dòng)態(tài)的批量刪除,即使用bulkUplate時(shí)要事先確定下占位符”?“的個(gè)數(shù),然后再使用其重載方法 bulkUpdate(queryString, Object[]),此時(shí),Object[]內(nèi)的元素個(gè)數(shù)就要跟queryString中的占位符“?”的個(gè)數(shù)相等,使用十分麻煩,因此能夠使用 HibernateCallback回調(diào)函數(shù)來(lái)進(jìn)行動(dòng)態(tài)批量刪除,即能夠不考慮要?jiǎng)h除元素的個(gè)數(shù)。詳細(xì)用法例如以下例:
??? 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();
??? ??? ??? }
??? ??? });
??? }
注:標(biāo)紅處的占位符要加上(),否則會(huì)拋出語(yǔ)法錯(cuò)誤異常。
?
-----------------------------------------------------------------------------------------
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);
總結(jié)
以上是生活随笔為你收集整理的hibernate批量删除和更新数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: X/Open DTP模型与XA协议的学习
- 下一篇: 与服务器交互的分页组件PageCompo