如何将spring repo注入hibernate拦截器

时间:2016-08-10 21:10:39

标签: spring hibernate interceptor

我们正在构建一个应用程序,我们需要将实体更新记录到History表中。我试图通过hibernate拦截器来实现这一点,并且我们能够管理以获得所有更改但是难以将它们插入到审计表中。

我的JPA配置

public class JPAConfiguration {
 ----
 @Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws SQLException {
    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(dataSource());
    factoryBean.setPackagesToScan(new String[] {"com.yyy.persist"});

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setShowSql(true);
    // thsi is required in order to enable Query DSL
    vendorAdapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect");
    factoryBean.setJpaVendorAdapter(vendorAdapter);
   // factoryBean.setMappingResources(mappingResources);
    // adding hibernate interceptor

    Properties jpaProperties = new Properties();
    jpaProperties.setProperty("hibernate.ejb.interceptor", "com.yyy.admin.service.AuditInterceptor");
    factoryBean.setJpaProperties(jpaProperties);
    return factoryBean;
}

我的拦截器

public class AuditInterceptor extends EmptyInterceptor {
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
        String[] propertyNames, Type[] types) {

     if ( entity instanceof Auditable ) {
    // updates++;

    for (int i = 0; i < propertyNames.length; i++) {

        if ((currentState[i] == null && previousState[i] != null)
                || (currentState[i] != null && previousState[i] == null) || (currentState[i] != null
                        && previousState[i] != null && !currentState[i].equals(previousState[i]))) {

            AuditLog audit = new AuditLog();
            audit.setAction("UPDATE");
            audit.setFieldChanged(propertyNames[i]);
            audit.setOldvalue(previousState[i] != null ? previousState[i].toString() : "");
            audit.setNewvalue(currentState[i] != null ? currentState[i].toString() : "");
            audit.setTimeStamp(new Date());
            audit.setUsername(userName);

            entities.add(audit);
        }
    }

    // iterate elements on the report build a entity
 }
    return false;
}

public void afterTransactionCompletion(Transaction tx) {

    if (tx.wasCommitted()) {
if (entities != null) {
            for (AuditLog e : entities) {
                System.out.println(e);
                //.save(e);
            }
            entities = new ArrayList<AuditLog>();
        }
    }
     }

}

在postTransactionCompletion方法中的

我需要将所有审计实体写入DB,Autowire不能正常工作,因为这不是Spring托管bean,有没有办法在这个方法中获取DB会话,以便我可以执行插入。?

2 个答案:

答案 0 :(得分:4)

将Spring Bean注入非Spring托管类的典型解决方案是通过静态资源持有者。例如,你有一个名为StaticServiceHolder的类,annotate与@Component一起,然后为你想要通过setter注入的spring bean创建静态字段。像:

@Component
public class StaticServiceHolder
{
    public static AuditService auditService;

    @Autowired
    public void setAuditService(AuditService auditService)
    {
        StaticServiceHolder.auditService = auditService;
    }
}

或者如果你需要注射很多这些东西,那就更容易了,那么你可以自动装配ApplicationContext。这样你就可以得到你需要的任何豆子。

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        ApplicationContextHolder.applicationContext = ctx;
    }
}

....
//in your hibernate interceptor
YourAuditService auditService = ApplicationContextHolder.applicationContext.getBean(YourAuditService.class);
auditService.saveAuditLog();

无论哪种方式,只要您使用的服务是Transactional,您就应该能够在数据库中保留您的资料。希望这对你有用。

对于事务管理器设置:

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf)
{
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

答案 1 :(得分:-1)

我知道这有点晚了,但也许对其他人有帮助。 通过使用spring bean而不是class name作为"hibernate.ejb.interceptor"的值,hibernate使用spring bean而不是实例化一个新类。

更多内容请点击此处: Autowired to hibernate Interceptor