【问题标题】:Spring cannot get a hibernate sessionSpring无法获得休眠会话
【发布时间】:2019-12-02 02:44:12
【问题描述】:

使用 Spring 2.0.5

在dao类中

@Repository
@Transactional
public class IsActiveTestDao {
  private EntityManager em;

 public void populateIsActiveTest(){
    Session session = em.unwrap(Session.class);

当我这样做或任何其他 50 种方式时:

SessionFactory f = em.unwrap(SessionFactory.class);

我也试过

em.getDelegate()

我总是得到空指针异常

我的问题是我可以在 Spring 中使用 @Transactional 注释从 JPA 实体管理器获取休眠会话吗?

【问题讨论】:

    标签: spring hibernate jpa


    【解决方案1】:

    你需要给EntityManager添加一个@Autowired注解

    【讨论】:

      【解决方案2】:

      您可以对EntityManager使用@PersistenceContext注解来指定您要使用的持久化单元。

      【讨论】:

        【解决方案3】:

        您正在创建一个空 EntityManager。所以,你得到一个空指针异常 您需要通过

        从 Application 上下文中获取 EntityManager 对象
         @PersistenceContext
        

         @Autowired 
        

        获取EntityManager的初始化对象。

        这样做对你有用。

        【讨论】:

          猜你喜欢
          • 2015-09-12
          • 2013-12-12
          • 1970-01-01
          • 2011-05-03
          • 2014-07-26
          • 2013-07-26
          • 2021-09-28
          • 2012-06-02
          相关资源
          最近更新 更多