gpt4 book ai didi

java - @PostConstruct 中没有可用的事务实体管理器

转载 作者:行者123 更新时间:2023-12-01 22:31:58 28 4
gpt4 key购买 nike

问题:entityManager.unwrap(SessionImplementor.class) 导致没有可用的事务实体管理器异常。

代码:

@Component
public class HibernateEventWiring {

@Autowired
private ViewListener listener;

@PersistenceContext(unitName = "config-punit")
private EntityManager entityManager;

@PostConstruct
public void registerListeners() {
SessionFactory sessionFactory = getSessionFactory();
EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(
EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(listener);
}

@Transactional
private SessionFactory getSessionFactory() {
// EXCEPTION: No transactional entitymanager available
return entityManager.unwrap(SessionImplementor.class).getFactory();
}
}

最佳答案

根据this excelent answer :

In the @PostConstruct (as with the afterPropertiesSet from the InitializingBean interface) there is no way to ensure that all the post processing is already done, so (indeed) there can be no Transactions.

正如我所见,您不需要事务,也不需要实体管理器 bean,而是需要实体管理器工厂 bean。我认为您应该简单地 Autowiring EntityManagerFactory,然后从中解开 Hibernate SessionFactory。

@Autowired
private EntityManagerFactory entityManagerFactory;

@PostConstruct
public void registerListeners() {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
...
}

关于java - @PostConstruct 中没有可用的事务实体管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27570641/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com