2

I need to create DB log events for every DB insert but the the sessionfactory is null in my Hibernate interceptor. What's the simplest way for getting a hibernate session in your interception when you are using spring boot.

public class Interceptor extends EmptyInterceptor {

@Autowired
SessionFactory session; //this is null not in the spring scope

public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
 sessionFactory.getCurrentSession()......
lars1595
  • 886
  • 3
  • 12
  • 27
  • Why not simply use Hibernate Envers for this? – M. Deinum Jun 01 '15 at 12:20
  • Envers looks good but i'm kind of stucked with the current And i basically have to do a sql insert to a specific table when object is persisted. – lars1595 Jun 01 '15 at 13:16
  • Did you take a look on http://stackoverflow.com/questions/25283767/how-to-use-spring-managed-hibernate-interceptors-in-spring-boot ? – mp911de Jun 01 '15 at 13:24
  • That solution seems so complex, I only want to get the current open hibernate session in the current thread. Arent there any static util that holds current session – lars1595 Jun 01 '15 at 13:34

1 Answers1

0

You can get hibernate session by injecting @PersistenceContext private EntityManager entityManager; and then calling entityManager.unwrap(Session.class)

Đuro
  • 61
  • 2
  • The @PersistenceContext private EntityManager entityManager is null Spring don't seem to inject it. – lars1595 Jun 02 '15 at 06:50
  • Well, your `Interceptor` class is POJO, it is not managed by Spring container and therefore you cannot inject anything in it. You could annotate it with `@Component` which would fix injection problem, but that might cause problems down the line. – Đuro Jun 02 '15 at 07:51
  • The @Component did not help so hard to get the sessionFactory from spring when you outside the IOC – lars1595 Jun 02 '15 at 08:17