mybatis事务相关知识点

来源:互联网 发布:淘宝店多少单一颗心 编辑:程序博客网 时间:2024/06/05 16:06

mybatis事务相关知:

事务接口(Transaction)一般包括如下几个方法:创建(getConnection) 提交(commit) 回滚(rollback) 关闭(close)可能还会有getTimeout。
Transaction接口代码片段:
{
  public abstract Connection getConnection()
    throws SQLException;
  
  public abstract void commit()
    throws SQLException;
  
  public abstract void rollback()
    throws SQLException;
  
  public abstract void close()
    throws SQLException;
  
  public abstract Integer getTimeout()
    throws SQLException;
}

mybatis有两种机制来对事务进行管理:

1.使用JdbcTransaction机制。从源码中可以知道,JdbcTransaction是对数据库连接Connection接口的包装,内部事务管理还是调用Connection中的commit、rollback 等方法。如图:
JdbcTransaction implements Transaction

  public Connection getConnection()
    throws SQLException
  {
    if (this.connection == null) {
      openConnection();
    }
    return this.connection;
  }
  
  public void commit()
    throws SQLException
  {
    if ((this.connection != null) && (!this.connection.getAutoCommit()))
    {
      if (log.isDebugEnabled()) {
        log.debug("Committing JDBC Connection [" + this.connection + "]");
      }
      this.connection.commit();
    }
  }
  
  public void rollback()
    throws SQLException
  {
    if ((this.connection != null) && (!this.connection.getAutoCommit()))
    {
      if (log.isDebugEnabled()) {
        log.debug("Rolling back JDBC Connection [" + this.connection + "]");
      }
      this.connection.rollback();
    }
  }
  
  public void close()
    throws SQLException
  {
    if (this.connection != null)
    {
      resetAutoCommit();
      if (log.isDebugEnabled()) {
        log.debug("Closing JDBC Connection [" + this.connection + "]");
      }
      this.connection.close();
    }
  }

2.使用ManagedTransaction机制。从源码中得知,ManagedTransaction什么都不做,而是事务交由外部容器(JBoss、WebLogic)来处理,如图:

  public Connection getConnection()
    throws SQLException
  {
    if (this.connection == null) {
      openConnection();
    }
    return this.connection;
  }
  
  public void commit()
    throws SQLException
  {}
  
  public void rollback()
    throws SQLException
  {}
  
  public void close()
    throws SQLException
  {
    if ((this.closeConnection) && (this.connection != null))
    {
      if (log.isDebugEnabled()) {
        log.debug("Closing JDBC Connection [" + this.connection + "]");
      }
      this.connection.close();
    }
  }


现在的web项目,mybatis的事务一般交由spring事务管理。
以上都是个人理解,若有不妥的地方,可以私信交流。







原创粉丝点击