![](/img/trans.png)
[英]EntityManagerFactory must not be null after migrate to hibernate 5.2.6 in spring boot
[英]Spring Boot 2.0.x EntityManagerFactory Null
我试图使用Hibernate SessionFactory从Mysql中获取数据,并试图从EntityManagerFactory中解开SessionFactory。
这段代码在Spring Boot 1.5.x中可以正常工作,但在2.0.x中却不能正常工作
@Configuration
public class SessionFactoryConfig {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("Factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
}
谁能帮我解决这个问题? 任何帮助都将得到高度重视。 谢谢!
正如@ m-deinum在评论中指出的那样,如果您确实要使用SessionFactory
,则可以避免创建SessionFactory
并使用注入的EntityManager
实例直接在存储库对象中访问它。
例如:
@Repository
public class MyRepository {
@Autowired
private EntityManagerFactory emf;
public void saveEntity(Foo foo) {
emf.unwrap(SessionFactory.class).getCurrentSession().saveOrUpdate(foo);
}
@Override
public Foo getEntity(Integer id) {
return emf.unwrap(SessionFactory.class).getCurrentSession().get(Foo.class, id);
}
}
希望对您有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.