我在数据访问层使用的是JPA-2.0和Hibernate。在Hibernate的EmptyInterceptor中注入JPA的实体管理器
对于审计记录的目的,我使用Hibernate的EmptyInterceptor通过配置以下属性在persistence.xml中:
<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);
}
}
我想注入JPA实体管理器中“AuditLogInterceptor”这样我就可以像在“AuditLogInterceptor”执行数据库操作我抽象的DAO。
任何想法?什么应该是适当的解决方案?
线程安全性如何? –
我想在JPA2中做到这一点,以获得对我的auditLogRepository的引用,因为使用@Resource注解没有注入任何东西,并给我留下了NPE。 – Stephane