Example usage for org.apache.ibatis.mapping SqlCommandType SELECT

List of usage examples for org.apache.ibatis.mapping SqlCommandType SELECT

Introduction

In this page you can find the example usage for org.apache.ibatis.mapping SqlCommandType SELECT.

Prototype

SqlCommandType SELECT

To view the source code for org.apache.ibatis.mapping SqlCommandType SELECT.

Click Source Link

Usage

From source file:cn.org.awcp.core.mybatis.mapper.MapperTemplate.java

License:Open Source License

/**
 * SelectKey - ?mysqlOracle?/*from  w  ww  .j av a 2s. co m*/
 * 
 * @param ms
 * @param column
 */
protected void newSelectKeyMappedStatement(MappedStatement ms, EntityHelper.EntityColumn column) {
    String keyId = ms.getId() + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    if (ms.getConfiguration().hasKeyGenerator(keyId)) {
        return;
    }
    Class<?> entityClass = getSelectReturnType(ms);
    // defaults
    Configuration configuration = ms.getConfiguration();
    KeyGenerator keyGenerator = null;
    Boolean executeBefore = getBEFORE();
    String IDENTITY = (column.getGenerator() == null || column.getGenerator().equals("")) ? getIDENTITY()
            : column.getGenerator();
    if (IDENTITY.equalsIgnoreCase("JDBC")) {
        keyGenerator = new Jdbc3KeyGenerator();
    } else {
        SqlSource sqlSource = new RawSqlSource(configuration, IDENTITY, entityClass);

        MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, keyId, sqlSource,
                SqlCommandType.SELECT);
        statementBuilder.resource(ms.getResource());
        statementBuilder.fetchSize(null);
        statementBuilder.statementType(StatementType.STATEMENT);
        statementBuilder.keyGenerator(new NoKeyGenerator());
        statementBuilder.keyProperty(column.getProperty());
        statementBuilder.keyColumn(null);
        statementBuilder.databaseId(null);
        statementBuilder.lang(configuration.getDefaultScriptingLanuageInstance());
        statementBuilder.resultOrdered(false);
        statementBuilder.resulSets(null);
        statementBuilder.timeout(configuration.getDefaultStatementTimeout());

        List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
        ParameterMap.Builder inlineParameterMapBuilder = new ParameterMap.Builder(configuration,
                statementBuilder.id() + "-Inline", entityClass, parameterMappings);
        statementBuilder.parameterMap(inlineParameterMapBuilder.build());

        List<ResultMap> resultMaps = new ArrayList<ResultMap>();
        ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder(configuration,
                statementBuilder.id() + "-Inline", column.getJavaType(), new ArrayList<ResultMapping>(), null);
        resultMaps.add(inlineResultMapBuilder.build());
        statementBuilder.resultMaps(resultMaps);
        statementBuilder.resultSetType(null);

        statementBuilder.flushCacheRequired(false);
        statementBuilder.useCache(false);
        statementBuilder.cache(null);

        MappedStatement statement = statementBuilder.build();
        configuration.addMappedStatement(statement);

        MappedStatement keyStatement = configuration.getMappedStatement(keyId, false);
        keyGenerator = new SelectKeyGenerator(keyStatement, executeBefore);
        configuration.addKeyGenerator(keyId, keyGenerator);
    }
    // keyGenerator
    try {
        MetaObject msObject = forObject(ms);
        msObject.setValue("keyGenerator", keyGenerator);
        msObject.setValue("keyProperties", new String[] { column.getProperty() });
    } catch (Exception e) {
        // ignore
    }
}

From source file:com.baomidou.mybatisplus.mapper.AutoSqlInjector.java

License:Apache License

public MappedStatement addSelectMappedStatement(Class<?> mapperClass, String id, SqlSource sqlSource,
        Class<?> resultType, TableInfo table) {
    if (null != table) {
        String resultMap = table.getResultMap();
        if (null != resultMap) {
            /*  resultMap  */
            return this.addMappedStatement(mapperClass, id, sqlSource, SqlCommandType.SELECT, null, resultMap,
                    null, new NoKeyGenerator(), null, null);
        }/*w  w  w .j  av  a  2s  .c o m*/
    }

    /*  */
    return this.addMappedStatement(mapperClass, id, sqlSource, SqlCommandType.SELECT, null, null, resultType,
            new NoKeyGenerator(), null, null);
}

From source file:com.baomidou.mybatisplus.mapper.AutoSqlInjector.java

License:Apache License

public MappedStatement addMappedStatement(Class<?> mapperClass, String id, SqlSource sqlSource,
        SqlCommandType sqlCommandType, Class<?> parameterClass, String resultMap, Class<?> resultType,
        KeyGenerator keyGenerator, String keyProperty, String keyColumn) {
    String statementName = mapperClass.getName() + "." + id;
    if (configuration.hasStatement(statementName)) {
        System.err.println("{" + statementName
                + "} Has been loaded by XML or SqlProvider, ignoring the injection of the SQL.");
        return null;
    }//from ww w  .j  av a  2s  . c  o  m
    /* ? */
    boolean isSelect = false;
    if (sqlCommandType == SqlCommandType.SELECT) {
        isSelect = true;
    }
    return builderAssistant.addMappedStatement(id, sqlSource, StatementType.PREPARED, sqlCommandType, null,
            null, null, parameterClass, resultMap, resultType, null, !isSelect, isSelect, false, keyGenerator,
            keyProperty, keyColumn, configuration.getDatabaseId(), languageDriver, null);
}

From source file:com.baomidou.mybatisplus.mapper.AutoSqlInjector.java

License:Apache License

/**
 * MappedStatement/*from  w  ww .  j ava 2s .c  om*/
 *
 * @param mappedStatement
 * @param sqlSource       sqlSource
 * @param resultType      
 */
@SuppressWarnings("serial")
private void createSelectMappedStatement(String mappedStatement, SqlSource sqlSource,
        final Class<?> resultType) {
    MappedStatement ms = new MappedStatement.Builder(configuration, mappedStatement, sqlSource,
            SqlCommandType.SELECT).resultMaps(new ArrayList<ResultMap>() {
                {
                    add(new ResultMap.Builder(configuration, "defaultResultMap", resultType,
                            new ArrayList<ResultMapping>(0)).build());
                }
            }).build();
    // 
    configuration.addMappedStatement(ms);
}

From source file:com.baomidou.mybatisplus.MybatisMapperAnnotationBuilder.java

License:Apache License

void parseStatement(Method method) {
    Class<?> parameterTypeClass = getParameterType(method);
    LanguageDriver languageDriver = getLanguageDriver(method);
    SqlSource sqlSource = getSqlSourceFromAnnotations(method, parameterTypeClass, languageDriver);
    if (sqlSource != null) {
        Options options = method.getAnnotation(Options.class);
        final String mappedStatementId = type.getName() + "." + method.getName();
        Integer fetchSize = null;
        Integer timeout = null;/*from   www.j  a va  2s.c o m*/
        StatementType statementType = StatementType.PREPARED;
        ResultSetType resultSetType = ResultSetType.FORWARD_ONLY;
        SqlCommandType sqlCommandType = getSqlCommandType(method);
        boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
        boolean flushCache = !isSelect;
        boolean useCache = isSelect;

        KeyGenerator keyGenerator;
        String keyProperty = "id";
        String keyColumn = null;
        if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
            // first check for SelectKey annotation - that overrides everything else
            SelectKey selectKey = method.getAnnotation(SelectKey.class);
            if (selectKey != null) {
                keyGenerator = handleSelectKeyAnnotation(selectKey, mappedStatementId, getParameterType(method),
                        languageDriver);
                keyProperty = selectKey.keyProperty();
            } else if (options == null) {
                keyGenerator = configuration.isUseGeneratedKeys() ? Jdbc3KeyGenerator.INSTANCE
                        : NoKeyGenerator.INSTANCE;
            } else {
                keyGenerator = options.useGeneratedKeys() ? Jdbc3KeyGenerator.INSTANCE
                        : NoKeyGenerator.INSTANCE;
                keyProperty = options.keyProperty();
                keyColumn = options.keyColumn();
            }
        } else {
            keyGenerator = NoKeyGenerator.INSTANCE;
        }

        if (options != null) {
            if (FlushCachePolicy.TRUE.equals(options.flushCache())) {
                flushCache = true;
            } else if (FlushCachePolicy.FALSE.equals(options.flushCache())) {
                flushCache = false;
            }
            useCache = options.useCache();
            fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE
                    ? options.fetchSize()
                    : null; //issue #348
            timeout = options.timeout() > -1 ? options.timeout() : null;
            statementType = options.statementType();
            resultSetType = options.resultSetType();
        }

        String resultMapId = null;
        ResultMap resultMapAnnotation = method.getAnnotation(ResultMap.class);
        if (resultMapAnnotation != null) {
            String[] resultMaps = resultMapAnnotation.value();
            StringBuilder sb = new StringBuilder();
            for (String resultMap : resultMaps) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(resultMap);
            }
            resultMapId = sb.toString();
        } else if (isSelect) {
            resultMapId = parseResultMap(method);
        }

        assistant.addMappedStatement(mappedStatementId, sqlSource, statementType, sqlCommandType, fetchSize,
                timeout,
                // ParameterMapID
                null, parameterTypeClass, resultMapId, getReturnType(method), resultSetType, flushCache,
                useCache,
                // TODO gcode issue #577
                false, keyGenerator, keyProperty, keyColumn,
                // DatabaseID
                null, languageDriver,
                // ResultSets
                options != null ? nullOrEmpty(options.resultSets()) : null);
    }
}

From source file:com.baomidou.mybatisplus.MybatisMapperAnnotationBuilder.java

License:Apache License

private KeyGenerator handleSelectKeyAnnotation(SelectKey selectKeyAnnotation, String baseStatementId,
        Class<?> parameterTypeClass, LanguageDriver languageDriver) {
    String id = baseStatementId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    Class<?> resultTypeClass = selectKeyAnnotation.resultType();
    StatementType statementType = selectKeyAnnotation.statementType();
    String keyProperty = selectKeyAnnotation.keyProperty();
    String keyColumn = selectKeyAnnotation.keyColumn();
    boolean executeBefore = selectKeyAnnotation.before();

    // defaults//from  ww w. ja  v a  2 s  .c om
    boolean useCache = false;
    KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;
    Integer fetchSize = null;
    Integer timeout = null;
    boolean flushCache = false;
    String parameterMap = null;
    String resultMap = null;
    ResultSetType resultSetTypeEnum = null;

    SqlSource sqlSource = buildSqlSourceFromStrings(selectKeyAnnotation.statement(), parameterTypeClass,
            languageDriver);
    SqlCommandType sqlCommandType = SqlCommandType.SELECT;

    assistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
            parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache, false,
            keyGenerator, keyProperty, keyColumn, null, languageDriver, null);

    id = assistant.applyCurrentNamespace(id, false);

    MappedStatement keyStatement = configuration.getMappedStatement(id, false);
    SelectKeyGenerator answer = new SelectKeyGenerator(keyStatement, executeBefore);
    configuration.addKeyGenerator(id, answer);
    return answer;
}

From source file:com.baomidou.mybatisplus.plugins.PaginationInterceptor.java

License:Apache License

/**
 * Physical Pagination Interceptor for all the queries with parameter {@link org.apache.ibatis.session.RowBounds}
 *///  w  ww . j av  a  2s.com
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
    // ?SELECT?
    MappedStatement mappedStatement = (MappedStatement) metaStatementHandler
            .getValue("delegate.mappedStatement");
    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return invocation.proceed();
    }
    RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
    /* ??? */
    if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
        return invocation.proceed();
    }
    BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
    String originalSql = boundSql.getSql();
    Connection connection = (Connection) invocation.getArgs()[0];
    if (isDynamicDataSource()) {
        dialectType = JdbcUtils.getDbType(connection.getMetaData().getURL()).getDb();
    }
    if (rowBounds instanceof Pagination) {
        Pagination page = (Pagination) rowBounds;
        boolean orderBy = true;
        if (page.isSearchCount()) {
            CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType, dialectType,
                    page.isOptimizeCount());
            orderBy = countOptimize.isOrderBy();
            this.queryTotal(countOptimize.getCountSQL(), mappedStatement, boundSql, page, connection);
            if (page.getTotal() <= 0) {
                return invocation.proceed();
            }
        }
        String buildSql = SqlUtils.concatOrderBy(originalSql, page, orderBy);
        originalSql = DialectFactory.buildPaginationSql(page, buildSql, dialectType, dialectClazz);
    } else {
        // support physical Pagination for RowBounds
        originalSql = DialectFactory.buildPaginationSql(rowBounds, originalSql, dialectType, dialectClazz);
    }

    /*
       * <p> ? </p> <p> ???????</p>
     */
    metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
    metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
    metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
    return invocation.proceed();
}

From source file:com.baomidou.mybatisplus.plugins.SqlExplainInterceptor.java

License:Apache License

/**
 * <p>/*from w  w  w.  jav  a2s.c o m*/
 * ? SQL
 * </p>
 *
 * @param configuration
 * @param mappedStatement
 * @param boundSql
 * @param connection
 * @param parameter
 * @return
 * @throws Exception
 */
protected void sqlExplain(Configuration configuration, MappedStatement mappedStatement, BoundSql boundSql,
        Connection connection, Object parameter) {
    StringBuilder explain = new StringBuilder("EXPLAIN ");
    explain.append(boundSql.getSql());
    String sqlExplain = explain.toString();
    StaticSqlSource sqlsource = new StaticSqlSource(configuration, sqlExplain, boundSql.getParameterMappings());
    MappedStatement.Builder builder = new MappedStatement.Builder(configuration, "explain_sql", sqlsource,
            SqlCommandType.SELECT);
    builder.resultMaps(mappedStatement.getResultMaps()).resultSetType(mappedStatement.getResultSetType())
            .statementType(mappedStatement.getStatementType());
    MappedStatement query_statement = builder.build();
    DefaultParameterHandler handler = new DefaultParameterHandler(query_statement, parameter, boundSql);
    try (PreparedStatement stmt = connection.prepareStatement(sqlExplain)) {
        handler.setParameters(stmt);
        try (ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                if (!"Using where".equals(rs.getString("Extra"))) {
                    if (this.isStopProceed()) {
                        throw new MybatisPlusException(
                                "Error: Full table operation is prohibited. SQL: " + boundSql.getSql());
                    }
                    break;
                }
            }
        }

    } catch (Exception e) {
        throw new MybatisPlusException(e);
    }
}

From source file:com.baomidou.mybatisplus.toolkit.TableInfoHelper.java

License:Apache License

public static KeyGenerator genKeyGenerator(TableInfo tableInfo, MapperBuilderAssistant builderAssistant,
        String baseStatementId, LanguageDriver languageDriver) {
    DBType dbType = GlobalConfiguration.getDbType(builderAssistant.getConfiguration());
    if (dbType != DBType.ORACLE)
        throw new IllegalArgumentException("??Oracle?");
    String id = baseStatementId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    Class<?> resultTypeClass = tableInfo.getKeySequence().idClazz();
    Class<?> parameterTypeClass = null;
    StatementType statementType = StatementType.PREPARED;
    String keyProperty = tableInfo.getKeyProperty();
    String keyColumn = tableInfo.getKeyColumn();
    boolean executeBefore = true;
    boolean useCache = false;
    KeyGenerator keyGenerator = new NoKeyGenerator();
    Integer fetchSize = null;/*from   w  ww.ja v  a  2  s .  c  o m*/
    Integer timeout = null;
    boolean flushCache = false;
    String parameterMap = null;
    String resultMap = null;
    ResultSetType resultSetTypeEnum = null;
    //??ORACLE????
    String sql = "select " + tableInfo.getKeySequence().value() + ".nextval from dual";
    SqlSource sqlSource = languageDriver.createSqlSource(builderAssistant.getConfiguration(), sql.trim(), null);
    SqlCommandType sqlCommandType = SqlCommandType.SELECT;
    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout,
            parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache,
            useCache, false, keyGenerator, keyProperty, keyColumn, null, languageDriver, null);
    id = builderAssistant.applyCurrentNamespace(id, false);
    MappedStatement keyStatement = builderAssistant.getConfiguration().getMappedStatement(id, false);
    SelectKeyGenerator answer = new SelectKeyGenerator(keyStatement, executeBefore);
    builderAssistant.getConfiguration().addKeyGenerator(id, answer);
    return answer;
}

From source file:com.eryansky.common.orm.mybatis.proxy.PaginationMapperMethod.java

License:Apache License

/**
 * ???/*from   w  w w  .  j  av a  2  s  .  com*/
 */
private void setupCommandType() {
    MappedStatement ms = config.getMappedStatement(commandName);
    type = ms.getSqlCommandType();
    if (type != SqlCommandType.SELECT) {
        throw new BindingException("Unsupport execution method for: " + commandName);
    }
}