we are building one application where we need to log Entity updates in to History table. I am trying to achieve this by hibernate interceptor, and we could able to mange to get all the changes but having difficulties in inserting them into audit table.
My JPA configuration
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;
}
My Interceptor
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>();
}
}
}
}
in method afterTransactionCompletion I need to write all audit entities into DB, Autowire not working as this is not spring managed bean, is there any way to get DB session in this method so that I can perform inserts .?