org.apache.ibatis.executor.Executor Java Examples

The following examples show how to use org.apache.ibatis.executor.Executor. 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: ExecutorUtil.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
/**
 * 分页查询
 *
 * @param dialect
 * @param executor
 * @param ms
 * @param parameter
 * @param rowBounds
 * @param resultHandler
 * @param boundSql
 * @param cacheKey
 * @param <E>
 * @return
 * @throws SQLException
 */
public static  <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter,
                             RowBounds rowBounds, ResultHandler resultHandler,
                             BoundSql boundSql, CacheKey cacheKey) throws SQLException {
    //判断是否需要进行分页查询
    if (dialect.beforePage(ms, parameter, rowBounds)) {
        //生成分页的缓存 key
        CacheKey pageKey = cacheKey;
        //处理参数对象
        parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
        //调用方言获取分页 sql
        String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
        BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);

        Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
        //设置动态参数
        for (String key : additionalParameters.keySet()) {
            pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
        }
        //执行分页查询
        return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
    } else {
        //不执行分页的情况下,也不执行内存分页
        return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
    }
}
 
Example #2
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 #3
Source File: RoutingStatementHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    //根据语句类型,委派到不同的语句处理器(STATEMENT|PREPARED|CALLABLE)
    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }
 
Example #4
Source File: BaseStatementHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
  this.configuration = mappedStatement.getConfiguration();
  this.executor = executor;
  this.mappedStatement = mappedStatement;
  this.rowBounds = rowBounds;

  this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  this.objectFactory = configuration.getObjectFactory();

  if (boundSql == null) { // issue #435, get the key before calculating the statement
    generateKeys(parameterObject);
    boundSql = mappedStatement.getBoundSql(parameterObject);
  }

  this.boundSql = boundSql;

  //生成parameterHandler
  this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
  //生成resultSetHandler
  this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
}
 
Example #5
Source File: RoutingStatementHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    //根据语句类型,委派到不同的语句处理器(STATEMENT|PREPARED|CALLABLE)
    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }
 
Example #6
Source File: BaseStatementHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
  this.configuration = mappedStatement.getConfiguration();
  this.executor = executor;
  this.mappedStatement = mappedStatement;
  this.rowBounds = rowBounds;

  this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  this.objectFactory = configuration.getObjectFactory();

  if (boundSql == null) { // issue #435, get the key before calculating the statement
    generateKeys(parameterObject);
    boundSql = mappedStatement.getBoundSql(parameterObject);
  }

  this.boundSql = boundSql;

  //生成parameterHandler
  this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
  //生成resultSetHandler
  this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
}
 
Example #7
Source File: SundialInterceptor.java    From Milkomeda with MIT License 6 votes vote down vote up
private void updateSql(String sql, Invocation invocation, MappedStatement ms, Object[] args, BoundSql boundSql) {
    BoundSql boundSqlNew = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    MappedStatement mappedStatement = copyFrom(ms, new BoundSqlSqlSource(boundSqlNew));
    // 替换映射的语句
    args[0] = mappedStatement;

    // 针对查询方式的参数替换
    if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
        Executor executor = (Executor) invocation.getTarget();
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        // 6个参数时(因为分页插件的原因导致问题,需要修改对应的类型值)
        if (args.length == 6) {
            args[4] = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            args[5] = boundSqlNew;
        }
    }
}
 
Example #8
Source File: PaginationHandler.java    From azeroth with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private Long executeQueryCount(Executor executor, MappedStatement countMs, Object parameter,
                               BoundSql boundSql, RowBounds rowBounds,
                               ResultHandler resultHandler) throws IllegalAccessException,
        SQLException {
    CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT,
            boundSql);

    String orignSql = boundSql.getSql().replaceAll(";$", "");
    // count sql
    String countSql = PageSqlUtils.getCountSql(orignSql);

    BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql,
            boundSql.getParameterMappings(), parameter);
    // 执行 count 查询
    Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT,
            resultHandler, countKey, countBoundSql);
    Long count = (Long) ((List) countResultList).get(0);
    return count;
}
 
Example #9
Source File: PaginationHandler.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private List executeQuery(Executor executor, MappedStatement ms,
           Object parameter, BoundSql boundSql,
		RowBounds rowBounds, ResultHandler resultHandler,PageParams pageParams) throws IllegalAccessException, SQLException {
	CacheKey countKey = executor.createCacheKey(ms, parameter, RowBounds.DEFAULT, boundSql);
	
	String orignSql = StringUtils.replace(boundSql.getSql(), ";$", StringUtils.EMPTY);
	
	String pageSql = PageSqlUtils.getLimitSQL(dbType,orignSql,pageParams);
	
	BoundSql countBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(),
			parameter);
	
	List<?> resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, countKey,
			countBoundSql);
	return resultList;
}
 
Example #10
Source File: PaginationHandler.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
	private Long executeQueryCount(Executor executor, MappedStatement countMs,
            Object parameter, BoundSql boundSql,
			RowBounds rowBounds, ResultHandler resultHandler) throws IllegalAccessException, SQLException {
		CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
		
		String orignSql = StringUtils.replace(boundSql.getSql(), ";$", StringUtils.EMPTY);
		// count sql
		String countSql = PageSqlUtils.getCountSql(orignSql);
		
		BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(),
				parameter);
//		for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
//			String propertyName = parameterMapping.getProperty();
//			if(boundSql.hasAdditionalParameter(propertyName)){
//				countBoundSql.setAdditionalParameter(propertyName, boundSql.getAdditionalParameter(propertyName));
//			}
//		}
		// 执行 count 查询
		Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey,
				countBoundSql);
		Long count = (Long) ((List) countResultList).get(0);
		return count;
	}
 
Example #11
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 #12
Source File: ExecutorUtil.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
/**
 * 执行自动生成的 count 查询
 *
 * @param dialect
 * @param executor
 * @param countMs
 * @param parameter
 * @param boundSql
 * @param rowBounds
 * @param resultHandler
 * @return
 * @throws SQLException
 */
public static Long executeAutoCount(Dialect dialect, Executor executor, MappedStatement countMs,
                                    Object parameter, BoundSql boundSql,
                                    RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
    //创建 count 查询的缓存 key
    CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
    //调用方言获取 count sql
    String countSql = dialect.getCountSql(countMs, boundSql, parameter, rowBounds, countKey);
    //countKey.update(countSql);
    BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter);
    //当使用动态 SQL 时,可能会产生临时的参数,这些参数需要手动设置到新的 BoundSql 中
    for (String key : additionalParameters.keySet()) {
        countBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
    }
    //执行 count 查询
    Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
    Long count = (Long) ((List) countResultList).get(0);
    return count;
}
 
Example #13
Source File: ResultLoader.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public ResultLoader(Configuration config, Executor executor, MappedStatement mappedStatement, Object parameterObject, Class<?> targetType, CacheKey cacheKey, BoundSql boundSql) {
  this.configuration = config;
  this.executor = executor;
  this.mappedStatement = mappedStatement;
  this.parameterObject = parameterObject;
  this.targetType = targetType;
  this.objectFactory = configuration.getObjectFactory();
  this.cacheKey = cacheKey;
  this.boundSql = boundSql;
  this.resultExtractor = new ResultExtractor(configuration, objectFactory);
  this.creatorThreadId = Thread.currentThread().getId();
}
 
Example #14
Source File: DefaultSqlSession.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  try {
    //根据statement id找到对应的MappedStatement
    MappedStatement ms = configuration.getMappedStatement(statement);
    //转而用执行器来查询结果,注意这里传入的ResultHandler是null
    return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}
 
Example #15
Source File: DataSessionRuleTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object intercept(final Invocation invocation) throws Throwable {
  if (failNextCommit) {
    // close connection without telling MyBatis - proceeding commit will then fail
    ((Executor) invocation.getTarget()).getTransaction().getConnection().close();
    failNextCommit = false;
  }
  return invocation.proceed();
}
 
Example #16
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public DefaultResultSetHandler(Executor executor, MappedStatement mappedStatement, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSql boundSql,
    RowBounds rowBounds) {
  this.executor = executor;
  this.configuration = mappedStatement.getConfiguration();
  this.mappedStatement = mappedStatement;
  this.rowBounds = rowBounds;
  this.parameterHandler = parameterHandler;
  this.boundSql = boundSql;
  this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  this.objectFactory = configuration.getObjectFactory();
  this.resultHandler = resultHandler;
}
 
Example #17
Source File: ResultLoader.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private <E> List<E> selectList() throws SQLException {
  Executor localExecutor = executor;
  //如果executor已经被关闭了,则创建一个新的
  if (Thread.currentThread().getId() != this.creatorThreadId || localExecutor.isClosed()) {
    localExecutor = newExecutor();
  }
  try {
    //又调回Executor.query去了,比较巧妙
    return localExecutor.<E> query(mappedStatement, parameterObject, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER, cacheKey, boundSql);
  } finally {
    if (localExecutor != executor) {
      localExecutor.close(false);
    }
  }
}
 
Example #18
Source File: EasyMybatisPaginationPlugin.java    From EasyEE with MIT License 5 votes vote down vote up
public Object plugin(Object target) {
	if (target instanceof StatementHandler) {
		return Plugin.wrap(target, this);
	} else if (target instanceof Executor) {
		return Plugin.wrap(target, this);
	} else {
		return target;
	}
}
 
Example #19
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 #20
Source File: DynamicDataSourcePlugin.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(final Object target) {
    if (target instanceof Executor) {
        return Plugin.wrap(target, this);
    }
    return target;
}
 
Example #21
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
	if (target instanceof Executor) {
		return Plugin.wrap(target, this);
	}
	return target;
}
 
Example #22
Source File: DefaultSqlSession.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  try {
    //根据statement id找到对应的MappedStatement
    MappedStatement ms = configuration.getMappedStatement(statement);
    //转而用执行器来查询结果,注意这里传入的ResultHandler是null
    return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}
 
Example #23
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public DefaultResultSetHandler(Executor executor, MappedStatement mappedStatement, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSql boundSql,
    RowBounds rowBounds) {
  this.executor = executor;
  this.configuration = mappedStatement.getConfiguration();
  this.mappedStatement = mappedStatement;
  this.rowBounds = rowBounds;
  this.parameterHandler = parameterHandler;
  this.boundSql = boundSql;
  this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  this.objectFactory = configuration.getObjectFactory();
  this.resultHandler = resultHandler;
}
 
Example #24
Source File: BatchInterceptor.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
  if (target instanceof Executor) {
    return Plugin.wrap(target, this);
  } else {
    return target;
  }
}
 
Example #25
Source File: EntityInterceptor.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object plugin(final Object delegate) {
  if (delegate instanceof Executor) {
    return new EntityExecutor((Executor) delegate, frozenMarker);
  }
  return delegate;
}
 
Example #26
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 #27
Source File: PageInterceptor.java    From genericdao with Artistic License 2.0 5 votes vote down vote up
/**
 * 只拦截Executor
 *
 * @param target
 * @return
 */
public Object plugin(Object target) {
    if (target instanceof Executor) {
        return Plugin.wrap(target, this);
    } else {
        return target;
    }
}
 
Example #28
Source File: AuditingInterceptor.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
	if (target instanceof Executor) {
		return Plugin.wrap(target, this);
	}
	return target;
}
 
Example #29
Source File: PageInterceptor.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
	if (target instanceof Executor) {
		return Plugin.wrap(target, this);
	} else {
		return target;
	}
}
 
Example #30
Source File: JeesuiteMybatisInterceptor.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public Object plugin(Object target) {
	if (target instanceof Executor) {
           return Plugin.wrap(target, this);
       } else {
           return target;
       }


}