【问题标题】:hibernate transaction begin/rollback/commit vs. also session.clear()休眠事务开始/回滚/提交与 session.clear()
【发布时间】:2016-04-04 18:07:13
【问题描述】:

我正在处理一些旧的应用程序代码,并且似乎涉及到几个概念,所以我希望确保我可以将它们改进为一种扎实而严格的实践。

基本上,整个代码都用这样的 HibernateSessionRequestFilter 包装

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        sf.getCurrentSession().beginTransaction();            

        chain.doFilter(request, response);

        sf.getCurrentSession().clear();

    } catch (...) {        
        //...
    } finally {
        sf.getCurrentSession().close();
    }

}

然后,有一个拦截器,做这样的事情

private String loadStaff(...) {
    //...

    try {
        dbSession = //...;
        dbSession.beginTransaction();

        // some logic

        dbSession.getTransaction().rollback();

    } catch (RuntimeException e) {
        //..
    }
    finally {
        if (dbSession != null && dbSession.isOpen()) {
            dbSession.clear();
        }
    }
    }

然后还有更多的业务逻辑代码,包括更多的 begintransactions 和 session clear 等。

所以,问题:

  1. 在同一会话中多次调用 beginTransaction 会发生什么?
  2. 有时,调用“clear()”会引发异常,我认为它发生在调用“rollback()”之后。如何解决?
  3. 一般而言,将 session.clear() 与事务开始/回滚/提交结合起来的最佳建议做法是什么?

谢谢

【问题讨论】:

标签: java sql database hibernate transactions


【解决方案1】:

您的代码应如下所示,这是处理单个 http 请求的事务的方式,

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        // Open the transaction.
        sf.getCurrentSession().beginTransaction();            

        // Handle the request
        chain.doFilter(request, response);

        // Persist the db changes into database.
        sf.getCurrentSession().commit();

    } catch (...) {        
        // Somthing gone wrong while handling the http request so we should remove all the changes and rollback the changes that are done in the current request.
        sf.getCurrentSession().rollback()
    } finally {
        sf.getCurrentSession().close();
    }

}

在您的代码的其他部分不应处理开始事务/关闭/提交事务。它应该只在一个地方处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多