我正试图了解Hibernate会话管理的工作原理。我正在尝试在Web应用程序中定义一个简单的每个请求会话模型,但它似乎没有起作用。到目前为止,我有这个:
@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 ();
}
}
我的问题是,尽管我收到消息“requestInitialized called!”在我的服务器控制台输出上,当我尝试从servlet请求中调用getAllCustomers
时(在doGet()
方法内),我收到以下异常:
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)
我做错了什么?
答案 0 :(得分:0)
您是否已将hibernate.current_session_context_class配置参数设置为Hibernate.Context.ICurrentSessionContext实现?
答案 1 :(得分:0)
问题非常明显 - 我在服务器上使用的HibernateDataAccess实例在调用侦听器方法时是不一样的,因此当前会话注册的会话工厂与一个会话工厂不同我的代码试图使用。解决方案是将两个问题分开:有一个完全独立的@WebListener
类,它调用我的单身HibernateDataAccess
来启动和关闭会话。