I did a lot of looking around on this for myself and thought I'd share what I got working (I included the helpful (non-inline) links at the bottom).
Interceptor
To use an interceptor, you extend the org.hibernate.EmptyInterceptor
class and override the methods you want to intercept.
You probably want onSave(...)
in your case.
package foo.bar;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import java.io.Serializable;
public class MyInterceptor extends EmptyInterceptor {
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
// do your checks here
return false;
}
}
You have to register your interceptor with Spring/Hibernate.
You can do this in your application.properties or application.yml.
spring:
jpa:
properties:
hibernate.ejb.interceptor: foo.bar.MyInterceptor
The upsides to an interceptor are that it is (potentially) less code and relatively simple configuration.
The downsides are that you can only have one for your entire application and the API can be confusing to work with.
Event Listener
For events, you implement one of Hibernate's org.hibernate.event.spi.*Listener
interfaces.
You probably want the org.hibernate.event.spi.PreInsertEventListener
in your case.
You have to register your event in the EventListenerRegistry
.
To do this, you can make your class a @Component
, @Autowire
the EntityManagerFactory
into your class, and create a @PostConstruct
method to register your class.
package foo.bar;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.PreInsertEvent;
import org.hibernate.event.spi.PreInsertEventListener;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
@Component
public class MyEventListener implements PreInsertEventListener {
@Autowired
private EntityManagerFactory entityManagerFactory;
@PostConstruct
private void init() {
SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(this);
}
@Override
public boolean onPreInsert(PreInsertEvent preInsertEvent) {
// do your checks here
return false;
}
}
The upsides to listeners are that you can have as many as you want, the API is nicer than the interceptor's, and the code and the configuration are all in one place.
The downside is that the configuration is longer and more involved.