Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.hibernate.jpa.internal;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.internal.SessionImpl;
- import javax.annotation.Nonnull;
- import javax.persistence.EntityManager;
- import javax.persistence.EntityManagerFactory;
- import java.sql.Connection;
- import java.sql.SQLException;
- /**
- * Manipulates Hibernate internals to allow connecting an {@link EntityManager}
- * to a new JDBC connection when the old connection of the EntityManager has died.
- *
- * @see <a href="http://stackoverflow.com/questions/24060782/jpa-2-hibernate-persistence-context-per-conversation-closed-connection">JPA 2 (Hibernate) persistence context per conversation - closed connection</a>
- *
- */
- public class EntityManagerFactoryAdapter {
- private final EntityManagerFactoryImpl entityManagerFactory;
- public EntityManagerFactoryAdapter(EntityManagerFactory entityManagerFactory) {
- this.entityManagerFactory = (EntityManagerFactoryImpl)entityManagerFactory;
- }
- /**
- * Reconnects given {@code entityManager} to the given {@code connection}
- * if the database connection of the EntityManager has been closed.
- * Does nothing if the EntityManager already has an open connection.
- *
- * @param entityManager The EntityManager to reconnect
- * @param connection The connection to connect the EntityManager to
- */
- public void reconnect(@Nonnull EntityManager entityManager, @Nonnull Connection connection) {
- SessionImpl existingSession = entityManager.unwrap(SessionImpl.class);
- try {
- if (existingSession.connection().isClosed()) {
- existingSession.disconnect();
- existingSession.reconnect(connection);
- }
- } catch (SQLException e) {
- throw new RuntimeException("Failed reconnecting EntityManager to given JDBC connection.", e);
- }
- }
- /**
- * Creates a new EntityManager that uses the given JDBC connection
- * for database access.
- *
- * @param connection The JDBC connection to use in the EntityManager
- * @return The created EntityManager
- */
- @Nonnull
- public EntityManager createEntityManager(@Nonnull Connection connection) {
- // Create new EntityManager & close the session attached to it.
- // Otherwise the original session is left open.
- EntityManagerImpl entityManager = (EntityManagerImpl)entityManagerFactory.createEntityManager();
- entityManager.unwrap(Session.class).close();
- // Replace EntityManager session with session created with
- // specified JDBC connection. Necessary to be able to
- // later call .reconnect(connection) on the session.
- SessionFactory sessionFactory = entityManagerFactory.getSessionFactory();
- entityManager.session = sessionFactory.withOptions()
- .connection(connection)
- .openSession();
- entityManager.getTransaction().begin();
- return entityManager;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement