如何在hibernate过滤器中使用session.commit



我正在使用Hibernate和jsp编写一个博客系统。我想使用过滤器来管理会话和事务。现在我写一个过滤器:

public class SessionFilter implements Filter {
FilterConfig config;
SessionFactory sessionFactory;
Session session;
public void destroy() {
    session.getTransaction().commit();
    this.config=null;
    System.out.println("session Filter is destroyed.");
}
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    sessionFactory = (SessionFactory) config.getServletContext().getAttribute("sessionFactory");
    session = sessionFactory.getCurrentSession();
    session.beginTransaction();

    chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
    this.config=config;
    System.out.println("session Filter is inited.");
}

}

现在的结果是我的表单字段没有保存到mysql。

我相信destroy()只会在容器关闭时被调用。如果你想采用这种方法,那么你可能需要将commit()放在doFilter()

的末尾

最新更新