Wstrzykiwanie menedżera Entity JPA w EmptyInterceptor Hibernate
Używam JPA-2.0 z Hibernate w mojej warstwie dostępu do danych.
Do celów rejestrowania inspekcji używam EmptyInterceptor Hibernate, konfigurując poniższą właściwość w persistence.xml:
<property name="hibernate.ejb.interceptor"
value="com.mycom.audit.AuditLogInterceptor" />
GdzieAuditLogInterceptor rozszerza hibernację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
}
}
Korzystam z menedżera encji JPA w warstwie dostępu do danych w celu wykonywania operacji na bazie danych. Konfiguracja JPA jest jak poniżej:
<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>
Moje AbstractDAO to:
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);
}
}
Chciałbym wstrzyknąć menedżera encji JPA do 'AuditLogInterceptor', aby móc wykonywać operacje na bazach danych w 'AuditLogInterceptor', jak mój abstrakcyjny DAO.
Dowolny pomysł? Jakie powinno być właściwe rozwiązanie?