簡體   English   中英

休眠:在插入或更新上執行自定義邏輯和SQL語句

[英]Hibernate: Execute custom logic and SQL statements on Insert or Update

我正在使用舊數據庫,每當將某些內容保存到其表之一中時,就需要執行一些自定義邏輯。 這包括檢查幾個字段以查看已更改的數據類型,以適當的更改狀態更新字段,更新表中的其他行,然后最終插入新行或更新現有行。

顯然,這比@SQLInsert或@SQLUpdate批注能做的更多。 什么是實現這一目標的最佳方法? 我需要在對象將要保存時被調用的東西,執行一些手動SQL調用,然后取消內置的保存功能,因為我們要小心地手動處理它。

您可以為此使用“自定義事件監聽器”。 請參閱http://grails.github.io/grails-doc/2.5.x/guide/single.html#eventsAutoTimestamping (“ 自定義事件監聽器”部分)。

一個例子是:

import org.grails.datastore.mapping.engine.event.PreUpdateEvent
import org.grails.datastore.mapping.engine.event.PreInsertEvent
import org.grails.datastore.mapping.engine.event.EventType
import org.springframework.context.ApplicationEvent
import org.grails.datastore.mapping.core.Datastore

class CustomSavePersistenceListener extends AbstractPersistenceEventListener {

   public CustomSavePersistenceListener(final Datastore datastore) {
      super(datastore)
   }

   @Override
   public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
      eventType in [ PreUpdateEvent, PreInsertEvent ]
   }

   @Override 
   protected void onPersistenceEvent(final AbstractPersistenceEvent event) {
      if (needsToBeCustomSaved(event.entityObject)) {
         doCustomSave(event.eventType, event.entityObject) 
         event.cancel()
      }
   }

   private boolean needsToBeCustomSaved(object) {
       // Your conditions to decide if needs special persistence
   }

   private void doCustomSave(EventType eventType, object) {
      // Your special persistence logic
   }
}

一旦准備好課程,別忘了注冊。 在Bootstrap的init閉包中,您可以添加:

application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
   applicationContext.addApplicationListener(new CustomSavePersistenceListener(datastore)
}

如果定義了多個數據源,則可能需要在調用each方法之前過濾它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM