Mybatis事务管理

一、Mybatis事务

1、事务管理方式

Mybatis中的事务管理方式有两种:

1、JDBC的事务管理机制,即使用JDBC事务管理机制进行事务管理

2、MANAGED的事务管理机制,Mybatis没有实现对事务的管理,而是通过容器来实现对事务的管理

其中,Mybatis提供了事务的接口:Transaction,其代码如下:

public interface Transaction {
   

  /**
   * Retrieve inner database connection
   * @return DataBase connection
   * @throws SQLException
   */
  //获得数据库连接
  Connection getConnection() throws SQLException;

  /**
   * Commit inner database connection.
   * @throws SQLException
   */
  //提交
  void commit() throws SQLException;

  /**
   * Rollback inner database connection.
   * @throws SQLException
   */
  //回滚
  void rollback() throws SQLException;

  /**
   * Close inner database connection.
   * @throws SQLException
   */
  //连接关闭
  void close() throws SQLException;

  /**
   * Get transaction timeout if set
   * @throws SQLException
   */
  //获取事务timeout
  Integer getTimeout() throws SQLException;
  
}

Transaction有两个实现类:JdbcTransaction和ManagedTransaction,分别对应两种事务管理方式。

JdbcTransaction的代码如下:

public class JdbcTransaction implements Transaction {
   

  private static final Log log = LogFactory.getLog(JdbcTransaction.class);

  //数据连接
  protected Connection connection;
  //数据源
  protected DataSource dataSource;
  //事务等级
  protected TransactionIsolationLevel level;
  //事务提交
  protected boolean autoCommmit;

  public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
   
    dataSource = ds;
    level = desiredLevel;
    autoCommmit = desiredAutoCommit;
  }

  public JdbcTransaction(Connection connection) {
   
    this.connection = connection;
  }

  @Override
  public Connection getConnection() throws SQLException {
   
    if (connection == null) {
   
      openConnection();
    }
    return connection;
  }

  @Override
  public void commit() throws SQLException {
   
    if (connection != null && !connection.getAutoCommit()) {
   
      if (log.isDebugEnabled()) {
   
        log.debug("Committing JDBC Connection [" + connection + "]");
      }
      connection.commit();
    }
  }

  @Override
  public void rollback() throws SQLException {
   
    if (connection != null && !connection.getAutoCommit()) {
   
      if (log.isDebugEnabled()) {
   
        log.debug("Rolling back JDBC Connection [" + connection 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值