2013-03-28 90 views
1

我正在使用spring和hibernate。 Hibernate 4.2聲明Ejb3Configuration已過時,並且它沒有方法getEventListeners允許設置偵聽器。這個班曾經拿到EntityManagerFactory休眠:從3.6.9遷移到4.2

我使用它來進行數據庫試聽(記錄更新,插入,刪除事件)。我應該如何獲得EntityManagerFactory與試聽配置?

public class HibernateExtendedPersistenceProvider extends HibernatePersistence { 

    private PostInsertEventListener[] postInsertEventListeners; 
    private PostUpdateEventListener[] postUpdateEventListeners; 
    private PostDeleteEventListener[] postDeleteEventListeners; 

    @SuppressWarnings("rawtypes") 
    @Override 
    public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { 
     Ejb3Configuration cfg = new Ejb3Configuration(); 
     setupConfiguration(cfg); 
     Ejb3Configuration configured = cfg.configure(persistenceUnitName, properties); 
     return configured != null ? configured.buildEntityManagerFactory() : null; 
    } 

    @SuppressWarnings("rawtypes") 
    @Override 
    public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) { 
     Ejb3Configuration cfg = new Ejb3Configuration(); 
     setupConfiguration(cfg); 
     Ejb3Configuration configured = cfg.configure(info, properties); 
     return configured != null ? configured.buildEntityManagerFactory() : null; 
    } 

    private void setupConfiguration(Ejb3Configuration cfg) { 
     // 4.2: Ejb3Configuration deprecated and has no method getEventListeners 
     cfg.getEventListeners().setPostInsertEventListeners(postInsertEventListeners); 
     cfg.getEventListeners().setPostDeleteEventListeners(postDeleteEventListeners); 
     cfg.getEventListeners().setPostUpdateEventListeners(postUpdateEventListeners); 
    } 

    public void setPostInsertEventListeners(PostInsertEventListener[] postInsertEventListeners) { 
     this.postInsertEventListeners = postInsertEventListeners; 
    } 

    public void setPostUpdateEventListeners(PostUpdateEventListener[] postUpdateEventListeners) { 
     this.postUpdateEventListeners = postUpdateEventListeners; 
    } 

    public void setPostDeleteEventListeners(PostDeleteEventListener[] postDeleteEventListeners) { 
     this.postDeleteEventListeners = postDeleteEventListeners; 
    } 
} 
+0

爲什麼不使用JPA'EntityListener'註解?我相信他們服務於相同的目的。 – 2013-03-28 05:13:42

+0

你能舉個例子嗎? – Damask 2013-03-28 05:20:20

回答

0

如果你有控制源代碼,我會看看hibernate envers。它在版本控制方面做得很好。它不僅僅是一個像更新一樣的審計軌跡,而是跟蹤舊的實體版本。

JPA實體監聽器api的缺點是,在更改之前您無法輕鬆訪問原始值。你將不得不從某處獲取這些值來創建增量。

您仍然可以註冊您的hibernate事件偵聽器,但現在推薦的方法是使用SPI。查看Hibernate Integrator來看看它是如何完成的。