Diablo.Wu
Diablo.Wu

Reputation: 1171

create a new hibernate session in multi-thread program

How to create a new hibernate session at a new thread ? The SessionFacatory was managed by Spring.

Upvotes: 2

Views: 1149

Answers (2)

ejaenv
ejaenv

Reputation: 2387

To use multiple sessions and avoid LazyInitiazationException, you can simulate what OpenSessionInViewFilter does (one session per http request):

public class HibernateSessionManager {

    private final SessionFactory sessionFactory;

    public HibernateSessionManager(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void openSession() {
        // Obtain the current Hibernate session factory
        Session session = sessionFactory.openSession();

        // Create a SessionHolder and associate it with the current thread
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
    }

    public Session getCurrentSession() {
        // Retrieve the Hibernate session from the current SessionHolder
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
        if (sessionHolder != null) {
            return sessionHolder.getSession();
        }
        return null;
    }

    public void closeSession() {
        // Unbind the SessionHolder from the current thread and close the session
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
        if (sessionHolder != null) {
            Session session = sessionHolder.getSession();
            session.close();
        }
    }
}

(code generated with chatgpt)

Upvotes: 0

K Erlandsson
K Erlandsson

Reputation: 13696

SessionFactory.openSession creates a new session if that is all you need to know. If you need anything more, please elaborate.

Upvotes: 3

Related Questions