org.apache.ibatis.executor.Executor

Here are the examples of the java api org.apache.ibatis.executor.Executor taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

85 Examples 7

19 Source : SchemaInterceptor.java
with Apache License 2.0
from zuihou

@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
// 统一交给 beforePrepare 处理,防止某些sql解析不到,又被beforePrepare重复处理
}

19 Source : TriggerValue4NoKeyGenerator.java
with Apache License 2.0
from zhouxx

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    super.processAfter(executor, ms, stmt, parameter);
}

19 Source : TriggerValue4NoKeyGenerator.java
with Apache License 2.0
from zhouxx

@Override
public void processBefore(Executor executor, MappedStatement mappedStatement, Statement stmt, Object parameterObject) {
    if (!(mappedStatement.getSqlCommandType() == SqlCommandType.INSERT || mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE)) {
        return;
    }
    Collection<Object> parameters = parameterreplacedistant.getParameters(parameterObject);
    // trigger auto set value
    if (parameters != null) {
        for (Object parameter : parameters) {
            EnreplacedyMetaData enreplacedyMetaData = EnreplacedyMetaDataRegistry.getInstance().get(parameter.getClreplaced());
            parameterreplacedistant.populateKeyAndTriggerValue(mappedStatement, parameter, enreplacedyMetaData);
        }
    } else {
        EnreplacedyMetaData enreplacedyMetaData = EnreplacedyMetaDataRegistry.getInstance().get(parameterObject.getClreplaced());
        parameterreplacedistant.populateKeyAndTriggerValue(mappedStatement, parameterObject, enreplacedyMetaData);
    }
}

19 Source : TriggerValue4Jdbc3KeyGenerator.java
with Apache License 2.0
from zhouxx

@Override
public void processBefore(Executor executor, MappedStatement mappedStatement, Statement stmt, Object parameterObject) {
    if (!(mappedStatement.getSqlCommandType() == SqlCommandType.INSERT || mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE)) {
        return;
    }
    Collection<Object> parameters = parameterreplacedistant.getParameters(parameterObject);
    // trigger auto set value and id auto set
    if (parameters != null) {
        for (Object parameter : parameters) {
            EnreplacedyMetaData enreplacedyMetaData = EnreplacedyMetaDataRegistry.getInstance().get(parameter.getClreplaced());
            parameterreplacedistant.populateKeyAndTriggerValue(mappedStatement, parameter, enreplacedyMetaData);
        }
    } else {
        EnreplacedyMetaData enreplacedyMetaData = EnreplacedyMetaDataRegistry.getInstance().get(parameterObject.getClreplaced());
        parameterreplacedistant.populateKeyAndTriggerValue(mappedStatement, parameterObject, enreplacedyMetaData);
    }
}

19 Source : DataScopeInterceptor.java
with GNU Lesser General Public License v3.0
from somowhere

@SneakyThrows
@Override
public void beforeQuery(Executor executor, MappedStatement mappedStatement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType() && StatementType.CALLABLE != mappedStatement.getStatementType()) {
        // 查找参数中包含DataScope类型的参数
        DataScope dataScope = findDataScopeObject(parameter);
        if (dataScope != null && !dataScope.isAll()) {
            String scopeName = dataScope.getScopeName(), creatorName = dataScope.getCreatorName(), userId = dataScope.getUserId();
            Set<String> deptIds = dataScope.getDeptIds();
            String originalSql = boundSql.getSql();
            Select selectStatement = (Select) CCJSqlParserUtil.parse(originalSql);
            if (selectStatement.getSelectBody() instanceof PlainSelect) {
                PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody();
                Expression expression = null;
                Alias alias = plainSelect.getFromItem().getAlias();
                String aliaName = "";
                if (alias != null && StringUtil.isNotEmpty(alias.getName())) {
                    aliaName = alias.getName() + StringUtil.DOT;
                }
                if (StringUtil.isNotBlank(scopeName) && CollectionUtil.isNotEmpty(deptIds)) {
                    ItemsList itemsList = new ExpressionList(deptIds.stream().map(deptId -> new StringValue(deptId)).collect(Collectors.toList()));
                    expression = new InExpression(new Column(aliaName + scopeName), itemsList);
                } else if (StringUtil.isNotEmpty(creatorName) && dataScope.isSelf()) {
                    EqualsTo equalsTo = new EqualsTo();
                    equalsTo.setLeftExpression(new Column(aliaName + creatorName));
                    equalsTo.setRightExpression(new StringValue(userId));
                    expression = equalsTo;
                }
                if (expression != null) {
                    AndExpression andExpression = new AndExpression(plainSelect.getWhere(), expression);
                    plainSelect.setWhere(andExpression);
                    PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
                    mpBoundSql.sql(plainSelect.toString());
                }
            }
        }
    }
}

19 Source : PageInterceptor.java
with Apache License 2.0
from open-hand

@Override
public Object intercept(Invocation invocation) throws Throwable {
    try {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        // 由于逻辑关系,只会进入一次
        if (args.length == 4) {
            // 4 个参数时
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            // 6 个参数时
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        List resultList;
        BoundSql sqlWithOrderBy = null;
        boolean executePage = !dialect.skip(ms, parameter, rowBounds);
        // 获得ThreadLocal里面的sort参数
        Sort sort = PageHelper.getLocalSort();
        boolean executeSort = (sort != null);
        // 反射获取动态参数
        Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
        if (executePage && !executeSort) {
            // 只分页,count统计sql
            if (doCount(ms, parameter, rowBounds, resultHandler, executor, boundSql, additionalParameters)) {
                return dialect.afterPage(new ArrayList(), parameter, rowBounds);
            }
            // 判断是否需要进行分页查询
            DoPage doPage = new DoPage(ms, parameter, rowBounds, resultHandler, executor, cacheKey, boundSql, sqlWithOrderBy, additionalParameters).invoke();
            resultList = doPage.getResultList();
            parameter = doPage.getParameter();
            return dialect.afterPage(resultList, parameter, rowBounds);
        } else if (!executePage && executeSort) {
            // 只排序
            parameter = dialect.processParameterObject(ms, parameter, boundSql, cacheKey);
            // 拼接排序order by操作
            sqlWithOrderBy = doSort(ms, parameter, boundSql, sqlWithOrderBy, sort, executeSort);
            // 设置动态参数
            setDynamicParam(sqlWithOrderBy, additionalParameters);
            // 执行排序查询
            return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, sqlWithOrderBy);
        } else if (executePage && executeSort) {
            // 分页和排序
            if (doCount(ms, parameter, rowBounds, resultHandler, executor, boundSql, additionalParameters)) {
                return dialect.afterPage(new ArrayList(), parameter, rowBounds);
            }
            // 拼接排序order by操作
            sqlWithOrderBy = doSort(ms, parameter, boundSql, sqlWithOrderBy, sort, executeSort);
            // 判断是否需要进行分页查询
            DoPage doPage = new DoPage(ms, parameter, rowBounds, resultHandler, executor, cacheKey, boundSql, sqlWithOrderBy, additionalParameters).invoke();
            resultList = doPage.getResultList();
            parameter = doPage.getParameter();
            return dialect.afterPage(resultList, parameter, rowBounds);
        } else {
            // 即不分页也不排序
            // rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
            return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
        }
    } finally {
        dialect.afterAll();
    }
}

19 Source : SnowflakeKeyGenerator.java
with Apache License 2.0
from open-hand

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// do nothing.
}

19 Source : SnowflakeKeyGenerator.java
with Apache License 2.0
from open-hand

@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    if (parameter != null && ms != null && ms.getConfiguration() != null) {
        final MetaObject parameterMeta = ms.getConfiguration().newMetaObject(parameter);
        String[] keyProperties = ms.getKeyProperties();
        if (keyProperties.length != 1) {
            throw new CommonException("Snowflake ID does not support composite primary keys.");
        }
        if (existsKeyValues(parameterMeta, keyProperties, parameter)) {
            return;
        }
        parameterMeta.setValue(keyProperties[0], generateKey());
    }
}

19 Source : SelectKeyGenerator.java
with Apache License 2.0
from open-hand

@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    if (executeBefore) {
        processGeneratedKeys(executor, ms, parameter);
    }
}

19 Source : SelectKeyGenerator.java
with Apache License 2.0
from open-hand

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    if (!executeBefore) {
        processGeneratedKeys(executor, ms, parameter);
    }
}

19 Source : IdentityKeyGenerator.java
with Apache License 2.0
from littlenb

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// do nothing
}

19 Source : IdentityKeyGenerator.java
with Apache License 2.0
from littlenb

@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    processGeneratedKeys(ms, stmt, parameter);
}

19 Source : SnowflakeIdKeyGenerator.java
with Apache License 2.0
from lightbatis

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
}

19 Source : SnowflakeIdKeyGenerator.java
with Apache License 2.0
from lightbatis

@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    // do nothing
    processGeneratedKeys(executor, ms, parameter);
}

19 Source : CatMybatisPlugin.java
with MIT License
from KevinClair

/**
 * CatMybatisPlugin.
 *
 * @author KevinClair
 */
@Intercepts({ @Signature(method = "query", type = Executor.clreplaced, args = { MappedStatement.clreplaced, Object.clreplaced, RowBounds.clreplaced, ResultHandler.clreplaced }), @Signature(method = "update", type = Executor.clreplaced, args = { MappedStatement.clreplaced, Object.clreplaced }) })
public clreplaced CatMybatisPlugin implements Interceptor {

    private static final Pattern PARAMETER_PATTERN = Pattern.compile("\\?");

    private static final String MYSQL_DEFAULT_URL = "jdbc:mysql://UUUUUKnown:3306/%s?useUnicode=true";

    private Executor target;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = this.getStatement(invocation);
        String methodName = this.getMethodName(mappedStatement);
        Transaction t = Cat.newTransaction(CatTypeEnum.MYBATIS_REQUEST.getName(), methodName);
        String sql = this.getSql(invocation, mappedStatement);
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Cat.logEvent(CatEventTypeEnum.MYBATIS_REQUEST_COMMANDTYPE.getName(), sqlCommandType.name().toLowerCase(), Message.SUCCESS, sql);
        // String url = this.getSQLDatabaseUrlByStatement(mappedStatement);
        // Cat.logEvent(CatEventTypeEnum.MYBATIS_REQUEST_DATABASE.getName(), url);
        return doFinish(invocation, t);
    }

    private MappedStatement getStatement(Invocation invocation) {
        return (MappedStatement) invocation.getArgs()[0];
    }

    private String getMethodName(MappedStatement mappedStatement) {
        String[] strArr = mappedStatement.getId().split("\\.");
        String methodName = strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];
        return methodName;
    }

    private String getSql(Invocation invocation, MappedStatement mappedStatement) {
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        String sql = sqlResolve(configuration, boundSql);
        return sql;
    }

    private Object doFinish(Invocation invocation, Transaction t) throws Throwable {
        Object returnObj = null;
        try {
            returnObj = invocation.proceed();
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception e) {
            Cat.logError(e);
            t.setStatus(e);
            throw e;
        } finally {
            t.complete();
        }
        return returnObj;
    }

    private String getSQLDatabaseUrlByStatement(MappedStatement mappedStatement) {
        String url = null;
        DataSource dataSource = null;
        try {
            Configuration configuration = mappedStatement.getConfiguration();
            Environment environment = configuration.getEnvironment();
            dataSource = environment.getDataSource();
            url = switchDataSource(dataSource);
            return url;
        } catch (NoSuchFieldException | IllegalAccessException | NullPointerException e) {
            Cat.logError(e);
        }
        Cat.logError(new Exception("UnSupport type of DataSource : " + dataSource.getClreplaced().toString()));
        return MYSQL_DEFAULT_URL;
    }

    private String switchDataSource(DataSource dataSource) throws NoSuchFieldException, IllegalAccessException {
        String url = null;
        if (dataSource instanceof HikariDataSource) {
            url = ((HikariDataSource) dataSource).getJdbcUrl().substring(0, ((HikariDataSource) dataSource).getJdbcUrl().indexOf("?"));
        } else if (dataSource instanceof PooledDataSource) {
            Field dataSource1 = dataSource.getClreplaced().getDeclaredField("dataSource");
            dataSource1.setAccessible(true);
            UnpooledDataSource dataSource2 = (UnpooledDataSource) dataSource1.get(dataSource);
            url = dataSource2.getUrl();
        } else {
        // other dataSource expand
        }
        return url;
    }

    public String sqlResolve(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClreplaced())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(resolveParameterValue(parameterObject)));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                Matcher matcher = PARAMETER_PATTERN.matcher(sql);
                StringBuffer sqlBuffer = new StringBuffer();
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    Object obj = null;
                    if (metaObject.hasGetter(propertyName)) {
                        obj = metaObject.getValue(propertyName);
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        obj = boundSql.getAdditionalParameter(propertyName);
                    }
                    if (matcher.find()) {
                        matcher.appendReplacement(sqlBuffer, Matcher.quoteReplacement(resolveParameterValue(obj)));
                    }
                }
                matcher.appendTail(sqlBuffer);
                sql = sqlBuffer.toString();
            }
        }
        return sql;
    }

    private String resolveParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format((Date) obj) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            this.target = (Executor) target;
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
    }
}

19 Source : DefaultResultSetHandlerTest2.java
with Apache License 2.0
from huifer

@SuppressWarnings("serial")
@Test
void shouldNotCallNextOnClosedResultSet_NestedResult() throws Exception {
    final Configuration config = new Configuration();
    final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
    final ResultMap nestedResultMap = new ResultMap.Builder(config, "roleMap", HashMap.clreplaced, new ArrayList<ResultMapping>() {

        {
            add(new ResultMapping.Builder(config, "role", "role", registry.getTypeHandler(String.clreplaced)).build());
        }
    }).build();
    config.addResultMap(nestedResultMap);
    final MappedStatement ms = new MappedStatement.Builder(config, "selectPerson", new StaticSqlSource(config, "select person..."), SqlCommandType.SELECT).resultMaps(new ArrayList<ResultMap>() {

        {
            add(new ResultMap.Builder(config, "personMap", HashMap.clreplaced, new ArrayList<ResultMapping>() {

                {
                    add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.clreplaced)).build());
                    add(new ResultMapping.Builder(config, "roles").nestedResultMapId("roleMap").build());
                }
            }).build());
        }
    }).resultOrdered(true).build();
    final Executor executor = null;
    final ParameterHandler parameterHandler = null;
    final ResultHandler<?> resultHandler = null;
    final BoundSql boundSql = null;
    final RowBounds rowBounds = new RowBounds(5, 1);
    final DefaultResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, ms, parameterHandler, resultHandler, boundSql, rowBounds);
    when(stmt.getResultSet()).thenReturn(rs);
    when(rsmd.getColumnCount()).thenReturn(2);
    when(rsmd.getColumnLabel(1)).thenReturn("id");
    when(rsmd.getColumnType(1)).thenReturn(Types.INTEGER);
    when(rsmd.getColumnClreplacedName(1)).thenReturn(Integer.clreplaced.getCanonicalName());
    final List<Object> results = resultSetHandler.handleResultSets(stmt);
    replacedertEquals(0, results.size());
}

19 Source : DefaultResultSetHandlerTest2.java
with Apache License 2.0
from huifer

@SuppressWarnings("serial")
@Test
void shouldNotCallNextOnClosedResultSet_SimpleResult() throws Exception {
    final Configuration config = new Configuration();
    final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
    final MappedStatement ms = new MappedStatement.Builder(config, "testSelect", new StaticSqlSource(config, "some select statement"), SqlCommandType.SELECT).resultMaps(new ArrayList<ResultMap>() {

        {
            add(new ResultMap.Builder(config, "testMap", HashMap.clreplaced, new ArrayList<ResultMapping>() {

                {
                    add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.clreplaced)).build());
                }
            }).build());
        }
    }).build();
    final Executor executor = null;
    final ParameterHandler parameterHandler = null;
    final ResultHandler<?> resultHandler = null;
    final BoundSql boundSql = null;
    final RowBounds rowBounds = new RowBounds(5, 1);
    final DefaultResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, ms, parameterHandler, resultHandler, boundSql, rowBounds);
    when(stmt.getResultSet()).thenReturn(rs);
    when(rsmd.getColumnCount()).thenReturn(1);
    when(rsmd.getColumnLabel(1)).thenReturn("id");
    when(rsmd.getColumnType(1)).thenReturn(Types.INTEGER);
    when(rsmd.getColumnClreplacedName(1)).thenReturn(Integer.clreplaced.getCanonicalName());
    when(stmt.getConnection()).thenReturn(conn);
    when(conn.getMetaData()).thenReturn(dbmd);
    // for simplicity.
    when(dbmd.supportsMultipleResultSets()).thenReturn(false);
    final List<Object> results = resultSetHandler.handleResultSets(stmt);
    replacedertEquals(0, results.size());
}

19 Source : DefaultResultSetHandlerTest.java
with Apache License 2.0
from huifer

/**
 * Contrary to the spec, some drivers require case-sensitive column names when getting result.
 *
 * @see <a href="http://code.google.com/p/mybatis/issues/detail?id=557">Issue 557</a>
 */
@Test
void shouldRetainColumnNameCase() throws Exception {
    final MappedStatement ms = getMappedStatement();
    final Executor executor = null;
    final ParameterHandler parameterHandler = null;
    final ResultHandler resultHandler = null;
    final BoundSql boundSql = null;
    final RowBounds rowBounds = new RowBounds(0, 100);
    final DefaultResultSetHandler fastResultSetHandler = new DefaultResultSetHandler(executor, ms, parameterHandler, resultHandler, boundSql, rowBounds);
    when(stmt.getResultSet()).thenReturn(rs);
    when(rs.getMetaData()).thenReturn(rsmd);
    when(rs.getType()).thenReturn(ResultSet.TYPE_FORWARD_ONLY);
    when(rs.next()).thenReturn(true).thenReturn(false);
    when(rs.getInt("CoLuMn1")).thenReturn(100);
    when(rsmd.getColumnCount()).thenReturn(1);
    when(rsmd.getColumnLabel(1)).thenReturn("CoLuMn1");
    when(rsmd.getColumnType(1)).thenReturn(Types.INTEGER);
    when(rsmd.getColumnClreplacedName(1)).thenReturn(Integer.clreplaced.getCanonicalName());
    when(stmt.getConnection()).thenReturn(conn);
    when(conn.getMetaData()).thenReturn(dbmd);
    // for simplicity.
    when(dbmd.supportsMultipleResultSets()).thenReturn(false);
    final List<Object> results = fastResultSetHandler.handleResultSets(stmt);
    replacedertEquals(1, results.size());
    replacedertEquals(100, ((HashMap) results.get(0)).get("cOlUmN1"));
}

19 Source : DefaultSqlSession.java
with Apache License 2.0
from huifer

/**
 * mybatis 默认的sqlSession
 * The default implementation for {@link SqlSession}.
 * Note that this clreplaced is not Thread-Safe.
 *
 * @author Clinton Begin
 */
public clreplaced DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    private final Executor executor;

    private final boolean autoCommit;

    private boolean dirty;

    private List<Cursor<?>> cursorList;

    /**
     * 默认的 sql session
     * @param configuration mybatis-config.xml
     * @param executor {@link Executor}
     * @param autoCommit 自动commit
     */
    public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
        this.configuration = configuration;
        this.executor = executor;
        this.dirty = false;
        this.autoCommit = autoCommit;
    }

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this(configuration, executor, false);
    }

    @Override
    public <T> T selectOne(String statement) {
        return this.selectOne(statement, null);
    }

    /**
     * 执行 selectList().get(0)
     * @param statement Unique identifier matching the statement to use.
     * @param parameter A parameter object to preplaced to the statement.
     * @param <T>
     * @return
     */
    @Override
    public <T> T selectOne(String statement, Object parameter) {
        // Popular vote was to return null on 0 results and throw exception on too many.
        List<T> list = this.selectList(statement, parameter);
        if (list.size() == 1) {
            return list.get(0);
        } else if (list.size() > 1) {
            throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
        } else {
            return null;
        }
    }

    @Override
    public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
        return this.selectMap(statement, null, mapKey, RowBounds.DEFAULT);
    }

    @Override
    public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
        return this.selectMap(statement, parameter, mapKey, RowBounds.DEFAULT);
    }

    /**
     * @param statement Unique identifier matching the statement to use.
     * @param parameter A parameter object to preplaced to the statement.
     * @param mapKey The property to use as key for each value in the list.
     * @param rowBounds  Bounds to limit object retrieval
     * @param <K>
     * @param <V>
     * @return
     */
    @Override
    public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
        final List<? extends V> list = selectList(statement, parameter, rowBounds);
        final DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler<>(mapKey, configuration.getObjectFactory(), configuration.getObjectWrapperFactory(), configuration.getReflectorFactory());
        final DefaultResultContext<V> context = new DefaultResultContext<>();
        for (V o : list) {
            context.nextResultObject(o);
            mapResultHandler.handleResult(context);
        }
        return mapResultHandler.getMappedResults();
    }

    @Override
    public <T> Cursor<T> selectCursor(String statement) {
        return selectCursor(statement, null);
    }

    @Override
    public <T> Cursor<T> selectCursor(String statement, Object parameter) {
        return selectCursor(statement, parameter, RowBounds.DEFAULT);
    }

    @Override
    public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) {
        try {
            MappedStatement ms = configuration.getMappedStatement(statement);
            Cursor<T> cursor = executor.queryCursor(ms, wrapCollection(parameter), rowBounds);
            registerCursor(cursor);
            return cursor;
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    @Override
    public <E> List<E> selectList(String statement) {
        return this.selectList(statement, null);
    }

    /**
     * 向下继续调用
     * @param statement Unique identifier matching the statement to use.
     * @param parameter A parameter object to preplaced to the statement.
     * @param <E>
     * @return
     */
    @Override
    public <E> List<E> selectList(String statement, Object parameter) {
        return this.selectList(statement, parameter, RowBounds.DEFAULT);
    }

    /**
     * 执行query
     * @param statement Unique identifier matching the statement to use.
     * @param parameter A parameter object to preplaced to the statement.
     * @param rowBounds  Bounds to limit object retrieval
     * @param <E>
     * @return
     */
    @Override
    public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
        try {
            MappedStatement ms = configuration.getMappedStatement(statement);
            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();
        }
    }

    @Override
    public void select(String statement, Object parameter, ResultHandler handler) {
        select(statement, parameter, RowBounds.DEFAULT, handler);
    }

    @Override
    public void select(String statement, ResultHandler handler) {
        select(statement, null, RowBounds.DEFAULT, handler);
    }

    @Override
    public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
        try {
            MappedStatement ms = configuration.getMappedStatement(statement);
            executor.query(ms, wrapCollection(parameter), rowBounds, handler);
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    @Override
    public int insert(String statement) {
        return insert(statement, null);
    }

    @Override
    public int insert(String statement, Object parameter) {
        return update(statement, parameter);
    }

    @Override
    public int update(String statement) {
        return update(statement, null);
    }

    @Override
    public int update(String statement, Object parameter) {
        try {
            dirty = true;
            MappedStatement ms = configuration.getMappedStatement(statement);
            return executor.update(ms, wrapCollection(parameter));
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error updating database.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    @Override
    public int delete(String statement) {
        return update(statement, null);
    }

    @Override
    public int delete(String statement, Object parameter) {
        return update(statement, parameter);
    }

    @Override
    public void commit() {
        commit(false);
    }

    @Override
    public void commit(boolean force) {
        try {
            executor.commit(isCommitOrRollbackRequired(force));
            dirty = false;
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error committing transaction.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    @Override
    public void rollback() {
        rollback(false);
    }

    @Override
    public void rollback(boolean force) {
        try {
            executor.rollback(isCommitOrRollbackRequired(force));
            dirty = false;
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error rolling back transaction.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    @Override
    public List<BatchResult> flushStatements() {
        try {
            return executor.flushStatements();
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error flushing statements.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }

    @Override
    public void close() {
        try {
            executor.close(isCommitOrRollbackRequired(false));
            closeCursors();
            dirty = false;
        } finally {
            ErrorContext.instance().reset();
        }
    }

    private void closeCursors() {
        if (cursorList != null && !cursorList.isEmpty()) {
            for (Cursor<?> cursor : cursorList) {
                try {
                    cursor.close();
                } catch (IOException e) {
                    throw ExceptionFactory.wrapException("Error closing cursor.  Cause: " + e, e);
                }
            }
            cursorList.clear();
        }
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }

    @Override
    public <T> T getMapper(Clreplaced<T> type) {
        return configuration.getMapper(type, this);
    }

    @Override
    public Connection getConnection() {
        try {
            return executor.getTransaction().getConnection();
        } catch (SQLException e) {
            throw ExceptionFactory.wrapException("Error getting a new connection.  Cause: " + e, e);
        }
    }

    @Override
    public void clearCache() {
        executor.clearLocalCache();
    }

    private <T> void registerCursor(Cursor<T> cursor) {
        if (cursorList == null) {
            cursorList = new ArrayList<>();
        }
        cursorList.add(cursor);
    }

    private boolean isCommitOrRollbackRequired(boolean force) {
        return (!autoCommit && dirty) || force;
    }

    private Object wrapCollection(final Object object) {
        if (object instanceof Collection) {
            StrictMap<Object> map = new StrictMap<>();
            map.put("collection", object);
            if (object instanceof List) {
                map.put("list", object);
            }
            return map;
        } else if (object != null && object.getClreplaced().isArray()) {
            StrictMap<Object> map = new StrictMap<>();
            map.put("array", object);
            return map;
        }
        return object;
    }

    public static clreplaced StrictMap<V> extends HashMap<String, V> {

        private static final long serialVersionUID = -5741767162221585340L;

        @Override
        public V get(Object key) {
            if (!super.containsKey(key)) {
                throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + this.keySet());
            }
            return super.get(key);
        }
    }
}

19 Source : ResultLoader.java
with Apache License 2.0
from huifer

private <E> List<E> selectList() throws SQLException {
    Executor localExecutor = executor;
    if (Thread.currentThread().getId() != this.creatorThreadId || localExecutor.isClosed()) {
        localExecutor = newExecutor();
    }
    try {
        return localExecutor.query(mappedStatement, parameterObject, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER, cacheKey, boundSql);
    } finally {
        if (localExecutor != executor) {
            localExecutor.close(false);
        }
    }
}

19 Source : NoKeyGenerator.java
with Apache License 2.0
from huifer

@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// Do Nothing
}

19 Source : NoKeyGenerator.java
with Apache License 2.0
from huifer

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// Do Nothing
}

19 Source : Jdbc3KeyGenerator.java
with Apache License 2.0
from huifer

@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// do nothing
}

19 Source : Jdbc3KeyGenerator.java
with Apache License 2.0
from huifer

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    processBatch(ms, stmt, parameter);
}

19 Source : ExecutorHelper.java
with Apache License 2.0
from hengboy

/**
 * 执行查询
 *
 * @param executor 执行器
 * @param request  执行查询请求对象
 * @param <E>      泛型类型
 * @return 查询后的数据列表
 * @throws SQLException 数据库异常
 */
public static <E> List<E> query(Executor executor, ExecutorQueryRequest request) throws SQLException {
    return executor.query(request.getStatement(), request.getParameter(), request.getRowBounds(), request.getResultHandler(), request.getCacheKey(), request.getBoundSql());
}

19 Source : UUIDKeyGenerator.java
with MIT License
from hengboy

/**
 * 执行后的方法
 * @param executor 执行对象
 * @param ms MappedStatement对象实例
 * @param statement Statement数据对象实例
 * @param parameter 参数对象
 */
@Override
public void processAfter(Executor executor, MappedStatement ms, Statement statement, Object parameter) {
}

19 Source : UUIDKeyGenerator.java
with MIT License
from hengboy

/**
 * 在执行insert之前设置对应主键的值
 *
 * @param executor 执行对象
 * @param ms MappedStatement对象实例
 * @param statement Statement数据对象实例
 * @param parameter 参数对象
 */
@Override
public void processBefore(Executor executor, MappedStatement ms, Statement statement, Object parameter) {
    // 如果参数存在多个,为每一个参数实体的主键都设置
    batchProcessBefore(ms, getParameters(parameter));
}

19 Source : MybatisUtils.java
with GNU Lesser General Public License v3.0
from fangjinuo

/**
 * @deprecated
 * @see #getDatabaseId(SqlRequestContextHolder, SQLStatementInstrumentor, MappedStatement, Executor, boolean)
 */
public static String getDatabaseId(@Nullable SqlRequestContextHolder sqlRequestContextHolder, @Nullable SQLStatementInstrumentor instrumentor, @NonNull final MappedStatement ms, Executor executor) {
    return getDatabaseId(sqlRequestContextHolder, instrumentor, ms, executor, true);
}

19 Source : PageStatementInterceptor.java
with Apache License 2.0
from chubaostream

@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler handler = (StatementHandler) invocation.getTarget();
    // 获取MappedStatement,Configuration对象
    MetaObject metaObject = MetaObject.forObject(handler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    String statement = mappedStatement.getId();
    if (!isPageSql(statement, metaObject.getValue("boundSql.parameterObject"))) {
        return invocation.proceed();
    }
    Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration");
    Executor executor = (Executor) metaObject.getValue("delegate.executor");
    // 获取分页参数
    BoundSql boundSql = handler.getBoundSql();
    QPageQuery pageQuery = (QPageQuery) boundSql.getParameterObject();
    String countStatement = buildCountStatement(statement);
    List<Integer> counts = executor.query(configuration.getMappedStatement(countStatement), pageQuery, RowBounds.DEFAULT, null);
    int count = 0;
    if (counts != null && !counts.isEmpty()) {
        count = counts.get(0) == null ? 0 : counts.get(0);
    }
    if (pageQuery.getPagination() == null) {
        pageQuery.setPagination(new Pagination());
    }
    pageQuery.getPagination().setTotalRecord(count);
    String sql = boundSql.getSql();
    if (logger.isDebugEnabled()) {
        logger.debug("raw SQL : " + sql);
    }
    if (sql == null || sql.isEmpty() || sql.contains(" limit ")) {
        return invocation.proceed();
    }
    String originalSql = (String) metaObject.getValue("delegate.boundSql.sql");
    metaObject.setValue("delegate.boundSql.sql", getLimitString(originalSql, pageQuery.getPagination().getStart(), pageQuery.getPagination().getSize()));
    metaObject.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
    metaObject.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
    if (logger.isDebugEnabled()) {
        logger.debug("pagination SQL : " + sql);
    }
    return invocation.proceed();
}

19 Source : PagePlugin.java
with Apache License 2.0
from chenlijia1111

/**
 * 执行拦截逻辑的方法
 *
 * @param invocation
 * @return
 * @throws Throwable
 */
@Override
public Object intercept(Invocation invocation) throws Throwable {
    // 注入的参数
    Object[] args = invocation.getArgs();
    MappedStatement mappedStatement = (MappedStatement) args[0];
    Object parameterObject = args[1];
    RowBounds rowBounds = (RowBounds) args[2];
    ResultHandler resultHandler = (ResultHandler) args[3];
    Executor executor = (Executor) invocation.getTarget();
    CacheKey cacheKey;
    BoundSql boundSql;
    // 由于逻辑关系,只会进入一次
    if (args.length == 4) {
        // 4 个参数时
        boundSql = mappedStatement.getBoundSql(parameterObject);
        cacheKey = executor.createCacheKey(mappedStatement, parameterObject, rowBounds, boundSql);
    } else {
        // 6 个参数时
        cacheKey = (CacheKey) args[4];
        boundSql = (BoundSql) args[5];
    }
    // 获取分页参数
    Page page = findCurrentPageParameter(parameterObject);
    if (Objects.nonNull(page)) {
        // 进行分页操作
        // 创建一个MappedStatement
        String countMsId = mappedStatement.getId() + PAGE_COUNT_ID_SUFFIX;
        MappedStatement countMappedStatement = MSUtils.newCountMappedStatement(mappedStatement, countMsId);
        Long autoCount = ExecutorUtil.executeAutoCount(executor, countMappedStatement, parameterObject, boundSql, rowBounds, resultHandler);
        page.setCount(autoCount.intValue());
        // 重新赋值线程变量,更新里面的 count 值
        PageThreadLocalParameter.setPageParameter(page);
        // 设置新的MappedStatement 加上分页
        List resultList = ExecutorUtil.pageQuery(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql, cacheKey);
        return resultList;
    }
    return invocation.proceed();
}

19 Source : PageInterceptor.java
with MIT License
from aoju

private Long count(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    String countMsId = ms.getId() + countSuffix;
    Long count;
    // 先判断是否存在手写的 count 查询
    MappedStatement countMs = CountExecutor.getExistedMappedStatement(ms.getConfiguration(), countMsId);
    if (countMs != null) {
        count = CountExecutor.executeManualCount(executor, countMs, parameter, boundSql, resultHandler);
    } else {
        countMs = msCountMap.get(countMsId);
        // 自动创建
        if (countMs == null) {
            // 根据当前的 ms 创建一个返回值为 Long 类型的 ms
            countMs = CountMappedStatement.newCountMappedStatement(ms, countMsId);
            msCountMap.put(countMsId, countMs);
        }
        count = CountExecutor.executeAutoCount(dialect, executor, countMs, parameter, boundSql, rowBounds, resultHandler);
    }
    return count;
}

19 Source : CountExecutor.java
with MIT License
from aoju

/**
 * 分页查询
 *
 * @param dialect       方言
 * @param executor      执行者
 * @param ms            MappedStatement
 * @param parameter     参数
 * @param rowBounds     RowBounds
 * @param resultHandler ResultHandler
 * @param boundSql      BoundSql
 * @param cacheKey      CacheKey
 * @param <E>           对象
 * @return the object
 * @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);
    }
}

19 Source : CountExecutor.java
with MIT License
from aoju

/**
 * 执行自动生成的 count 查询
 *
 * @param dialect       方言
 * @param executor      执行者
 * @param countMs       MappedStatement
 * @param parameter     参数
 * @param boundSql      BoundSql
 * @param rowBounds     RowBounds
 * @param resultHandler ResultHandler
 * @return the long
 * @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);
    return (Long) ((List) countResultList).get(0);
}

19 Source : CountExecutor.java
with MIT License
from aoju

/**
 * 执行手动设置的 count 查询,该查询支持的参数必须和被分页的方法相同
 *
 * @param executor      执行者
 * @param countMs       MappedStatement
 * @param parameter     参数
 * @param boundSql      BoundSql
 * @param resultHandler ResultHandler
 * @return the long
 * @throws SQLException 异常
 */
public static Long executeManualCount(Executor executor, MappedStatement countMs, Object parameter, BoundSql boundSql, ResultHandler resultHandler) throws SQLException {
    CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
    BoundSql countBoundSql = countMs.getBoundSql(parameter);
    Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
    return ((Number) ((List) countResultList).get(0)).longValue();
}

18 Source : DataScopeInnerInterceptor.java
with Apache License 2.0
from zuihou

@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    DataScope dataScope = findDataScope(parameter).orElse(null);
    if (dataScope == null) {
        return;
    }
    String originalSql = boundSql.getSql();
    String scopeName = dataScope.getScopeName();
    String selfScopeName = dataScope.getSelfScopeName();
    Long userId = dataScope.getUserId() == null ? ContextUtil.getUserId() : dataScope.getUserId();
    List<Long> orgIds = dataScope.getOrgIds();
    DataScopeType dsType = DataScopeType.SELF;
    if (CollectionUtil.isEmpty(orgIds)) {
        // 查询当前用户的 角色 最小权限
        // userId
        // dsType orgIds
        Map<String, Object> result = function.apply(userId);
        if (result == null) {
            return;
        }
        Integer type = (Integer) result.get("dsType");
        dsType = DataScopeType.get(type);
        orgIds = (List<Long>) result.get("orgIds");
    }
    // 查全部
    if (DataScopeType.ALL.eq(dsType)) {
        return;
    }
    // 查个人
    if (DataScopeType.SELF.eq(dsType)) {
        originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + selfScopeName + " = " + userId;
    } else // 查其他
    if (StrUtil.isNotBlank(scopeName) && CollUtil.isNotEmpty(orgIds)) {
        String join = CollectionUtil.join(orgIds, ",");
        originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
    }
    PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
    mpBoundSql.sql(originalSql);
}

18 Source : LockHelper.java
with GNU General Public License v3.0
from xiaomujiayou

@Override
public Object intercept(Invocation invocation) throws Throwable {
    String orderBy = ORDERBY_LOCAL.get();
    if (orderBy != null && orderBy.length() > 0) {
        ORDERBY_LOCAL.remove();
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        // 由于逻辑关系,只会进入一次
        if (args.length == 4) {
            // 4 个参数时
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            // 6 个参数时
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        String sql = boundSql.getSql();
        String orderBySql = sql + " for update ";
        // 更新cacheKey,防止缓存错误#3
        cacheKey.update(orderBy);
        BoundSql orderbyBoundSql = new BoundSql(ms.getConfiguration(), orderBySql, boundSql.getParameterMappings(), parameter);
        Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
        for (String key : additionalParameters.keySet()) {
            orderbyBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
        }
        return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, orderbyBoundSql);
    } else {
        return invocation.proceed();
    }
}

18 Source : MybatisSessionFactory.java
with Apache License 2.0
from XiaoMi

@Override
public SqlSession openSession(boolean autoCommit) {
    try {
        final Environment environment = configuration.getEnvironment();
        Transaction tx = null;
        if (TransactionalContext.getContext().get() != null) {
            MybatisTransaction _tx = TransactionalContext.getContext().get();
            _tx.setDataSource(environment.getDataSource());
            tx = _tx;
        } else {
            TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
            tx = transactionFactory.newTransaction(environment.getDataSource(), null, autoCommit);
        }
        final Executor executor = configuration.newExecutor(tx, configuration.getDefaultExecutorType());
        return new DefaultSqlSession(configuration, executor, autoCommit);
    } finally {
        ErrorContext.instance().reset();
    }
}

18 Source : MultipleJdbc3KeyGenerator.java
with Apache License 2.0
from open-hand

@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
    processBatch(ms, stmt, getParameters(parameter));
}

18 Source : DefaultResultSetHandler.java
with Apache License 2.0
from open-hand

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 * @author Iwao AVE!
 * @author Kazuki Shimizu
 */
public clreplaced DefaultResultSetHandler implements ResultSetHandler {

    private static final Object DEFERED = new Object();

    private final Executor executor;

    private final Configuration configuration;

    private final MappedStatement mappedStatement;

    private final RowBounds rowBounds;

    private final ParameterHandler parameterHandler;

    private final ResultHandler<?> resultHandler;

    private final BoundSql boundSql;

    private final TypeHandlerRegistry typeHandlerRegistry;

    private final ObjectFactory objectFactory;

    private final ReflectorFactory reflectorFactory;

    // nested resultmaps
    private final Map<CacheKey, Object> nestedResultObjects = new HashMap<CacheKey, Object>();

    private final Map<String, Object> ancestorObjects = new HashMap<String, Object>();

    private Object previousRowValue;

    // multiple resultsets
    private final Map<String, ResultMapping> nextResultMaps = new HashMap<String, ResultMapping>();

    private final Map<CacheKey, List<PendingRelation>> pendingRelations = new HashMap<CacheKey, List<PendingRelation>>();

    // Cached Automappings
    private final Map<String, List<UnMappedColumnAutoMapping>> autoMappingsCache = new HashMap<String, List<UnMappedColumnAutoMapping>>();

    // temporary marking flag that indicate using constructor mapping (use field to reduce memory usage)
    private boolean useConstructorMappings;

    private static clreplaced PendingRelation {

        public MetaObject metaObject;

        public ResultMapping propertyMapping;
    }

    private static clreplaced UnMappedColumnAutoMapping {

        private final String column;

        private final String property;

        private final TypeHandler<?> typeHandler;

        private final boolean primitive;

        public UnMappedColumnAutoMapping(String column, String property, TypeHandler<?> typeHandler, boolean primitive) {
            this.column = column;
            if ("flex.".equals(property)) {
                property = column;
            }
            this.property = property;
            this.typeHandler = typeHandler;
            this.primitive = primitive;
        }
    }

    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.reflectorFactory = configuration.getReflectorFactory();
        this.resultHandler = resultHandler;
    }

    // 
    // HANDLE OUTPUT PARAMETER
    // 
    @Override
    public void handleOutputParameters(CallableStatement cs) throws SQLException {
        final Object parameterObject = parameterHandler.getParameterObject();
        final MetaObject metaParam = configuration.newMetaObject(parameterObject);
        final List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            final ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
                if (ResultSet.clreplaced.equals(parameterMapping.getJavaType())) {
                    handleRefCursorOutputParameter((ResultSet) cs.getObject(i + 1), parameterMapping, metaParam);
                } else {
                    final TypeHandler<?> typeHandler = parameterMapping.getTypeHandler();
                    metaParam.setValue(parameterMapping.getProperty(), typeHandler.getResult(cs, i + 1));
                }
            }
        }
    }

    private void handleRefCursorOutputParameter(ResultSet rs, ParameterMapping parameterMapping, MetaObject metaParam) throws SQLException {
        if (rs == null) {
            return;
        }
        try {
            final String resultMapId = parameterMapping.getResultMapId();
            final ResultMap resultMap = configuration.getResultMap(resultMapId);
            final DefaultResultHandler resultHandler = new DefaultResultHandler(objectFactory);
            final ResultSetWrapper rsw = new ResultSetWrapper(rs, configuration);
            handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
            metaParam.setValue(parameterMapping.getProperty(), resultHandler.getResultList());
        } finally {
            // issue #228 (close resultsets)
            closeResultSet(rs);
        }
    }

    // 
    // HANDLE RESULT SETS
    // 
    @Override
    public List<Object> handleResultSets(Statement stmt) throws SQLException {
        ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
        final List<Object> multipleResults = new ArrayList<Object>();
        int resultSetCount = 0;
        ResultSetWrapper rsw = getFirstResultSet(stmt);
        List<ResultMap> resultMaps = mappedStatement.getResultMaps();
        int resultMapCount = resultMaps.size();
        validateResultMapsCount(rsw, resultMapCount);
        while (rsw != null && resultMapCount > resultSetCount) {
            ResultMap resultMap = resultMaps.get(resultSetCount);
            handleResultSet(rsw, resultMap, multipleResults, null);
            rsw = getNextResultSet(stmt);
            cleanUpAfterHandlingResultSet();
            resultSetCount++;
        }
        String[] resultSets = mappedStatement.getResultSets();
        if (resultSets != null) {
            while (rsw != null && resultSetCount < resultSets.length) {
                ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
                if (parentMapping != null) {
                    String nestedResultMapId = parentMapping.getNestedResultMapId();
                    ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
                    handleResultSet(rsw, resultMap, null, parentMapping);
                }
                rsw = getNextResultSet(stmt);
                cleanUpAfterHandlingResultSet();
                resultSetCount++;
            }
        }
        return collapseSingleResultList(multipleResults);
    }

    @Override
    public <E> Cursor<E> handleCursorResultSets(Statement stmt) throws SQLException {
        ErrorContext.instance().activity("handling cursor results").object(mappedStatement.getId());
        ResultSetWrapper rsw = getFirstResultSet(stmt);
        List<ResultMap> resultMaps = mappedStatement.getResultMaps();
        int resultMapCount = resultMaps.size();
        validateResultMapsCount(rsw, resultMapCount);
        if (resultMapCount != 1) {
            throw new ExecutorException("Cursor results cannot be mapped to multiple resultMaps");
        }
        ResultMap resultMap = resultMaps.get(0);
        return new DefaultCursor<E>(this, resultMap, rsw, rowBounds);
    }

    private ResultSetWrapper getFirstResultSet(Statement stmt) throws SQLException {
        ResultSet rs = stmt.getResultSet();
        return new ResultSetWrapper(rs, configuration);
    }

    private ResultSetWrapper getNextResultSet(Statement stmt) throws SQLException {
        // Making this method tolerant of bad JDBC drivers
        try {
            if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
                // Crazy Standard JDBC way of determining if there are more results
                if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) {
                    ResultSet rs = stmt.getResultSet();
                    return new ResultSetWrapper(rs, configuration);
                }
            }
        } catch (Exception e) {
        // Intentionally ignored.
        }
        return null;
    }

    private void closeResultSet(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
        // ignore
        }
    }

    private void cleanUpAfterHandlingResultSet() {
        nestedResultObjects.clear();
    }

    private void validateResultMapsCount(ResultSetWrapper rsw, int resultMapCount) {
        if (rsw != null && resultMapCount < 1) {
            throw new ExecutorException("A query was run and no Result Maps were found for the Mapped Statement '" + mappedStatement.getId() + "'.  It's likely that neither a Result Type nor a Result Map was specified.");
        }
    }

    private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
        try {
            if (parentMapping != null) {
                handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
            } else {
                if (resultHandler == null) {
                    DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
                    handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
                    multipleResults.add(defaultResultHandler.getResultList());
                } else {
                    handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
                }
            }
        } finally {
            // issue #228 (close resultsets)
            closeResultSet(rsw.getResultSet());
        }
    }

    @SuppressWarnings("unchecked")
    private List<Object> collapseSingleResultList(List<Object> multipleResults) {
        return multipleResults.size() == 1 ? (List<Object>) multipleResults.get(0) : multipleResults;
    }

    // 
    // HANDLE ROWS FOR SIMPLE RESULTMAP
    // 
    public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
        if (resultMap.hasNestedResultMaps()) {
            ensureNoRowBounds();
            checkResultHandler();
            handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
        } else {
            handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
        }
    }

    private void ensureNoRowBounds() {
        if (configuration.isSafeRowBoundsEnabled() && rowBounds != null && (rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT || rowBounds.getOffset() > RowBounds.NO_ROW_OFFSET)) {
            throw new ExecutorException("Mapped Statements with nested result mappings cannot be safely constrained by RowBounds. " + "Use safeRowBoundsEnabled=false setting to bypreplaced this check.");
        }
    }

    protected void checkResultHandler() {
        if (resultHandler != null && configuration.isSafeResultHandlerEnabled() && !mappedStatement.isResultOrdered()) {
            throw new ExecutorException("Mapped Statements with nested result mappings cannot be safely used with a custom ResultHandler. " + "Use safeResultHandlerEnabled=false setting to bypreplaced this check " + "or ensure your statement returns ordered data and set resultOrdered=true on it.");
        }
    }

    private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
        DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
        skipRows(rsw.getResultSet(), rowBounds);
        while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
            ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
            Object rowValue = getRowValue(rsw, discriminatedResultMap);
            storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
        }
    }

    private void storeObject(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext, Object rowValue, ResultMapping parentMapping, ResultSet rs) throws SQLException {
        if (parentMapping != null) {
            linkToParents(rs, parentMapping, rowValue);
        } else {
            callResultHandler(resultHandler, resultContext, rowValue);
        }
    }

    @SuppressWarnings("unchecked")
    private void callResultHandler(ResultHandler<?> resultHandler, DefaultResultContext<Object> resultContext, Object rowValue) {
        resultContext.nextResultObject(rowValue);
        ((ResultHandler<Object>) resultHandler).handleResult(resultContext);
    }

    private boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) throws SQLException {
        return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
    }

    private void skipRows(ResultSet rs, RowBounds rowBounds) throws SQLException {
        if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
            if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
                rs.absolute(rowBounds.getOffset());
            }
        } else {
            for (int i = 0; i < rowBounds.getOffset(); i++) {
                rs.next();
            }
        }
    }

    // 
    // GET VALUE FROM ROW FOR SIMPLE RESULT MAP
    // 
    private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
        final ResultLoaderMap lazyLoader = new ResultLoaderMap();
        Object rowValue = createResultObject(rsw, resultMap, lazyLoader, null);
        if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
            final MetaObject metaObject = configuration.newMetaObject(rowValue);
            boolean foundValues = this.useConstructorMappings;
            if (shouldApplyAutomaticMappings(resultMap, false)) {
                foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
            }
            foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
            foundValues = lazyLoader.size() > 0 || foundValues;
            rowValue = (foundValues || configuration.isReturnInstanceForEmptyRow()) ? rowValue : null;
        }
        return rowValue;
    }

    private boolean shouldApplyAutomaticMappings(ResultMap resultMap, boolean isNested) {
        if (resultMap.getAutoMapping() != null) {
            return resultMap.getAutoMapping();
        } else {
            if (isNested) {
                return AutoMappingBehavior.FULL == configuration.getAutoMappingBehavior();
            } else {
                return AutoMappingBehavior.NONE != configuration.getAutoMappingBehavior();
            }
        }
    }

    // 
    // PROPERTY MAPPINGS
    // 
    private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
        final List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
        boolean foundValues = false;
        final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
        for (ResultMapping propertyMapping : propertyMappings) {
            String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
            if (propertyMapping.getNestedResultMapId() != null) {
                // the user added a column attribute to a nested result map, ignore it
                column = null;
            }
            if (propertyMapping.isCompositeResult() || (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) || propertyMapping.getResultSet() != null) {
                Object value = getPropertyMappingValue(rsw.getResultSet(), metaObject, propertyMapping, lazyLoader, columnPrefix);
                // issue #541 make property optional
                final String property = propertyMapping.getProperty();
                if (property == null) {
                    continue;
                } else if (value == DEFERED) {
                    foundValues = true;
                    continue;
                }
                if (value != null) {
                    foundValues = true;
                }
                if (value != null || (configuration.isCallSettersOnNulls() && !metaObject.getSetterType(property).isPrimitive())) {
                    // gcode issue #377, call setter on nulls (value is not 'found')
                    metaObject.setValue(property, value);
                }
            }
        }
        return foundValues;
    }

    private Object getPropertyMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
        if (propertyMapping.getNestedQueryId() != null) {
            return getNestedQueryMappingValue(rs, metaResultObject, propertyMapping, lazyLoader, columnPrefix);
        } else if (propertyMapping.getResultSet() != null) {
            // TODO is that OK?
            addPendingChildRelation(rs, metaResultObject, propertyMapping);
            return DEFERED;
        } else {
            final TypeHandler<?> typeHandler = propertyMapping.getTypeHandler();
            final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
            return typeHandler.getResult(rs, column);
        }
    }

    private List<UnMappedColumnAutoMapping> createAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
        final String mapKey = resultMap.getId() + ":" + columnPrefix;
        List<UnMappedColumnAutoMapping> autoMapping = autoMappingsCache.get(mapKey);
        if (autoMapping == null) {
            autoMapping = new ArrayList<UnMappedColumnAutoMapping>();
            final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
            for (String columnName : unmappedColumnNames) {
                String propertyName = columnName;
                if (columnPrefix != null && !columnPrefix.isEmpty()) {
                    // When columnPrefix is specified,
                    // ignore columns without the prefix.
                    if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
                        propertyName = columnName.substring(columnPrefix.length());
                    } else {
                        continue;
                    }
                }
                final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
                if (property != null && metaObject.hreplacedetter(property)) {
                    final Clreplaced<?> propertyType = metaObject.getSetterType(property);
                    if (typeHandlerRegistry.hasTypeHandler(propertyType, rsw.getJdbcType(columnName))) {
                        final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
                        autoMapping.add(new UnMappedColumnAutoMapping(columnName, property, typeHandler, propertyType.isPrimitive()));
                    } else {
                        configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName, property, propertyType);
                    }
                } else {
                    configuration.getAutoMappingUnknownColumnBehavior().doAction(mappedStatement, columnName, (property != null) ? property : propertyName, null);
                }
            }
            autoMappingsCache.put(mapKey, autoMapping);
        }
        return autoMapping;
    }

    private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
        List<UnMappedColumnAutoMapping> autoMapping = createAutomaticMappings(rsw, resultMap, metaObject, columnPrefix);
        boolean foundValues = false;
        if (autoMapping.size() > 0) {
            for (UnMappedColumnAutoMapping mapping : autoMapping) {
                final Object value = mapping.typeHandler.getResult(rsw.getResultSet(), mapping.column);
                if (value != null) {
                    foundValues = true;
                }
                if (value != null || (configuration.isCallSettersOnNulls() && !mapping.primitive)) {
                    // gcode issue #377, call setter on nulls (value is not 'found')
                    metaObject.setValue(mapping.property, value);
                }
            }
        }
        return foundValues;
    }

    // MULTIPLE RESULT SETS
    private void linkToParents(ResultSet rs, ResultMapping parentMapping, Object rowValue) throws SQLException {
        CacheKey parentKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(), parentMapping.getForeignColumn());
        List<PendingRelation> parents = pendingRelations.get(parentKey);
        if (parents != null) {
            for (PendingRelation parent : parents) {
                if (parent != null && rowValue != null) {
                    linkObjects(parent.metaObject, parent.propertyMapping, rowValue);
                }
            }
        }
    }

    private void addPendingChildRelation(ResultSet rs, MetaObject metaResultObject, ResultMapping parentMapping) throws SQLException {
        CacheKey cacheKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(), parentMapping.getColumn());
        PendingRelation deferLoad = new PendingRelation();
        deferLoad.metaObject = metaResultObject;
        deferLoad.propertyMapping = parentMapping;
        List<PendingRelation> relations = pendingRelations.get(cacheKey);
        // issue #255
        if (relations == null) {
            relations = new ArrayList<DefaultResultSetHandler.PendingRelation>();
            pendingRelations.put(cacheKey, relations);
        }
        relations.add(deferLoad);
        ResultMapping previous = nextResultMaps.get(parentMapping.getResultSet());
        if (previous == null) {
            nextResultMaps.put(parentMapping.getResultSet(), parentMapping);
        } else {
            if (!previous.equals(parentMapping)) {
                throw new ExecutorException("Two different properties are mapped to the same resultSet");
            }
        }
    }

    private CacheKey createKeyForMultipleResults(ResultSet rs, ResultMapping resultMapping, String names, String columns) throws SQLException {
        CacheKey cacheKey = new CacheKey();
        cacheKey.update(resultMapping);
        if (columns != null && names != null) {
            String[] columnsArray = columns.split(",");
            String[] namesArray = names.split(",");
            replacedert.isTrue(namesArray.length > 0, "error param");
            for (int i = 0; i < columnsArray.length; i++) {
                Object value = rs.getString(columnsArray[i]);
                if (value != null) {
                    cacheKey.update(namesArray[i]);
                    cacheKey.update(value);
                }
            }
        }
        return cacheKey;
    }

    // 
    // INSTANTIATION & CONSTRUCTOR MAPPING
    // 
    private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
        // reset previous mapping result
        this.useConstructorMappings = false;
        final List<Clreplaced<?>> constructorArgTypes = new ArrayList<Clreplaced<?>>();
        final List<Object> constructorArgs = new ArrayList<Object>();
        Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix);
        if (resultObject != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
            final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
            for (ResultMapping propertyMapping : propertyMappings) {
                // issue gcode #109 && issue #149
                if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) {
                    resultObject = configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs);
                    break;
                }
            }
        }
        // set current mapping result
        this.useConstructorMappings = (resultObject != null && !constructorArgTypes.isEmpty());
        return resultObject;
    }

    private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List<Clreplaced<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) throws SQLException {
        final Clreplaced<?> resultType = resultMap.getType();
        final MetaClreplaced metaType = MetaClreplaced.forClreplaced(resultType, reflectorFactory);
        final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
        if (hasTypeHandlerForResultObject(rsw, resultType)) {
            return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
        } else if (!constructorMappings.isEmpty()) {
            return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs, columnPrefix);
        } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
            return objectFactory.create(resultType);
        } else if (shouldApplyAutomaticMappings(resultMap, false)) {
            return createByConstructorSignature(rsw, resultType, constructorArgTypes, constructorArgs, columnPrefix);
        }
        throw new ExecutorException("Do not know how to create an instance of " + resultType);
    }

    Object createParameterizedResultObject(ResultSetWrapper rsw, Clreplaced<?> resultType, List<ResultMapping> constructorMappings, List<Clreplaced<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) {
        boolean foundValues = false;
        for (ResultMapping constructorMapping : constructorMappings) {
            final Clreplaced<?> parameterType = constructorMapping.getJavaType();
            final String column = constructorMapping.getColumn();
            final Object value;
            try {
                if (constructorMapping.getNestedQueryId() != null) {
                    value = getNestedQueryConstructorValue(rsw.getResultSet(), constructorMapping, columnPrefix);
                } else if (constructorMapping.getNestedResultMapId() != null) {
                    final ResultMap resultMap = configuration.getResultMap(constructorMapping.getNestedResultMapId());
                    value = getRowValue(rsw, resultMap);
                } else {
                    final TypeHandler<?> typeHandler = constructorMapping.getTypeHandler();
                    value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix));
                }
            } catch (ResultMapException e) {
                throw new ExecutorException("Could not process result for mapping: " + constructorMapping, e);
            } catch (SQLException e) {
                throw new ExecutorException("Could not process result for mapping: " + constructorMapping, e);
            }
            constructorArgTypes.add(parameterType);
            constructorArgs.add(value);
            foundValues = value != null || foundValues;
        }
        return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
    }

    private Object createByConstructorSignature(ResultSetWrapper rsw, Clreplaced<?> resultType, List<Clreplaced<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) throws SQLException {
        for (Constructor<?> constructor : resultType.getDeclaredConstructors()) {
            if (typeNames(constructor.getParameterTypes()).equals(rsw.getClreplacedNames())) {
                boolean foundValues = false;
                for (int i = 0; i < constructor.getParameterTypes().length; i++) {
                    Clreplaced<?> parameterType = constructor.getParameterTypes()[i];
                    String columnName = rsw.getColumnNames().get(i);
                    TypeHandler<?> typeHandler = rsw.getTypeHandler(parameterType, columnName);
                    Object value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(columnName, columnPrefix));
                    constructorArgTypes.add(parameterType);
                    constructorArgs.add(value);
                    foundValues = value != null || foundValues;
                }
                return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
            }
        }
        throw new ExecutorException("No constructor found in " + resultType.getName() + " matching " + rsw.getClreplacedNames());
    }

    private List<String> typeNames(Clreplaced<?>[] parameterTypes) {
        List<String> names = new ArrayList<String>();
        for (Clreplaced<?> type : parameterTypes) {
            names.add(type.getName());
        }
        return names;
    }

    private Object createPrimitiveResultObject(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix) throws SQLException {
        final Clreplaced<?> resultType = resultMap.getType();
        final String columnName;
        if (!resultMap.getResultMappings().isEmpty()) {
            final List<ResultMapping> resultMappingList = resultMap.getResultMappings();
            final ResultMapping mapping = resultMappingList.get(0);
            columnName = prependPrefix(mapping.getColumn(), columnPrefix);
        } else {
            columnName = rsw.getColumnNames().get(0);
        }
        final TypeHandler<?> typeHandler = rsw.getTypeHandler(resultType, columnName);
        return typeHandler.getResult(rsw.getResultSet(), columnName);
    }

    // 
    // NESTED QUERY
    // 
    private Object getNestedQueryConstructorValue(ResultSet rs, ResultMapping constructorMapping, String columnPrefix) throws SQLException {
        final String nestedQueryId = constructorMapping.getNestedQueryId();
        final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
        final Clreplaced<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
        final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, constructorMapping, nestedQueryParameterType, columnPrefix);
        Object value = null;
        if (nestedQueryParameterObject != null) {
            final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
            final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT, nestedBoundSql);
            final Clreplaced<?> targetType = constructorMapping.getJavaType();
            final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery, nestedQueryParameterObject, targetType, key, nestedBoundSql);
            value = resultLoader.loadResult();
        }
        return value;
    }

    private Object getNestedQueryMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
        final String nestedQueryId = propertyMapping.getNestedQueryId();
        final String property = propertyMapping.getProperty();
        final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
        final Clreplaced<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
        final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, propertyMapping, nestedQueryParameterType, columnPrefix);
        Object value = null;
        if (nestedQueryParameterObject != null) {
            final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
            final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT, nestedBoundSql);
            final Clreplaced<?> targetType = propertyMapping.getJavaType();
            if (executor.isCached(nestedQuery, key)) {
                executor.deferLoad(nestedQuery, metaResultObject, property, key, targetType);
                value = DEFERED;
            } else {
                final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery, nestedQueryParameterObject, targetType, key, nestedBoundSql);
                if (propertyMapping.isLazy()) {
                    lazyLoader.addLoader(property, metaResultObject, resultLoader);
                    value = DEFERED;
                } else {
                    value = resultLoader.loadResult();
                }
            }
        }
        return value;
    }

    private Object prepareParameterForNestedQuery(ResultSet rs, ResultMapping resultMapping, Clreplaced<?> parameterType, String columnPrefix) throws SQLException {
        if (resultMapping.isCompositeResult()) {
            return prepareCompositeKeyParameter(rs, resultMapping, parameterType, columnPrefix);
        } else {
            return prepareSimpleKeyParameter(rs, resultMapping, parameterType, columnPrefix);
        }
    }

    private Object prepareSimpleKeyParameter(ResultSet rs, ResultMapping resultMapping, Clreplaced<?> parameterType, String columnPrefix) throws SQLException {
        final TypeHandler<?> typeHandler;
        if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
            typeHandler = typeHandlerRegistry.getTypeHandler(parameterType);
        } else {
            typeHandler = typeHandlerRegistry.getUnknownTypeHandler();
        }
        return typeHandler.getResult(rs, prependPrefix(resultMapping.getColumn(), columnPrefix));
    }

    private Object prepareCompositeKeyParameter(ResultSet rs, ResultMapping resultMapping, Clreplaced<?> parameterType, String columnPrefix) throws SQLException {
        final Object parameterObject = instantiateParameterObject(parameterType);
        final MetaObject metaObject = configuration.newMetaObject(parameterObject);
        boolean foundValues = false;
        for (ResultMapping innerResultMapping : resultMapping.getComposites()) {
            final Clreplaced<?> propType = metaObject.getSetterType(innerResultMapping.getProperty());
            final TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(propType);
            final Object propValue = typeHandler.getResult(rs, prependPrefix(innerResultMapping.getColumn(), columnPrefix));
            // issue #353 & #560 do not execute nested query if key is null
            if (propValue != null) {
                metaObject.setValue(innerResultMapping.getProperty(), propValue);
                foundValues = true;
            }
        }
        return foundValues ? parameterObject : null;
    }

    private Object instantiateParameterObject(Clreplaced<?> parameterType) {
        if (parameterType == null) {
            return new HashMap<Object, Object>();
        } else if (ParamMap.clreplaced.equals(parameterType)) {
            // issue #649
            return new HashMap<Object, Object>();
        } else {
            return objectFactory.create(parameterType);
        }
    }

    // 
    // DISCRIMINATOR
    // 
    public ResultMap resolveDiscriminatedResultMap(ResultSet rs, ResultMap resultMap, String columnPrefix) throws SQLException {
        Set<String> pastDiscriminators = new HashSet<String>();
        Discriminator discriminator = resultMap.getDiscriminator();
        while (discriminator != null) {
            final Object value = getDiscriminatorValue(rs, discriminator, columnPrefix);
            final String discriminatedMapId = discriminator.getMapIdFor(String.valueOf(value));
            if (configuration.hasResultMap(discriminatedMapId)) {
                resultMap = configuration.getResultMap(discriminatedMapId);
                Discriminator lastDiscriminator = discriminator;
                discriminator = resultMap.getDiscriminator();
                if (discriminator == lastDiscriminator || !pastDiscriminators.add(discriminatedMapId)) {
                    break;
                }
            } else {
                break;
            }
        }
        return resultMap;
    }

    private Object getDiscriminatorValue(ResultSet rs, Discriminator discriminator, String columnPrefix) throws SQLException {
        final ResultMapping resultMapping = discriminator.getResultMapping();
        final TypeHandler<?> typeHandler = resultMapping.getTypeHandler();
        return typeHandler.getResult(rs, prependPrefix(resultMapping.getColumn(), columnPrefix));
    }

    private String prependPrefix(String columnName, String prefix) {
        if (columnName == null || columnName.length() == 0 || prefix == null || prefix.length() == 0) {
            return columnName;
        }
        return prefix + columnName;
    }

    // 
    // HANDLE NESTED RESULT MAPS
    // 
    private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
        final DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
        skipRows(rsw.getResultSet(), rowBounds);
        Object rowValue = previousRowValue;
        while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
            final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
            final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
            Object partialObject = nestedResultObjects.get(rowKey);
            // issue #577 && #542
            if (mappedStatement.isResultOrdered()) {
                if (partialObject == null && rowValue != null) {
                    nestedResultObjects.clear();
                    storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
                }
                rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
            } else {
                rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, null, partialObject);
                if (partialObject == null) {
                    storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
                }
            }
        }
        if (rowValue != null && mappedStatement.isResultOrdered() && shouldProcessMoreRows(resultContext, rowBounds)) {
            storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
            previousRowValue = null;
        } else if (rowValue != null) {
            previousRowValue = rowValue;
        }
    }

    // 
    // GET VALUE FROM ROW FOR NESTED RESULT MAP
    // 
    private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap, CacheKey combinedKey, String columnPrefix, Object partialObject) throws SQLException {
        final String resultMapId = resultMap.getId();
        Object rowValue = partialObject;
        if (rowValue != null) {
            final MetaObject metaObject = configuration.newMetaObject(rowValue);
            putAncestor(rowValue, resultMapId, columnPrefix);
            applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, false);
            ancestorObjects.remove(resultMapId);
        } else {
            final ResultLoaderMap lazyLoader = new ResultLoaderMap();
            rowValue = createResultObject(rsw, resultMap, lazyLoader, columnPrefix);
            if (rowValue != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
                final MetaObject metaObject = configuration.newMetaObject(rowValue);
                boolean foundValues = this.useConstructorMappings;
                if (shouldApplyAutomaticMappings(resultMap, true)) {
                    foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, columnPrefix) || foundValues;
                }
                foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, columnPrefix) || foundValues;
                putAncestor(rowValue, resultMapId, columnPrefix);
                foundValues = applyNestedResultMappings(rsw, resultMap, metaObject, columnPrefix, combinedKey, true) || foundValues;
                ancestorObjects.remove(resultMapId);
                foundValues = lazyLoader.size() > 0 || foundValues;
                rowValue = (foundValues || configuration.isReturnInstanceForEmptyRow()) ? rowValue : null;
            }
            if (combinedKey != CacheKey.NULL_CACHE_KEY) {
                nestedResultObjects.put(combinedKey, rowValue);
            }
        }
        return rowValue;
    }

    private void putAncestor(Object resultObject, String resultMapId, String columnPrefix) {
        ancestorObjects.put(resultMapId, resultObject);
    }

    // 
    // NESTED RESULT MAP (JOIN MAPPING)
    // 
    private boolean applyNestedResultMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String parentPrefix, CacheKey parentRowKey, boolean newObject) {
        boolean foundValues = false;
        for (ResultMapping resultMapping : resultMap.getPropertyResultMappings()) {
            final String nestedResultMapId = resultMapping.getNestedResultMapId();
            if (nestedResultMapId != null && resultMapping.getResultSet() == null) {
                try {
                    final String columnPrefix = getColumnPrefix(parentPrefix, resultMapping);
                    final ResultMap nestedResultMap = getNestedResultMap(rsw.getResultSet(), nestedResultMapId, columnPrefix);
                    if (resultMapping.getColumnPrefix() == null) {
                        // try to fill circular reference only when columnPrefix
                        // is not specified for the nested result map (issue #215)
                        Object ancestorObject = ancestorObjects.get(nestedResultMapId);
                        if (ancestorObject != null) {
                            if (newObject) {
                                // issue #385
                                linkObjects(metaObject, resultMapping, ancestorObject);
                            }
                            continue;
                        }
                    }
                    final CacheKey rowKey = createRowKey(nestedResultMap, rsw, columnPrefix);
                    final CacheKey combinedKey = combineKeys(rowKey, parentRowKey);
                    Object rowValue = nestedResultObjects.get(combinedKey);
                    boolean knownValue = (rowValue != null);
                    // mandatory
                    instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
                    if (anyNotNullColumnHasValue(resultMapping, columnPrefix, rsw)) {
                        rowValue = getRowValue(rsw, nestedResultMap, combinedKey, columnPrefix, rowValue);
                        if (rowValue != null && !knownValue) {
                            linkObjects(metaObject, resultMapping, rowValue);
                            foundValues = true;
                        }
                    }
                } catch (SQLException e) {
                    throw new ExecutorException("Error getting nested result map values for '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
                }
            }
        }
        return foundValues;
    }

    private String getColumnPrefix(String parentPrefix, ResultMapping resultMapping) {
        final StringBuilder columnPrefixBuilder = new StringBuilder();
        if (parentPrefix != null) {
            columnPrefixBuilder.append(parentPrefix);
        }
        if (resultMapping.getColumnPrefix() != null) {
            columnPrefixBuilder.append(resultMapping.getColumnPrefix());
        }
        return columnPrefixBuilder.length() == 0 ? null : columnPrefixBuilder.toString().toUpperCase(Locale.ENGLISH);
    }

    private boolean anyNotNullColumnHasValue(ResultMapping resultMapping, String columnPrefix, ResultSetWrapper rsw) throws SQLException {
        Set<String> notNullColumns = resultMapping.getNotNullColumns();
        if (notNullColumns != null && !notNullColumns.isEmpty()) {
            ResultSet rs = rsw.getResultSet();
            for (String column : notNullColumns) {
                rs.getObject(prependPrefix(column, columnPrefix));
                if (!rs.wasNull()) {
                    return true;
                }
            }
            return false;
        } else if (columnPrefix != null) {
            for (String columnName : rsw.getColumnNames()) {
                if (columnName.toUpperCase().startsWith(columnPrefix.toUpperCase())) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    private ResultMap getNestedResultMap(ResultSet rs, String nestedResultMapId, String columnPrefix) throws SQLException {
        ResultMap nestedResultMap = configuration.getResultMap(nestedResultMapId);
        return resolveDiscriminatedResultMap(rs, nestedResultMap, columnPrefix);
    }

    // 
    // UNIQUE RESULT KEY
    // 
    private CacheKey createRowKey(ResultMap resultMap, ResultSetWrapper rsw, String columnPrefix) throws SQLException {
        final CacheKey cacheKey = new CacheKey();
        cacheKey.update(resultMap.getId());
        List<ResultMapping> resultMappings = getResultMappingsForRowKey(resultMap);
        if (resultMappings.size() == 0) {
            if (Map.clreplaced.isreplacedignableFrom(resultMap.getType())) {
                createRowKeyForMap(rsw, cacheKey);
            } else {
                createRowKeyForUnmappedProperties(resultMap, rsw, cacheKey, columnPrefix);
            }
        } else {
            createRowKeyForMappedProperties(resultMap, rsw, cacheKey, resultMappings, columnPrefix);
        }
        if (cacheKey.getUpdateCount() < 2) {
            return CacheKey.NULL_CACHE_KEY;
        }
        return cacheKey;
    }

    private CacheKey combineKeys(CacheKey rowKey, CacheKey parentRowKey) {
        if (rowKey.getUpdateCount() > 1 && parentRowKey.getUpdateCount() > 1) {
            CacheKey combinedKey;
            try {
                combinedKey = rowKey.clone();
            } catch (CloneNotSupportedException e) {
                throw new ExecutorException("Error cloning cache key.  Cause: " + e, e);
            }
            combinedKey.update(parentRowKey);
            return combinedKey;
        }
        return CacheKey.NULL_CACHE_KEY;
    }

    private List<ResultMapping> getResultMappingsForRowKey(ResultMap resultMap) {
        List<ResultMapping> resultMappings = resultMap.getIdResultMappings();
        if (resultMappings.size() == 0) {
            resultMappings = resultMap.getPropertyResultMappings();
        }
        return resultMappings;
    }

    private void createRowKeyForMappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, List<ResultMapping> resultMappings, String columnPrefix) throws SQLException {
        for (ResultMapping resultMapping : resultMappings) {
            if (resultMapping.getNestedResultMapId() != null && resultMapping.getResultSet() == null) {
                // Issue #392
                final ResultMap nestedResultMap = configuration.getResultMap(resultMapping.getNestedResultMapId());
                createRowKeyForMappedProperties(nestedResultMap, rsw, cacheKey, nestedResultMap.getConstructorResultMappings(), prependPrefix(resultMapping.getColumnPrefix(), columnPrefix));
            } else if (resultMapping.getNestedQueryId() == null) {
                final String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
                final TypeHandler<?> th = resultMapping.getTypeHandler();
                List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
                // Issue #114
                if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) {
                    final Object value = th.getResult(rsw.getResultSet(), column);
                    if (value != null || configuration.isReturnInstanceForEmptyRow()) {
                        cacheKey.update(column);
                        cacheKey.update(value);
                    }
                }
            }
        }
    }

    private void createRowKeyForUnmappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, String columnPrefix) throws SQLException {
        final MetaClreplaced metaType = MetaClreplaced.forClreplaced(resultMap.getType(), reflectorFactory);
        List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
        for (String column : unmappedColumnNames) {
            String property = column;
            if (columnPrefix != null && !columnPrefix.isEmpty()) {
                // When columnPrefix is specified, ignore columns without the prefix.
                if (column.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
                    property = column.substring(columnPrefix.length());
                } else {
                    continue;
                }
            }
            if (metaType.findProperty(property, configuration.isMapUnderscoreToCamelCase()) != null) {
                String value = rsw.getResultSet().getString(column);
                if (value != null) {
                    cacheKey.update(column);
                    cacheKey.update(value);
                }
            }
        }
    }

    private void createRowKeyForMap(ResultSetWrapper rsw, CacheKey cacheKey) throws SQLException {
        List<String> columnNames = rsw.getColumnNames();
        for (String columnName : columnNames) {
            final String value = rsw.getResultSet().getString(columnName);
            if (value != null) {
                cacheKey.update(columnName);
                cacheKey.update(value);
            }
        }
    }

    private void linkObjects(MetaObject metaObject, ResultMapping resultMapping, Object rowValue) {
        final Object collectionProperty = instantiateCollectionPropertyIfAppropriate(resultMapping, metaObject);
        if (collectionProperty != null) {
            final MetaObject targetMetaObject = configuration.newMetaObject(collectionProperty);
            targetMetaObject.add(rowValue);
        } else {
            metaObject.setValue(resultMapping.getProperty(), rowValue);
        }
    }

    private Object instantiateCollectionPropertyIfAppropriate(ResultMapping resultMapping, MetaObject metaObject) {
        final String propertyName = resultMapping.getProperty();
        Object propertyValue = metaObject.getValue(propertyName);
        if (propertyValue == null) {
            Clreplaced<?> type = resultMapping.getJavaType();
            if (type == null) {
                type = metaObject.getSetterType(propertyName);
            }
            try {
                if (objectFactory.isCollection(type)) {
                    propertyValue = objectFactory.create(type);
                    metaObject.setValue(propertyName, propertyValue);
                    return propertyValue;
                }
            } catch (Exception e) {
                throw new ExecutorException("Error instantiating collection property for result '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
            }
        } else if (objectFactory.isCollection(propertyValue.getClreplaced())) {
            return propertyValue;
        }
        return null;
    }

    private boolean hasTypeHandlerForResultObject(ResultSetWrapper rsw, Clreplaced<?> resultType) {
        if (rsw.getColumnNames().size() == 1) {
            return typeHandlerRegistry.hasTypeHandler(resultType, rsw.getJdbcType(rsw.getColumnNames().get(0)));
        }
        return typeHandlerRegistry.hasTypeHandler(resultType);
    }
}

18 Source : SelectKeyGenerator.java
with Apache License 2.0
from open-hand

private void processGeneratedKeys(Executor executor, MappedStatement ms, Object parameter) {
    try {
        if (parameter != null && keyStatement != null && keyStatement.getKeyProperties() != null) {
            String[] keyProperties = keyStatement.getKeyProperties();
            final Configuration configuration = ms.getConfiguration();
            final MetaObject metaParam = configuration.newMetaObject(parameter);
            if (existsKeyValues(metaParam, keyProperties, parameter)) {
                return;
            }
            if (keyProperties != null) {
                // Do not close keyExecutor.
                // The transaction will be closed by parent executor.
                Executor keyExecutor = configuration.newExecutor(executor.getTransaction(), ExecutorType.SIMPLE);
                List<Object> values = keyExecutor.query(keyStatement, parameter, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
                if (values.size() == 0) {
                    throw new ExecutorException("SelectKey returned no data.");
                } else if (values.size() > 1) {
                    throw new ExecutorException("SelectKey returned more than one value.");
                } else {
                    MetaObject metaResult = configuration.newMetaObject(values.get(0));
                    if (keyProperties.length == 1) {
                        if (metaResult.hasGetter(keyProperties[0])) {
                            setValue(metaParam, keyProperties[0], metaResult.getValue(keyProperties[0]));
                        } else {
                            // no getter for the property - maybe just a single value object
                            // so try that
                            setValue(metaParam, keyProperties[0], values.get(0));
                        }
                    } else {
                        handleMultipleProperties(keyProperties, metaParam, metaResult);
                    }
                }
            }
        }
    } catch (ExecutorException e) {
        throw e;
    } catch (Exception e) {
        throw new ExecutorException("Error selecting key or setting result to parameter object. Cause: " + e, e);
    }
}

18 Source : SnowflakeIdKeyGenerator.java
with Apache License 2.0
from lightbatis

private void processGeneratedKeys(Executor executor, MappedStatement ms, Object parameter) {
    try {
        if (parameter != null && ms.getKeyProperties() != null) {
            // keyStatement.getKeyProperties();
            String[] keyProperties = ms.getKeyProperties();
            final Configuration configuration = ms.getConfiguration();
            final MetaObject metaParam = configuration.newMetaObject(parameter);
            if (keyProperties != null) {
                if (keyProperties.length == 1) {
                    Long nextId = ITableSchemaManager.getInstance().nextId();
                    setValue(metaParam, keyProperties[0], nextId);
                } else {
                    int size = keyProperties.length;
                    Long[] nextIds = ITableSchemaManager.getInstance().nextIds(size);
                    for (int i = 0; i < size; i++) {
                        setValue(metaParam, keyProperties[i], nextIds[i]);
                    }
                // handleMultipleProperties(keyProperties, metaParam, metaResult);
                }
            }
        }
    } catch (ExecutorException e) {
        throw e;
    } catch (Exception e) {
        throw new ExecutorException("Error selecting key or setting result to parameter object. Cause: " + e, e);
    }
}

18 Source : DefaultCursorTest.java
with Apache License 2.0
from huifer

@SuppressWarnings("unchecked")
@Test
void shouldCloseImmediatelyIfResultSetIsClosed() throws Exception {
    final MappedStatement ms = getNestedAndOrderedMappedStatement();
    final ResultMap rm = ms.getResultMaps().get(0);
    final Executor executor = null;
    final ParameterHandler parameterHandler = null;
    final ResultHandler<?> resultHandler = null;
    final BoundSql boundSql = null;
    final RowBounds rowBounds = RowBounds.DEFAULT;
    final DefaultResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, ms, parameterHandler, resultHandler, boundSql, rowBounds);
    when(rsmd.getColumnCount()).thenReturn(2);
    doReturn("id").when(rsmd).getColumnLabel(1);
    doReturn(Types.INTEGER).when(rsmd).getColumnType(1);
    doReturn(Integer.clreplaced.getCanonicalName()).when(rsmd).getColumnClreplacedName(1);
    doReturn("role").when(rsmd).getColumnLabel(2);
    doReturn(Types.VARCHAR).when(rsmd).getColumnType(2);
    doReturn(String.clreplaced.getCanonicalName()).when(rsmd).getColumnClreplacedName(2);
    final ResultSetWrapper rsw = new ResultSetWrapper(rs, ms.getConfiguration());
    try (DefaultCursor<?> cursor = new DefaultCursor<>(resultSetHandler, rm, rsw, RowBounds.DEFAULT)) {
        Iterator<?> iter = cursor.iterator();
        replacedertTrue(iter.hasNext());
        Map<String, Object> map = (Map<String, Object>) iter.next();
        replacedertEquals(1, map.get("id"));
        replacedertEquals("CEO", ((Map<String, Object>) map.get("roles")).get("role"));
        replacedertFalse(cursor.isConsumed());
        replacedertTrue(cursor.isOpen());
        replacedertFalse(iter.hasNext());
        replacedertTrue(cursor.isConsumed());
        replacedertFalse(cursor.isOpen());
    }
}

18 Source : DefaultSqlSessionFactory.java
with Apache License 2.0
from huifer

/**
 * <setting name="defaultExecutorType" value="SIMPLE"/>
 *
 * @param execType   setting 标签的 defaultExecutorType 属性
 * @param level      事物级别
 * @param autoCommit
 * @return
 */
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
        final Environment environment = configuration.getEnvironment();
        // <transactionManager type="JDBC"/>
        // org.apache.ibatis.transaction.jdbc.JdbcTransaction
        final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
        tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
        final Executor executor = configuration.newExecutor(tx, execType);
        return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
        // may have fetched a connection so lets call close()
        closeTransaction(tx);
        throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
        ErrorContext.instance().reset();
    }
}

18 Source : SelectKeyGenerator.java
with Apache License 2.0
from huifer

private void processGeneratedKeys(Executor executor, MappedStatement ms, Object parameter) {
    try {
        if (parameter != null && keyStatement != null && keyStatement.getKeyProperties() != null) {
            String[] keyProperties = keyStatement.getKeyProperties();
            final Configuration configuration = ms.getConfiguration();
            final MetaObject metaParam = configuration.newMetaObject(parameter);
            // Do not close keyExecutor.
            // The transaction will be closed by parent executor.
            Executor keyExecutor = configuration.newExecutor(executor.getTransaction(), ExecutorType.SIMPLE);
            List<Object> values = keyExecutor.query(keyStatement, parameter, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
            if (values.size() == 0) {
                throw new ExecutorException("SelectKey returned no data.");
            } else if (values.size() > 1) {
                throw new ExecutorException("SelectKey returned more than one value.");
            } else {
                MetaObject metaResult = configuration.newMetaObject(values.get(0));
                if (keyProperties.length == 1) {
                    if (metaResult.hasGetter(keyProperties[0])) {
                        setValue(metaParam, keyProperties[0], metaResult.getValue(keyProperties[0]));
                    } else {
                        // no getter for the property - maybe just a single value object
                        // so try that
                        setValue(metaParam, keyProperties[0], values.get(0));
                    }
                } else {
                    handleMultipleProperties(keyProperties, metaParam, metaResult);
                }
            }
        }
    } catch (ExecutorException e) {
        throw e;
    } catch (Exception e) {
        throw new ExecutorException("Error selecting key or setting result to parameter object. Cause: " + e, e);
    }
}

18 Source : MyBatisExecutePageableInterceptor.java
with Apache License 2.0
from hengboy

/**
 * 拦截器方法
 *
 * @param invocation 拦截器拦截方法封装对象
 * @return 拦截的目标方法执行后的返回值
 * @throws Throwable 执行异常
 */
public Object intercept(Invocation invocation) throws Throwable {
    // 默认行绑定不执行分页
    if (PageableRequestHelper.getPageLocal() == null) {
        return invocation.proceed();
    }
    // 获取Executor对象query方法的参数列表
    final Object[] args = invocation.getArgs();
    // MappedStatement对象实例
    MappedStatement statement = (MappedStatement) args[0];
    // 本次拦截的执行器对象
    Executor executor = (Executor) invocation.getTarget();
    // 获取threadLocal内保存的分页响应对象
    DefaultPage pageable = (DefaultPage) PageableRequestHelper.getPageLocal();
    /*
         * 缓存对象优先
         * 如果每次生成存在性能瓶颈
         * 数据库方言
         * 根据不同的数据库方言生成分页sql、查询总数量sql、参数映射、参数重装等操作
         */
    if (dialectCache == null) {
        dialectCache = DialectDynamicFactory.newInstance(statement, this.dialect);
    }
    // 构建请求对象
    ExecutorQueryRequest queryRequest = buildExecutorQueryRequest(args);
    // 执行分页查询 & 设置到分页响应对象
    pageable.setData(executeQuery(executor, queryRequest, pageable, dialectCache));
    // 查询总数量 & 设置到分页响应对象
    pageable.setTotalElements(executeCount(executor, queryRequest, dialectCache));
    // 分页查询后的列表数据
    return pageable.getData();
}

18 Source : QueryInterceptor.java
with GNU Lesser General Public License v3.0
from fangjinuo

@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    Object parameter = args[1];
    RowBounds rowBounds = (RowBounds) args[2];
    ResultHandler resultHandler = (ResultHandler) args[3];
    Executor executor = (Executor) invocation.getTarget();
    CacheKey cacheKey;
    BoundSql boundSql;
    // 由于逻辑关系,只会进入一次
    if (args.length == 4) {
        // 4 个参数时
        boundSql = ms.getBoundSql(parameter);
        cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
    } else {
        // 6 个参数时
        cacheKey = (CacheKey) args[4];
        boundSql = (BoundSql) args[5];
    }
    // 自己要进行的各种处理
    // 注:下面的方法可以根据自己的逻辑调用多次,在分页插件中,count 和 page 各调用了一次
    return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}

18 Source : MybatisUtils.java
with GNU Lesser General Public License v3.0
from fangjinuo

public static String getDatabaseId(@Nullable SqlRequestContextHolder sqlRequestContextHolder, @Nullable SQLStatementInstrumentor instrumentor, @NonNull final MappedStatement ms, @Nullable Executor executor, boolean enableExtractDialectUseNative) {
    String databaseId = null;
    // 从 sql request 中获取
    if (sqlRequestContextHolder != null) {
        SqlRequestContext sqlRequestContext = sqlRequestContextHolder.get();
        if (sqlRequestContext != null) {
            SqlRequest request = sqlRequestContext.getRequest();
            if (request != null) {
                databaseId = request.getDialect();
            }
        }
    }
    // 从 mapped statement 中获取
    if (Emptys.isEmpty(databaseId)) {
        databaseId = ms.getDatabaseId();
    }
    // 从 全局配置 中获取
    if (Emptys.isEmpty(databaseId) && instrumentor != null && instrumentor.getConfig() != null) {
        databaseId = instrumentor.getConfig().getDialect();
    }
    // 从 MyBatis Configuration 中获取
    if (Emptys.isEmpty(databaseId) && enableExtractDialectUseNative) {
        databaseId = 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) {
            logger.error(ex.getMessage(), ex);
        }
    }
    return databaseId;
}

18 Source : QueryInterceptor.java
with MIT License
from aoju

@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    Object parameter = args[1];
    RowBounds rowBounds = (RowBounds) args[2];
    ResultHandler resultHandler = (ResultHandler) args[3];
    Executor executor = (Executor) invocation.getTarget();
    CacheKey cacheKey;
    BoundSql boundSql;
    // 由于逻辑关系,只会进入一次
    if (args.length == 4) {
        // 4 个参数时
        boundSql = ms.getBoundSql(parameter);
        cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
    } else {
        // 6 个参数时
        cacheKey = (CacheKey) args[4];
        boundSql = (BoundSql) args[5];
    }
    // 注:下面的方法可以根据自己的逻辑调用多次,在分页插件中,count 和 proxy 各调用了一次
    return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}

18 Source : OrderByHelper.java
with MIT License
from abel533

@Override
public Object intercept(Invocation invocation) throws Throwable {
    String orderBy = ORDERBY_LOCAL.get();
    if (orderBy != null && orderBy.length() > 0) {
        ORDERBY_LOCAL.remove();
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        // 由于逻辑关系,只会进入一次
        if (args.length == 4) {
            // 4 个参数时
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        } else {
            // 6 个参数时
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        String sql = boundSql.getSql();
        String orderBySql = OrderByParser.converToOrderBySql(sql, orderBy);
        // 更新cacheKey,防止缓存错误#3
        cacheKey.update(orderBy);
        BoundSql orderbyBoundSql = new BoundSql(ms.getConfiguration(), orderBySql, boundSql.getParameterMappings(), parameter);
        Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
        for (String key : additionalParameters.keySet()) {
            orderbyBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
        }
        return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, orderbyBoundSql);
    } else {
        return invocation.proceed();
    }
}

17 Source : TriggerValue4SelectKeyGenerator.java
with Apache License 2.0
from zhouxx

@Override
public void processBefore(Executor executor, MappedStatement mappedStatement, Statement stmt, Object parameterObject) {
    if (!(mappedStatement.getSqlCommandType() == SqlCommandType.INSERT || mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE)) {
        return;
    }
    Collection<Object> parameters = parameterreplacedistant.getParameters(parameterObject);
    // trigger auto set value
    if (parameters != null) {
        for (Object parameter : parameters) {
            EnreplacedyMetaData enreplacedyMetaData = EnreplacedyMetaDataRegistry.getInstance().get(parameter.getClreplaced());
            parameterreplacedistant.populateKeyAndTriggerValue(mappedStatement, parameter, enreplacedyMetaData);
        }
    } else {
        EnreplacedyMetaData enreplacedyMetaData = EnreplacedyMetaDataRegistry.getInstance().get(parameterObject.getClreplaced());
        parameterreplacedistant.populateKeyAndTriggerValue(mappedStatement, parameterObject, enreplacedyMetaData);
    }
    // id select and set
    if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT) {
        if (executeBefore) {
            if (parameters != null) {
                for (Object parameter : parameters) {
                    processGeneratedKeys(executor, mappedStatement, parameter);
                }
            } else {
                processGeneratedKeys(executor, mappedStatement, parameterObject);
            }
        }
    }
}

See More Examples