hibernate.transaction.auto_close_session throws "Session/EntityManager is closed" when set to true

324 Views Asked by At

When we set hibernate.transaction.auto_close_session to true, it is throwing java.lang.IllegalStateException: Session/EntityManager is closed .

We are using hibernate 5.3.18.Final and spring 5.3.28 versions.

When we set hibernate.transaction.auto_close_session to false above error is not seen. However we want that property to be true in our codebase.

Could you please confirm the above error is resolved in which versions of hibernate? or is it safe to ignore the above error?

Thanks in Advance.

1

There are 1 best solutions below

3
Ken Chan On

Set hibernate.transaction.auto_close_session to true means that session will be automatically closed when the transaction completes.

If the session is already closed and then you call EntityManager#close() or Session#close() , it will throw that IllegalStateException. There is no harm and so you could simply try-catch it to make the codes keep running instead of interrupted by it.

But a better idea is to use EntityManager#isOpen() or Session#isOpen() to check if the session is already closed before calling EntityManager#close() or Session#close() .

Something like :

if (entityManager.isOpen()){
  entityManager.close();
}