Spring with Hibernate JPA - EntityManager 关闭异常 [英] Spring with Hibernate JPA - EntityManager is closed exception

查看:70
本文介绍了Spring with Hibernate JPA - EntityManager 关闭异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我需要访问数据库时,我都使用 EntityManagerFactory(injected) 来创建 entityManager.我有以下代码抛出,

I am using EntityManagerFactory(injected) to create entityManager each time I need to access the db. I have the following code which throws,

org.springframework.dao.InvalidDataAccessApiUsageException:EntityManager 已关闭

entityManager = entityManagerFactory.createEntityManager();

List<Object> list = entityManager.createQuery("FROM Class").getResultList();

entityManager.close();

return list.toArray(new Object[list.size()]);

我正在创建一个 EntityManager,查询数据库以获得一些结果,关闭 EntityManager 并将结果返回给想要这些结果的人.我想我可以弄清楚出了什么问题.getResultList() 返回被管理的对象.因此,在关闭导致错误的 EntityManager 后尝试访问它们(好吧,我认为......).我在关闭它之前尝试了 entityManager.clear() .我得到了同样的错误.我试过分离列表中的每个对象 (entityManager.detach(obj)),然后再关闭它.尽管如此,我还是遇到了同样的错误.我尝试在方法上使用 @Transactional(readOnly=true) 进行注释.没用.

I am creating an EntityManager, querying db for some results, closing EntityManager and returning result to someone who wants those results. I think I can figure out what's wrong. The getResultList() returning objects which are managed. So, trying to access them after closing the EntityManager causing the error(Well, I think...). I tried entityManager.clear() before closing it. I got the same error. I tried detaching each object from the list(entityManager.detach(obj)), before closing it. Still, I got the same error. I tried annotating with @Transactional(readOnly=true) on the method. No use.

我不会修改对象.我只需要它们显示在 UI 上.你能给我一个解决方案吗?我正在使用 Spring Boot + Hibernate JPA + AngularJS + Postgresql.

I am not going to modify the objects. I just need them to display on the UI. Can you give me a solution for that? I am using Spring boot + hibernate JPA + AngularJS + Postgresql.

(PS:我不能让entityManager保持打开状态.保持打开状态,出现连接限制超出错误.这也不是最好的方法)

(PS: I can't left the entityManager open. Left it open, I got connection limit exceeded error. It is not a best way either)

推荐答案

为什么不注入实体管理器而不是工厂?通过这种方式,您可以将创建和处理委托给框架,同时还可以消除连接限制错误(因为框架会为您处理所有这些).

Why don't you inject the entity manager instead of the factory? This way you can delegate creation and disposal to the framework, gettind also rid of the connection limit error (since the framework will handle all of that for you).

你应该可以这样注入:

@PersistenceContext
private EntityManager em;

然后你就可以使用它了.

Then you can just use it.

这篇关于Spring with Hibernate JPA - EntityManager 关闭异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆