簡體   English   中英

在Hibernate的EmptyInterceptor中注入JPA的實體管理器

[英]Injecting JPA's Entity Manager in Hibernate's EmptyInterceptor

我在我的數據訪問層使用JPA-2.0和Hibernate。

出於審計日志記錄的目的,我通過在persistence.xml中配置下面的屬性來使用Hibernate的EmptyInterceptor:

<property name="hibernate.ejb.interceptor"  
                value="com.mycom.audit.AuditLogInterceptor" /> 

AuditLogInterceptor擴展了hibernate的' org.hibernate.EmptyInterceptor '。

public class AuditLogInterceptor extends EmptyInterceptor {  

    private Long userId;  

    public AuditLogInterceptor() {}  

    @Override  
    public boolean onSave(Object entity, Serializable id, Object[] state,  
            String[] propertyNames, Type[] types) throws CallbackException {  
        // Need to perform database operations using JPA entity manager
        return false;  
    }  

   @Override
    public boolean onFlushDirty(Object entity, Serializable id,
            Object[] currentState, Object[] previousState,
            String[] propertyNames, Type[] types) {
        // other code here        
        return false;
    }

    @Override  
    public void postFlush(Iterator iterator) throws CallbackException {  
        System.out.println("I am on postFlush");
        // other code here 
    }  
}  

我在數據訪問層中使用JPA實體管理器來執行數據庫操作。 JPA配置如下:

<bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:persistenceUnitName="PersistenceUnit"
        p:persistenceXmlLocation="classpath*:persistence.xml"
        p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
        <property name="loadTimeWeaver">
            <bean
                class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
        </property>
    </bean>

我的AbstractDAO是:

public class AbstractDao<T, ID extends Serializable> {

    private final transient Class<T> persistentClass;

    protected transient EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public AbstractDao() {

        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @PersistenceContext
    public final void setEntityManager(final EntityManager entityMgrToSet) {

        this.entityManager = entityMgrToSet;
    }

    public final Class<T> getPersistentClass() {

        return persistentClass;
    }

    public final void persist(final T entity) {

         entityManager.persist(entity);       
    }

}

我想在'AuditLogInterceptor'中注入JPA實體管理器,以便我可以在'AuditLogInterceptor'中執行數據庫操作,就像我的抽象DAO一樣。

任何的想法? 什么應該是正確的解決方案?

我有一個簡單的方法來使用'AuditLogInterceptor'中的JPA實體管理器來執行數據庫操作

我創建了下面的類,它將提供應用程序上下文引用:

@Component("applicationContextProvider")
    public class ApplicationContextProvider implements ApplicationContextAware {
        private static ApplicationContext context;

        public static ApplicationContext getApplicationContext() {
            return context;
        }

        @Override
        public void setApplicationContext(ApplicationContext ctx) {
            context = ctx;
        }
    }

創建數據訪問類:

@Repository("myAuditDAO")
public class myAuditDAO<T, ID extends Serializable> {

    private final transient Class<T> persistentClass;

    protected transient EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public MyDAO() {

        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @PersistenceContext
    public final void setEntityManager(final EntityManager entityMgrToSet) {

        this.entityManager = entityMgrToSet;
    }

    public final Class<T> getPersistentClass() {

        return persistentClass;
    }

    public final T findById(final ID theId) {

        return entityManager.find(persistentClass, theId);
    }

    public final void persist(final T entity) {

        entityManager.persist(entity);
    }

    public final void merge(final T entity) {

        entityManager.merge(entity);
    }
}

並在'AuditLogInterceptor'中使用'ApplicationContextProvider'來獲取具有JPA實體管理器的'MyAuditDAO'的引用,該實體管理器是在DAO初始化期間注入的屬性。 現在在'MyAuditDAO'的幫助下,我可以執行數據庫操作。

public class AuditLogInterceptor extends EmptyInterceptor {  

    @Override  
    public void postFlush(Iterator iterator) throws CallbackException {  

      // Here we can get the MyAuditDao reference and can perform persiste/merge options
       MyAuditDao myAuditDao = (MyAuditDao ) ApplicationContextProvider.getApplicationContext().getBean("myAuditDao");

      //  myAuditDao.persist(myEntity);

    }  
} 

我正在考慮在您的Abstract類中成功啟動persistenceManager 您可能有一個AuditLogDAO類,它擴展了您的AbstractDao 將AuditLogDAO類注入攔截器並調用auditLogDAO.save(entity); 和其他方法。

或編寫一個執行數據庫操作的Util類,並將util類注入攔截器。

暫無
暫無

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

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