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 is closed
entityManager = entityManagerFactory.createEntityManager();
List<Object> list = entityManager.createQuery("FROM Class").getResultList();
entityManager.close();
return list.toArray(new Object[list.size()]);
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.
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: I can't left the entityManager open. Left it open, I got connection limit exceeded error. It is not a best way either)