blog

mybatisをゼロから手書きする - mybatisのトランザクション管理メカニズムを詳しく見る

このセクションでは、mybatisのトランザクション管理について説明します。 JDBCのトランザクション管理機構を使う:オブジェクトを使って、トランザクションをコミット、ロールバック、クローズします。...

Nov 29, 2020 · 9 min. read
シェア

展望のレビュー

セクション3: ゼロからのmybatisjdbcプールの記述

このセクションでは、mybatisのトランザクション管理について学びます。

mybatis JdbcTransaction.java でのトランザクション管理

mybatisトランザクションを使用するには2つの方法があります:

  1. JDBCトランザクション管理機構を使用:つまり、java.Sql.Connectionオブジェクトを使用して、コミット、ロールバック、クローズ操作のトランザクションを完了します。

  2. MANAGEDトランザクション管理機構の使用:mybatis自体は、トランザクション管理の関連する操作の実装に行くことはありませんが、トランザクションを管理するために外部コンテナを引き渡すこと。springインテグレーションと併用する場合は、一般にspringでトランザクションを管理します。

TransactionFactory

インタフェース定義

これは以下のインターフェイスを持つトランザクションのファクトリーです:

public interface TransactionFactory {
 /**
 * Sets transaction factory custom properties.
 * @param props
 */
 void setProperties(Properties props);
 /**
 * Creates a {@link Transaction} out of an existing connection.
 * @param conn Existing database connection
 * @return Transaction
 * @since 3.1.0
 */
 Transaction newTransaction(Connection conn);
 
 /**
 * Creates a {@link Transaction} out of a datasource.
 * @param dataSource DataSource to take the connection from
 * @param level Desired isolation level
 * @param autoCommit Desired autocommit
 * @return Transaction
 * @since 3.1.0
 */
 Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit);
}

主な内容は、DataSourceに基づいてTransactionを作成する方法です。

実際、全体的なフィーリングはあまり重要ではありません。

その核心は、トランザクションの実装を見ることが重要です。

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
 */
 Integer getTimeout() throws SQLException;
 
}

ここで本当に中心となるのはcommit()とrollback()だけで、他はすべて無視してかまいません。

mybatis 操作のタイムアウト機構は、 getTimeout() をターゲットにすることで提供できます。

JdbcTransaction

jdbcメカニズムに基づくいくつかの処理。

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 + "]");
 }
 connection.rollback();
 }
 }
 @Override
 public void close() throws SQLException {
 if (connection != null) {
 resetAutoCommit();
 if (log.isDebugEnabled()) {
 log.debug("Closing JDBC Connection [" + connection + "]");
 }
 connection.close();
 }
 }
 protected void setDesiredAutoCommit(boolean desiredAutoCommit) {
 try {
 if (connection.getAutoCommit() != desiredAutoCommit) {
 if (log.isDebugEnabled()) {
 log.debug("Setting autocommit to " + desiredAutoCommit + " on JDBC Connection [" + connection + "]");
 }
 connection.setAutoCommit(desiredAutoCommit);
 }
 } catch (SQLException e) {
 // Only a very poorly implemented driver would fail here,
 // and there's not much we can do about that.
 throw new TransactionException("Error configuring AutoCommit. "
 + "Your driver may not support getAutoCommit() or setAutoCommit(). "
 + "Requested setting: " + desiredAutoCommit + ". Cause: " + e, e);
 }
 }
 protected void resetAutoCommit() {
 try {
 if (!connection.getAutoCommit()) {
 // MyBatis does not call commit/rollback on a connection if just selects were performed.
 // Some databases start transactions with select statements
 // and they mandate a commit/rollback before closing the connection.
 // A workaround is setting the autocommit to true before closing the connection.
 // Sybase throws an exception here.
 if (log.isDebugEnabled()) {
 log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]");
 }
 connection.setAutoCommit(true);
 }
 } catch (SQLException e) {
 if (log.isDebugEnabled()) {
 log.debug("Error resetting autocommit to true "
 + "before closing the connection. Cause: " + e);
 }
 }
 }
 protected void openConnection() throws SQLException {
 if (log.isDebugEnabled()) {
 log.debug("Opening JDBC Connection");
 }
 connection = dataSource.getConnection();
 if (level != null) {
 connection.setTransactionIsolation(level.getLevel());
 }
 setDesiredAutoCommit(autoCommmit);
 }
 @Override
 public Integer getTimeout() throws SQLException {
 return null;
 }
 
}

ここでの全体的な実装は実際には非常にシンプルで、auto-submitプロパティを積極的に設定するだけです。

ManagedDataSource

これは別の実装で、実際にはもっとシンプルです。

commit()とrollback()の実装は両方とも空です。

public class ManagedTransaction implements Transaction {
 private static final Log log = LogFactory.getLog(ManagedTransaction.class);
 private DataSource dataSource;
 private TransactionIsolationLevel level;
 private Connection connection;
 private boolean closeConnection;
 public ManagedTransaction(Connection connection, boolean closeConnection) {
 this.connection = connection;
 this.closeConnection = closeConnection;
 }
 public ManagedTransaction(DataSource ds, TransactionIsolationLevel level, boolean closeConnection) {
 this.dataSource = ds;
 this.level = level;
 this.closeConnection = closeConnection;
 }
 @Override
 public Connection getConnection() throws SQLException {
 if (this.connection == null) {
 openConnection();
 }
 return this.connection;
 }
 @Override
 public void commit() throws SQLException {
 // Does nothing
 }
 @Override
 public void rollback() throws SQLException {
 // Does nothing
 }
 @Override
 public void close() throws SQLException {
 if (this.closeConnection && this.connection != null) {
 if (log.isDebugEnabled()) {
 log.debug("Closing JDBC Connection [" + this.connection + "]");
 }
 this.connection.close();
 }
 }
 protected void openConnection() throws SQLException {
 if (log.isDebugEnabled()) {
 log.debug("Opening JDBC Connection");
 }
 this.connection = this.dataSource.getConnection();
 if (this.level != null) {
 this.connection.setTransactionIsolation(this.level.getLevel());
 }
 }
 @Override
 public Integer getTimeout() throws SQLException {
 return null;
 }
}

は英語の -ity、-ism、-ization に対応します。

ManagedTransactionのトランザクションのコミットやロールバックは、コンテナが管理するように引き渡され、それ自身は処理を行いません。

mybatis 使用方法

Mybatisが単独で動作していて、他のフレームワークが管理していない場合、この時点でmybatisは内部的に以下のコードを実装しています。

con.setAutoCommit(false);
//ここでのコマンドは、この瞬間から現在の Connection チャネルが
//SQLこれらの SQL 文は同じビジネスに属し、同じデータベースに保存する必要がある。
//Transaction .このトランザクションの動作は、現在の Connection によって管理される。.
try{
 //SQLステートメント・コマンドをプッシュする。..;
 con.commit();//トランザクション・コミットの通知.
}catch(SQLException ex){
 con.rollback();//ロールバックのトランザクションへの通知.
}

全体として、これは原始的な書き方であり、コネクションによって処理されるトランザクションを、トランザクション・マネージャーによって処理されるように統一することができます。

spring

もちろんmybatisでは、そのほとんどが1つのステートメントの実行です。

コネクションを使用すると、実際にはmybatisトランザクション・マネージャによってカプセル化されたコネクションを取得します。

実際、春季大会の統合は、もう少し応用が利くでしょう。

個々の実装

mybatis実装の原則を見た後、実装は非常にシンプルになります。

上記の実装のいくつかを簡略化し、コアだけを残すことも可能です。

インタフェース定義

コアの3つのインターフェースのみが保持されます。

/**
 * トランザクション管理
 */
public interface Transaction {
 /**
 * Retrieve inner database connection
 * @return DataBase connection
 */
 Connection getConnection();
 /**
 * Commit inner database connection.
 */
 void commit();
 /**
 * Rollback inner database connection.
 */
 void rollback();
}

ManageTransaction

このコミットとロールバックの実装は何もしません。

/**
 * トランザクション管理
 *
 * @since 0.0.18
 */
public class ManageTransaction implements Transaction {
 /**
 * データ情報
 * @since 0.0.18
 */
 private final DataSource dataSource;
 /**
 * 分離レベル
 * @since 0.0.18
 */
 private final TransactionIsolationLevel isolationLevel;
 /**
 * 接続情報
 * @since 0.0.18
 */
 private Connection connection;
 public ManageTransaction(DataSource dataSource, TransactionIsolationLevel isolationLevel) {
 this.dataSource = dataSource;
 this.isolationLevel = isolationLevel;
 }
 public ManageTransaction(DataSource dataSource) {
 this(dataSource, TransactionIsolationLevel.READ_COMMITTED);
 }
 @Override
 public Connection getConnection() {
 try {
 if(this.connection == null) {
 Connection connection = dataSource.getConnection();
 connection.setTransactionIsolation(isolationLevel.getLevel());
 this.connection = connection;
 }
 return connection;
 } catch (SQLException throwables) {
 throw new MybatisException(throwables);
 }
 }
 @Override
 public void commit() {
 //nothing
 }
 @Override
 public void rollback() {
 //nothing
 }
}

JdbcTransaction.java

上記と比べると、コミットやロールバックのロジックが多くなっています。

package com.github.houbb.mybatis.transaction.impl;
import com.github.houbb.mybatis.constant.enums.TransactionIsolationLevel;
import com.github.houbb.mybatis.exception.MybatisException;
import com.github.houbb.mybatis.transaction.Transaction;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
 * トランザクション管理
 *
 * @since 0.0.18
 */
public class JdbcTransaction implements Transaction {
 /**
 * データ情報
 * @since 0.0.18
 */
 private final DataSource dataSource;
 /**
 * 分離レベル
 * @since 0.0.18
 */
 private final TransactionIsolationLevel isolationLevel;
 /**
 * 自動コミット
 * @since 0.0.18
 */
 private final boolean autoCommit;
 /**
 * 接続情報
 * @since 0.0.18
 */
 private Connection connection;
 public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel isolationLevel, boolean autoCommit) {
 this.dataSource = dataSource;
 this.isolationLevel = isolationLevel;
 this.autoCommit = autoCommit;
 }
 public JdbcTransaction(DataSource dataSource) {
 this(dataSource, TransactionIsolationLevel.READ_COMMITTED, true);
 }
 @Override
 public Connection getConnection(){
 try {
 if(this.connection == null) {
 Connection connection = dataSource.getConnection();
 connection.setTransactionIsolation(isolationLevel.getLevel());
 connection.setAutoCommit(autoCommit);
 this.connection = connection;
 }
 return connection;
 } catch (SQLException throwables) {
 throw new MybatisException(throwables);
 }
 }
 @Override
 public void commit() {
 try {
 //コミット操作は、コミットが自動でない場合にのみ実行される。
 if(connection != null && !this.autoCommit) {
 connection.commit();
 }
 } catch (SQLException throwables) {
 throw new MybatisException(throwables);
 }
 }
 @Override
 public void rollback() {
 try {
 //コミット操作は、コミットが自動でない場合にのみ実行される。
 if(connection != null && !this.autoCommit) {
 connection.rollback();
 }
 } catch (SQLException throwables) {
 throw new MybatisException(throwables);
 }
 }
}
Read next

JavaScriptにおける継承

# 継承 > オブジェクト指向言語の3大機能の1つ、**継承**。 > 継承はJSにおいて非常に重要な概念であり、プログラマのレベルを見る上で最も重要なベンチマークの一つです。

Nov 29, 2020 · 10 min read