m0_57895351
2022-03-29 16:47
采纳率: 33.3%
浏览 80
已结题

springboot + hibernate5 出现EntityManagerFactory is closed 报错 第一次访问正常 第二次访问报错

问题遇到的现象和发生背景

springboot + hibernate5 出现EntityManagerFactory is closed 报错 第一次访问正常 第二次访问报错

问题相关代码,请勿粘贴截图
 controller层
  @Autowired
    HibernateDao hibernateDao;

    @RequestMapping("/test")
    public ProjectInfoEntity test(){
        ProjectInfoEntity projectInfoEntity = hibernateDao.get(ProjectInfoEntity.class, "3");
        return projectInfoEntity;
    }

dao层

   private SessionFactory sessionFactory;

    public <T> T get(Class<T> aclass, Serializable id){
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        T t = session.get(aclass, id);

        transaction.commit();
        session.close();
        sessionFactory.close();
        return t;
    }
运行结果及报错内容
Caused by: java.lang.IllegalStateException: EntityManagerFactory is closed
    at org.hibernate.internal.SessionFactoryImpl.validateNotClosed(SessionFactoryImpl.java:498) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.hibernate.internal.SessionFactoryImpl.buildEntityManager(SessionFactoryImpl.java:573) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.hibernate.internal.SessionFactoryImpl.createEntityManager(SessionFactoryImpl.java:569) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.hibernate.internal.SessionFactoryImpl.createEntityManager(SessionFactoryImpl.java:155) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.springframework.orm.jpa.EntityManagerFactoryAccessor.createEntityManager(EntityManagerFactoryAccessor.java:154) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor.preHandle(OpenEntityManagerInViewInterceptor.java:87) ~[spring-orm-4.3.18.RELEASE.jar:4.3.18.RELEASE]
    at org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter.preHandle(WebRequestHandlerInterceptorAdapter.java:57) ~[spring-webmvc-5.3.17.jar:5.3.17]
    at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:148) ~[spring-webmvc-5.3.17.jar:5.3.17]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1062) ~[spring-webmvc-5.3.17.jar:5.3.17]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.17.jar:5.3.17]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.17.jar:5.3.17]
    ... 36 common frames omitted

我的解答思路和尝试过的方法
我想要达到的结果

1条回答 默认 最新

相关推荐 更多相似问题