一下代码纯属个人项目应用不喜勿喷。
参考链接
所有拦截器以及触发器
http://blog.csdn.net/ljhabc1982/article/details/6319251
Interceptor 加入到程序应用当中(配置)
第一步继承拦截器
import org.hibernate.EmptyInterceptor; import org.hibernate.type.Type; import org.springframework.context.annotation.Configuration;
import java.io.Serializable;
/** * Created by pw on 2016/12/16. */ @Configuration public class AuditLogInterceptor extends EmptyInterceptor {
@Override
public boolean onLoad(Object entity, Serializable id, Object\[\] state, String\[\] propertyNames, Type\[\] types) {
return false;
}
public boolean onFlushDirty(Object entity, Serializable id, Object\[\] currentState, Object\[\] previousState, String\[\] propertyNames, Type\[\] types) {
return false;
}
}
第二部 配置拦截器
spring: jpa: properties: hibernate: ejb: interceptor: com.**.AuditLogInterceptor
触发器应用配置
第一步创建触发器
import org.hibernate.HibernateException; import org.hibernate.event.spi.LoadEvent; import org.hibernate.event.spi.LoadEventListener; import org.springframework.stereotype.Component;
import java.util.EventListener;
/** * Created by pw on 2016/12/16. */ @Component public class MyLoadEventListener implements LoadEventListener{
public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException{
System.out.println("MyLoadEventListener -->onLoad");
}
}
第二部配置触发器
import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.jpa.HibernateEntityManagerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct; import javax.persistence.EntityManagerFactory;
/** * Created by pw on 2016/12/19. */ @Component public class HibernateListenersConfigurer { @Autowired private EntityManagerFactory entityManagerFactory;
@Autowired
private MyLoadEventListener loadEventListener;
@PostConstruct
public void registerListeners() {
HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) this.entityManagerFactory;
SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
System.out.println("\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*");
registry.getEventListenerGroup(EventType.LOAD).appendListener(loadEventListener);
}
}