【问题标题】:how to use session.commit in a filter with hibernate?如何在休眠过滤器中使用 session.commit?
【发布时间】:2011-10-15 17:32:55
【问题描述】:

我正在使用 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 。

【问题讨论】:

    标签: java hibernate jsp servlets servlet-filters


    【解决方案1】:

    我相信destroy() 只会在容器关闭时被调用。如果你想这样做,那么你可能需要将commit() 放在doFilter() 的末尾

    【讨论】:

    • 绝对正确。正常模式是在调用chain.doFilter 之后在doFilter 中调用commit()。这种模式相当普遍,例如 struts2-hibernate 模块就是以这种方式工作的(除了使用 struts 拦截器而不是过滤器)。
    猜你喜欢
    • 2017-06-08
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多