hibernate3 批次更新刪除資料

來源:互聯網
上載者:User

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)中,FROM關鍵字是可選的

在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 connection com.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);

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.