hsc*_*hsc 4 hibernate jpa spring-boot
我正在使用 springboot 1.5.x 并尝试按照本教程实现事件侦听器。
我遇到的阻碍是我不能用SpringBoot 1.5.x设置hibernate integrator?我试图properties.yml像下面的代码一样配置积分器,但它抛出了一个无法将字符串转换为积分器的异常:
spring:
jpa:
properties:
hibernate.integrator_provider: com.xxxxx.RootAwareEventListenerIntegrator
Run Code Online (Sandbox Code Playgroud)
这是一个相关的问题,但提供的解决方案不适用于 springBoot 1.5.x。
我从这里找到了一个可用的解决方案。它不使用集成器,而是将所有事件侦听器一一添加。下面是我的代码:
public class RootAwareInsertEventListener implements PersistEventListener {
public static final RootAwareInsertEventListener INSTANCE = new RootAwareInsertEventListener();
@Override
public void onPersist(PersistEvent event) throws HibernateException {
final Object entity = event.getObject();
if (entity instanceof RootAware) {
RootAware rootAware = (RootAware) entity;
Object root = rootAware.getRoot();
event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);
log.info("Incrementing {} entity version because a {} child entity has been inserted",
root, entity);
}
}
@Override
public void onPersist(PersistEvent event, Map createdAlready)
throws HibernateException {
onPersist(event);
}
}
Run Code Online (Sandbox Code Playgroud)
@Component
public class HibernateListenerConfigurer {
@PersistenceUnit
private EntityManagerFactory emf;
@PostConstruct
protected void init() {
SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.PERSIST).appendListener(RootAwareInsertEventListener.INSTANCE);
registry.getEventListenerGroup(EventType.FLUSH_ENTITY).appendListener(RootAwareUpdateAndDeleteEventListener.INSTANCE);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1792 次 |
| 最近记录: |