'Spring with Hibernate JPA - EntityManager is closed exception

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)



Solution 1:[1]

I also faced similar issue but it didn't work by just using @PersistenceContext, we need to set PersistenceContextType also which is by default TRANSACTION, but in this case when multiple threads try to use same singleton instance of EntityManager, we need to set it to EXTENDED like this -

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;

and it worked. I got this issue when i was trying to execute a db query in one of my schedulars.

Reference - https://www.baeldung.com/jpa-hibernate-persistence-context

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1