org.apache.ibatis.transaction.Transaction Java Examples

The following examples show how to use org.apache.ibatis.transaction.Transaction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SQLHelp.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * 查询总纪录数
 *
 * @param mappedStatement mapped
 * @param parameterObject 参数
 * @param boundSql        boundSql
 * @param dialect         database dialect
 * @return 总记录数
 * @throws java.sql.SQLException sql查询错误
 */
public static int getCount(
                           final MappedStatement mappedStatement, final Transaction transaction, final Object parameterObject,
                           final BoundSql boundSql, Dialect dialect) throws SQLException {
    final String count_sql = dialect.getCountSQL();
    logger.debug("Total count SQL [{}] ", count_sql);
    logger.debug("Total count Parameters: {} ", parameterObject);

    Connection connection = transaction.getConnection();
    PreparedStatement countStmt = connection.prepareStatement(count_sql);
    DefaultParameterHandler handler = new DefaultParameterHandler(mappedStatement,parameterObject,boundSql);
    handler.setParameters(countStmt);

    ResultSet rs = countStmt.executeQuery();
    int count = 0;
    if (rs.next()) {
        count = rs.getInt(1);
    }
    logger.debug("Total count: {}", count);
    return count;

}
 
Example #2
Source File: DynamicSqlSessionFactory.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("all")
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
        final Environment environment = getConfiguration().getEnvironment();
        final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
        DataSource ds = DataSourceHolder.currentDataSource().getNative();
        if (ds == null) {
            ds = environment.getDataSource();
        }
        tx = transactionFactory.newTransaction(ds, level, autoCommit);
        final Executor executor = getConfiguration().newExecutor(tx, execType);
        return new DefaultSqlSession(getConfiguration(), executor, autoCommit);
    } catch (Exception e) {
        closeTransaction(tx); // may have fetched a connection so lets call close()
        throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
        ErrorContext.instance().reset();
    }
}
 
Example #3
Source File: DefaultSqlSessionFactory.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  Transaction tx = null;
  try {
    final Environment environment = configuration.getEnvironment();
    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    //通过事务工厂来产生一个事务
    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    //生成一个执行器(事务包含在执行器里)
    final Executor executor = configuration.newExecutor(tx, execType);
    //然后产生一个DefaultSqlSession
    return new DefaultSqlSession(configuration, executor, autoCommit);
  } catch (Exception e) {
    //如果打开事务出错,则关闭它
    closeTransaction(tx); // may have fetched a connection so lets call close()
    throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
  } finally {
    //最后清空错误上下文
    ErrorContext.instance().reset();
  }
}
 
Example #4
Source File: DefaultSqlSessionFactory.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  Transaction tx = null;
  try {
    final Environment environment = configuration.getEnvironment();
    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    //通过事务工厂来产生一个事务
    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    //生成一个执行器(事务包含在执行器里)
    final Executor executor = configuration.newExecutor(tx, execType);
    //然后产生一个DefaultSqlSession
    return new DefaultSqlSession(configuration, executor, autoCommit);
  } catch (Exception e) {
    //如果打开事务出错,则关闭它
    closeTransaction(tx); // may have fetched a connection so lets call close()
    throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
  } finally {
    //最后清空错误上下文
    ErrorContext.instance().reset();
  }
}
 
Example #5
Source File: DefaultSqlSessionFactory.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void closeTransaction(Transaction tx) {
  if (tx != null) {
    try {
      tx.close();
    } catch (SQLException ignore) {
      // Intentionally ignore. Prefer previous error.
    }
  }
}
 
Example #6
Source File: BaseExecutor.java    From mybatis with Apache License 2.0 5 votes vote down vote up
protected BaseExecutor(Configuration configuration, Transaction transaction) {
  this.transaction = transaction;
  this.deferredLoads = new ConcurrentLinkedQueue<DeferredLoad>();
  this.localCache = new PerpetualCache("LocalCache");
  this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
  this.closed = false;
  this.configuration = configuration;
  this.wrapper = this;
}
 
Example #7
Source File: BaseExecutor.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public Transaction getTransaction() {
  if (closed) {
    throw new ExecutorException("Executor was closed.");
  }
  return transaction;
}
 
Example #8
Source File: ResultLoader.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private Executor newExecutor() {
  final Environment environment = configuration.getEnvironment();
  if (environment == null) {
    throw new ExecutorException("ResultLoader could not load lazily.  Environment was not configured.");
  }
  final DataSource ds = environment.getDataSource();
  if (ds == null) {
    throw new ExecutorException("ResultLoader could not load lazily.  DataSource was not configured.");
  }
  final TransactionFactory transactionFactory = environment.getTransactionFactory();
  final Transaction tx = transactionFactory.newTransaction(ds, null, false);
  //如果executor已经被关闭了,则创建一个新的SimpleExecutor
  return configuration.newExecutor(tx, ExecutorType.SIMPLE);
}
 
Example #9
Source File: ManagedTransactionFactoryTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEnsureThatCallsToManagedTransactionAPIDoNotForwardToManagedConnections() throws Exception {
  TransactionFactory tf = new ManagedTransactionFactory();
  tf.setProperties(new Properties());
  Transaction tx = tf.newTransaction(conn);
  assertEquals(conn, tx.getConnection());
  tx.commit();
  tx.rollback();
  tx.close();
  verify(conn).close();
}
 
Example #10
Source File: ResultLoader.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private Executor newExecutor() {
  final Environment environment = configuration.getEnvironment();
  if (environment == null) {
    throw new ExecutorException("ResultLoader could not load lazily.  Environment was not configured.");
  }
  final DataSource ds = environment.getDataSource();
  if (ds == null) {
    throw new ExecutorException("ResultLoader could not load lazily.  DataSource was not configured.");
  }
  final TransactionFactory transactionFactory = environment.getTransactionFactory();
  final Transaction tx = transactionFactory.newTransaction(ds, null, false);
  //如果executor已经被关闭了,则创建一个新的SimpleExecutor
  return configuration.newExecutor(tx, ExecutorType.SIMPLE);
}
 
Example #11
Source File: BaseExecutor.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public Transaction getTransaction() {
  if (closed) {
    throw new ExecutorException("Executor was closed.");
  }
  return transaction;
}
 
Example #12
Source File: BaseExecutor.java    From mybaties with Apache License 2.0 5 votes vote down vote up
protected BaseExecutor(Configuration configuration, Transaction transaction) {
  this.transaction = transaction;
  this.deferredLoads = new ConcurrentLinkedQueue<DeferredLoad>();
  this.localCache = new PerpetualCache("LocalCache");
  this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
  this.closed = false;
  this.configuration = configuration;
  this.wrapper = this;
}
 
Example #13
Source File: DefaultSqlSessionFactory.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void closeTransaction(Transaction tx) {
  if (tx != null) {
    try {
      tx.close();
    } catch (SQLException ignore) {
      // Intentionally ignore. Prefer previous error.
    }
  }
}
 
Example #14
Source File: ManagedTransactionFactoryTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEnsureThatCallsToManagedTransactionAPIDoNotForwardToManagedConnectionsAndDoesNotCloseConnection() throws Exception {
  TransactionFactory tf = new ManagedTransactionFactory();
  Properties props = new Properties();
  props.setProperty("closeConnection", "false");
  tf.setProperties(props);
  Transaction tx = tf.newTransaction(conn);
  assertEquals(conn, tx.getConnection());
  tx.commit();
  tx.rollback();
  tx.close();
  verifyNoMoreInteractions(conn);
}
 
Example #15
Source File: ManagedTransactionFactory.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
  // Silently ignores autocommit and isolation level, as managed transactions are entirely
  // controlled by an external manager.  It's silently ignored so that
  // code remains portable between managed and unmanaged configurations.
  return new ManagedTransaction(ds, level, closeConnection);
}
 
Example #16
Source File: ManagedTransactionFactoryTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEnsureThatCallsToManagedTransactionAPIDoNotForwardToManagedConnections() throws Exception {
  TransactionFactory tf = new ManagedTransactionFactory();
  tf.setProperties(new Properties());
  Transaction tx = tf.newTransaction(conn);
  assertEquals(conn, tx.getConnection());
  tx.commit();
  tx.rollback();
  tx.close();
  verify(conn).close();
}
 
Example #17
Source File: ManagedTransactionFactoryTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEnsureThatCallsToManagedTransactionAPIDoNotForwardToManagedConnectionsAndDoesNotCloseConnection() throws Exception {
  TransactionFactory tf = new ManagedTransactionFactory();
  Properties props = new Properties();
  props.setProperty("closeConnection", "false");
  tf.setProperties(props);
  Transaction tx = tf.newTransaction(conn);
  assertEquals(conn, tx.getConnection());
  tx.commit();
  tx.rollback();
  tx.close();
  verifyNoMoreInteractions(conn);
}
 
Example #18
Source File: MybatisUtils.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getDatabaseId(@Nullable SqlRequestContextHolder sqlRequestContextHolder,
                                   @Nullable SQLStatementInstrumentor instrumentor,
                                   @NonNull final MappedStatement ms, Executor executor) {
    String databaseId = null;
    if (sqlRequestContextHolder != null) {
        SqlRequestContext sqlRequestContext = sqlRequestContextHolder.get();
        if (sqlRequestContext != null) {
            SqlRequest request = sqlRequestContext.getRequest();
            if (request != null) {
                databaseId = request.getDialect();
            }
        }
    }

    if (Emptys.isEmpty(databaseId)) {
        databaseId = ms.getDatabaseId();
    }

    if (Emptys.isEmpty(databaseId) && instrumentor != null && instrumentor.getConfig() != null) {
        databaseId = instrumentor.getConfig().getDialect();
    }

    if (Emptys.isEmpty(databaseId)) {
        return ms.getConfiguration().getDatabaseId();
    }
    if (Emptys.isEmpty(databaseId) && executor != null) {
        Transaction tx = executor.getTransaction();
        try {
            Connection connection = tx.getConnection();
            Dialect dialect = instrumentor.getDialect(connection.getMetaData());
            return dialect.getDatabaseId();
        } catch (Throwable ex) {
        }
    }
    return databaseId;
}
 
Example #19
Source File: ManagedTransactionFactory.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
  // Silently ignores autocommit and isolation level, as managed transactions are entirely
  // controlled by an external manager.  It's silently ignored so that
  // code remains portable between managed and unmanaged configurations.
  return new ManagedTransaction(ds, level, closeConnection);
}
 
Example #20
Source File: DynamicSqlSessionFactory.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
private void closeTransaction(Transaction tx) {
    if (tx != null) {
        try {
            tx.close();
        } catch (SQLException ignore) {
            // Intentionally ignore. Prefer previous error.
        }
    }
}
 
Example #21
Source File: Configuration.java    From mybatis with Apache License 2.0 4 votes vote down vote up
public Executor newExecutor(Transaction transaction) {
  return newExecutor(transaction, defaultExecutorType);
}
 
Example #22
Source File: ManagedTransactionFactory.java    From mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public Transaction newTransaction(Connection conn) {
  return new ManagedTransaction(conn, closeConnection);
}
 
Example #23
Source File: JdbcTransactionFactory.java    From mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
  return new JdbcTransaction(ds, level, autoCommit);
}
 
Example #24
Source File: JdbcTransactionFactory.java    From mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public Transaction newTransaction(Connection conn) {
  return new JdbcTransaction(conn);
}
 
Example #25
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 4 votes vote down vote up
protected Executor createExecutor(Transaction transaction) {
  return new SimpleExecutor(config,transaction);
}
 
Example #26
Source File: RountingManagedTransactionFactory.java    From easyooo-framework with Apache License 2.0 4 votes vote down vote up
@Override
public Transaction newTransaction(DataSource dataSource,
		TransactionIsolationLevel level, boolean autoCommit) {
	return new RoutingSpringManagedTransaction(dataSource);
}
 
Example #27
Source File: ReuseExecutor.java    From mybatis with Apache License 2.0 4 votes vote down vote up
public ReuseExecutor(Configuration configuration, Transaction transaction) {
  super(configuration, transaction);
}
 
Example #28
Source File: BatchExecutor.java    From mybatis with Apache License 2.0 4 votes vote down vote up
public BatchExecutor(Configuration configuration, Transaction transaction) {
  super(configuration, transaction);
}
 
Example #29
Source File: CachingExecutor.java    From mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public Transaction getTransaction() {
  return delegate.getTransaction();
}
 
Example #30
Source File: SimpleExecutor.java    From mybatis with Apache License 2.0 4 votes vote down vote up
public SimpleExecutor(Configuration configuration, Transaction transaction) {
  super(configuration, transaction);
}