@PostConstruct中没有可用的事务性实体管理器 [英] No transactional entitymanager available in @PostConstruct
问题描述
entityManager.unwrap(SessionImplementor.class)
原因没有事务性的entitymanager可用
代码:
@Component
public class HibernateEventWiring {
$ b $ @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);
$ b @Transactional
private SessionFactory getSessionFactory(){
// EXCEPTION:无事务型实体管理器可用
返回entityManager.unwrap(SessionImplementor.class) .getFactory();
$ div $解析方案
在@PostConstruct中(与InitializingBean接口中的afterPropertiesSet一样),没有办法确保所有的后处理已经完成,所以(的确)不会有事务。
< blockquote>
正如我所看到的,您不需要事务,也不需要实体管理器bean,而是实体管理器工厂bean。我认为你应该简单地自动调用EntityManagerFactory,然后从中解开Hibernate SessionFactory。
@Autowired $ b $ private EntityManagerFactory entityManagerFactory ;
@PostConstruct
public void registerListeners(){
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
...
}
Problem:
entityManager.unwrap(SessionImplementor.class)
causeno transactional entitymanager available
exception.Code:
@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(); } }
解决方案According to 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.
As I see, you do not need a transaction nor an entity manager bean, but rather an entity manager factory bean. I think you should simply autowire the EntityManagerFactory and then unwrap the Hibernate SessionFactory from it.
@Autowired private EntityManagerFactory entityManagerFactory; @PostConstruct public void registerListeners() { SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); ... }
这篇关于@PostConstruct中没有可用的事务性实体管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!