我有一个简单的方法可以在“ 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”来获取“
MyAuditDAO”的引用,该引用具有JPA实体管理器作为在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); } }


