简体   繁体   中英

How to use managed Hibernate sessions with a web application

I'm trying to get my head around how Hibernate session management works. I'm trying to define a simple session-per-request model in a web application, but it just doesn't seem to be working. So far I have this:

@WebListener
public class HibernateDataAccess implements ServletRequestListener
{
    Configuration configuration;
    SessionFactory sessionFactory;

    public HibernateDataAccess ()
    {
        configuration = new Configuration ().configure ();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder ().applySettings (
            configuration.getProperties ()).build ();
        sessionFactory = configuration.buildSessionFactory (serviceRegistry);
    }

    public List<Customer> getAllCustomers () throws SQLException
    {
        Session session = sessionFactory.getCurrentSession ();
        return (List<Customer>) session.createQuery ("select c from Customer c").list ();
    }

    @Override
    public void requestDestroyed (ServletRequestEvent arg0)
    {
        ManagedSessionContext.unbind (sessionFactory).close ();
    }

    @Override
    public void requestInitialized (ServletRequestEvent arg0)
    {
        System.out.println ("requestInitialized called!");
        Session session = sessionFactory.openSession ();
        ManagedSessionContext.bind (session);
        session.beginTransaction ();
    }

}

My problem is that despite the fact that I get the message "requestInitialized called!" on my server's console output, I get the following exception when I try to call getAllCustomers from within a servlet request (inside a doGet() method):

org.hibernate.HibernateException: No session currently bound to execution context
at org.hibernate.context.internal.ManagedSessionContext.currentSession(ManagedSessionContext.java:75)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1013)
at net.meridiandigital.binco.web.HibernateDataAccess.getAllCustomers(HibernateDataAccess.java:38)
at net.meridiandigital.binco.web.CustomerServlet.doGetList(CustomerServlet.java:80)

What am I doing wrong?

您是否已将hibernate.current_session_context_class配置参数设置为Hibernate.Context.ICurrentSessionContext实现?

The problem was quite obvious -- the instance of HibernateDataAccess I was using wasn't the same on the server was calling the listener methods on, so the session factory that was having the current session registered was a different one to the one my code was trying to use. The solutions was to separate the two concerns: have an entirely separate @WebListener class that called to my singleton HibernateDataAccess to start and close sessions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM