Injecting JPA's Entity Manager in Hibernate's EmptyInterceptor

后端 未结 2 1809
误落风尘
误落风尘 2021-02-14 19:51

I am using JPA-2.0 with Hibernate in my data access layer.

For audit logging purposes, I am using Hibernate\'s EmptyInterceptor by configuring below property in persiste

2条回答
  •  旧时难觅i
    2021-02-14 20:58

    I have got a simple way to perform database operation using JPA Entity Manager in 'AuditLogInterceptor'

    I have created below class that will give the application context reference:

    @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;
            }
        }
    

    Created Data access class:

    @Repository("myAuditDAO")
    public class myAuditDAO {
    
        private final transient Class persistentClass;
    
        protected transient EntityManager entityManager;
    
        @SuppressWarnings("unchecked")
        public MyDAO() {
    
            this.persistentClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
    
        @PersistenceContext
        public final void setEntityManager(final EntityManager entityMgrToSet) {
    
            this.entityManager = entityMgrToSet;
        }
    
        public final Class 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);
        }
    }
    

    And used 'ApplicationContextProvider' in 'AuditLogInterceptor' to get the reference of 'MyAuditDAO' that is having JPA entity manager as a property which is injected during DAO initialization. Now with the help of 'MyAuditDAO' I can perform database operations.

    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);
    
        }  
    } 
    

提交回复
热议问题