Is it possible to integrate Spring managed Hibernate interceptors (http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch14.html) in Spring Boot?
I'm using Spring Data JPA and Spring Data REST and need an Hibernate interceptor to act on an update of a particular field on an entity.
With standard JPA events it's not possible to get the old values, and hence I think I need to use the Hibernate interceptor.
Taking the several threads as reference I ended up with the following solution:
I am using Spring-Boot 1.2.3.RELEASE (which is the current ga at the moment)
My use case was that described in this bug (DATAREST-373).
I needed to be able to encode the password of a
User
@Entity
upon create, and have special logic upon save. The create was very straightforward using@HandleBeforeCreate
and checking the@Entity
id for0L
equality.For the save I implemented a Hibernate Interceptor which extends an EmptyInterceptor
Using spring boot the documentation states that
As many references stated, we can defined our interceptor using
spring.jpa.properties.hibernate.ejb.interceptor
in our Spring-Boot configuration. However I couldn't get the@Autowire PasswordEncoder
to work.So I resorted to using HibernateJpaAutoConfiguration and overriding
protected void customizeVendorProperties(Map<String, Object> vendorProperties)
. Here is my configuration.Autowiring the
Interceptor
instead of allowing Hibernate to instantiate it was the key to getting it to work.What bothers me now is that the logic is split in two, but hopefully once DATAREST-373 is resolved then this wont be necessary.
Because the interceptor do not register as a spring bean,you can use a util which can get
ApplicationContext
instance,like this:Then you can call the service in the interceptor,like this:
My simple one file example of hibernate listeners for spring boot (spring-boot-starter 1.2.4.RELEASE)