【问题标题】:Spring Boot 2.0.x EntityManagerFactory NullSpring Boot 2.0.x EntityManagerFactory 空
【发布时间】:2019-02-20 22:03:19
【问题描述】:

我正在尝试使用 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);
 }
}

谁能帮我解决这个问题?任何帮助都会受到高度评价。谢谢!

【问题讨论】:

  • 您能否添加您收到的错误消息
  • Spring Boot 2.x 正在使用 Hibernate 5.2+ 。其中包含SessionFactory 扩展EntityManagerFactory 的更改。由于此更改,此代码现在使 Spring Boot 不再配置 EntityManagerFactory(因为 SessionFactory 是其中之一)。你必须考虑你真的需要SessionFactory吗?通常,在 JPA 的当前状态下,您并不真正需要它。如果您需要Session,请使用EntityManager 来`解开会话。如果你真的需要降级到低于 5.2 的 Hibernate 版本。
  • 您可以从 EntityManager 获取 EntityManagerFactory,然后执行您的 getSessionFactory。

标签: hibernate spring-boot jpa entitymanager sessionfactory


【解决方案1】:

正如@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);
    }
}

希望对你有用。

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 2019-03-05
    • 2018-04-02
    • 2019-07-16
    • 2017-10-23
    • 2018-01-03
    • 2018-08-03
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多