簡體   English   中英

Spring Boot 2.0.x EntityManagerFactory為空

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM