Skip to content
Advertisement

Cleaning up after changing the isolation level in JPA / EclipsLink EntityManager

I’m performing a transaction in JPA (EclipseLink) using a custom transaction isolation level, which I set on the underlying connection of the JPA EntityManager using this code:

JavaScript

If I try to reset the isolation level to the old value after having committed the transaction, the underlying connection is null (entityManager.unwrap(Connection.class) returns null). I’m worried, if I just don’t reset the isolation level, a connection with a bad isolation level gets leaked back to the pool.

What is the correct way of cleaning up after changing the isolation level? Should I maybe do it before calling commit()?

Advertisement

Answer

The java.sql.Connection gets returned to the pool in the call to entityManager.getTransaction().commit(); So resetting the isolation level afterwards is not possible and prevented by EclipseLink by returning a null connection.

Maintaining a reference to the Connection to circumvent this will likely leak a connection with altered settings, so I cannot accept your answer RomanC

I ended up creating two instances of EntityManagerFactory. One that creates default EntityManagers and one that creates EntityManagers with Connections with my desired transaction level using a SessionCustomizer:

JavaScript

See here Set Isolation level in eclipselink

I then use the EntityManagerFactory that provides whichever connection type I need. Caveat: Transactions cannot span EntityManagers from multiple EntityManagerFactories

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement