Java Code Examples for org.apache.ibatis.mapping.MappedStatement#getSqlCommandType()

The following examples show how to use org.apache.ibatis.mapping.MappedStatement#getSqlCommandType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
private MappedStatement cloneMappedStatement(MappedStatement old, BoundSql boundSql){
	MappedStatement.Builder builder = new MappedStatement.Builder(
			old.getConfiguration(), old.getId(), new AlwaySqlSource(
					boundSql), old.getSqlCommandType());
       builder.cache(old.getCache());
       builder.databaseId(old.getDatabaseId());
       builder.fetchSize(old.getFetchSize());
       builder.flushCacheRequired(old.isFlushCacheRequired());
       builder.keyGenerator(old.getKeyGenerator());
       builder.keyProperty(join(old.getKeyProperties()));
       builder.keyColumn(join(old.getKeyColumns()));
       builder.lang(old.getLang());
       builder.resource(old.getResource());
       builder.resultMaps(old.getResultMaps());
       builder.resultSetType(old.getResultSetType());
       builder.parameterMap(old.getParameterMap());
       builder.statementType(old.getStatementType());
       builder.timeout(old.getTimeout());
       builder.useCache(old.isUseCache());
       builder.resultOrdered(old.isResultOrdered());
       builder.resulSets(join(old.getResulSets()));

       return builder.build();
}
 
Example 2
Source File: MapperEnhancer.java    From tsharding with MIT License 6 votes vote down vote up
protected MappedStatement copyFromMappedStatement(MappedStatement ms,
                                                  SqlSource newSqlSource, String newMsId) {
    MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, newSqlSource, ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    // setStatementTimeout()
    builder.timeout(ms.getTimeout());
    // setParameterMap()
    builder.parameterMap(ms.getParameterMap());
    // setStatementResultMap()
    List<ResultMap> resultMaps = ms.getResultMaps();
    builder.resultMaps(resultMaps);
    builder.resultSetType(ms.getResultSetType());
    // setStatementCache()
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());
    return builder.build();
}
 
Example 3
Source File: SundialInterceptor.java    From Milkomeda with MIT License 6 votes vote down vote up
private void updateSql(String sql, Invocation invocation, MappedStatement ms, Object[] args, BoundSql boundSql) {
    BoundSql boundSqlNew = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    MappedStatement mappedStatement = copyFrom(ms, new BoundSqlSqlSource(boundSqlNew));
    // 替换映射的语句
    args[0] = mappedStatement;

    // 针对查询方式的参数替换
    if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
        Executor executor = (Executor) invocation.getTarget();
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        // 6个参数时(因为分页插件的原因导致问题,需要修改对应的类型值)
        if (args.length == 6) {
            args[4] = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            args[5] = boundSqlNew;
        }
    }
}
 
Example 4
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 6 votes vote down vote up
private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
    MappedStatement.Builder builder =
            new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
        StringBuilder keyProperties = new StringBuilder();
        for (String keyProperty : ms.getKeyProperties()) {
            keyProperties.append(keyProperty).append(",");
        }
        keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
        builder.keyProperty(keyProperties.toString());
    }
    builder.timeout(ms.getTimeout());
    builder.parameterMap(ms.getParameterMap());
    builder.resultMaps(ms.getResultMaps());
    builder.resultSetType(ms.getResultSetType());
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());
 
    return builder.build();
}
 
Example 5
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 6 votes vote down vote up
private String getOperateType(Invocation invocation) {
    final Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    SqlCommandType commondType = ms.getSqlCommandType();
    if (commondType.compareTo(SqlCommandType.SELECT) == 0) {
        return "select";
    }
    if (commondType.compareTo(SqlCommandType.INSERT) == 0) {
        return "insert";
    }
    if (commondType.compareTo(SqlCommandType.UPDATE) == 0) {
        return "update";
    }
    if (commondType.compareTo(SqlCommandType.DELETE) == 0) {
        return "delete";
    }
    return null;
}
 
Example 6
Source File: PaginationHandler.java    From sqlhelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
private MappedStatement customOrderByStatement(final MappedStatement ms, final String orderByStatementId) {
    final MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), orderByStatementId, ms.getSqlSource(), ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    if (Emptys.isNotEmpty(ms.getKeyProperties())) {
        final StringBuilder keyProperties = new StringBuilder();
        for (final String keyProperty : ms.getKeyProperties()) {
            keyProperties.append(keyProperty).append(",");
        }
        keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
        builder.keyProperty(keyProperties.toString());
    }
    builder.timeout(ms.getTimeout());
    builder.parameterMap(ms.getParameterMap());
    builder.resultMaps(ms.getResultMaps());
    builder.resultSetType(ms.getResultSetType());
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());
    return builder.build();
}
 
Example 7
Source File: CheckSQLInterceptor.java    From java-tutorial with MIT License 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

    //获取方法的第0个参数,也就是MappedStatement。@Signature注解中的args中的顺序
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    //获取sql命令操作类型
    SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
    final Object[] queryArgs = invocation.getArgs();
    final Object parameter = queryArgs[1];

    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    String sql = boundSql.getSql();

    if (SqlCommandType.DELETE.equals(sqlCommandType)) {
        //格式化sql
        sql = sql.replace("\n", "");
        if (!sql.toLowerCase().contains(SQL_DELETE_WHERE)) {
            sql = sql.replace(" ", "");
            logger.warn("删除语句中没有where条件,sql为:{}", sql);
            throw new SQLException("删除语句中没有where条件");
        }
        return invocation.proceed();
    }

    return null;
}
 
Example 8
Source File: UpdateEnhancement.java    From mybatis-boost with MIT License 6 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    if (mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE &&
            sql.toUpperCase().startsWith("UPDATE SET ")) {
        String[] split = splitSql(sql); // split[0] = columns, split[1] = conditions(if there were)
        Class<?> entityType = MapperUtils.getEntityTypeFromMapper
                (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");

        BinaryTuple<List<String>, List<String>> propertiesAndColumns =
                SqlUtils.getPropertiesAndColumnsFromLiteralColumns(split[0], entityType, mapUnderscoreToCamelCase);
        List<String> conditionProperties = getConditionProperties(entityType, boundSql.getParameterMappings());
        propertiesAndColumns.first().removeAll(conditionProperties);
        propertiesAndColumns.second().removeAll(conditionProperties.stream()
                .map(it -> SqlUtils.normalizeColumn(it, mapUnderscoreToCamelCase)).collect(Collectors.toList()));

        metaObject.setValue("delegate.boundSql.sql",
                buildSQL(sql, entityType, propertiesAndColumns.second(), split));
        metaObject.setValue("delegate.boundSql.parameterMappings",
                getParameterMappings(metaObject, boundSql, propertiesAndColumns.first()));
    }
}
 
Example 9
Source File: NullEnhancement.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT ||
            mappedStatement.getSqlCommandType() == SqlCommandType.DELETE) {
        String sql = boundSql.getSql();

        Matcher matcher = SqlUtils.PATTERN_PLACEHOLDER.matcher(sql);
        Iterator<ParameterMapping> iterator = boundSql.getParameterMappings().iterator();
        MetaObject parameterMetaObject = MyBatisUtils.getMetaObject(boundSql.getParameterObject());
        boolean isUpperCase = Character.isUpperCase(sql.charAt(0));

        int offset = 0;
        StringBuilder sqlBuilder = new StringBuilder();
        while (matcher.find() & iterator.hasNext()) {
            try {
                if (parameterMetaObject.getValue(iterator.next().getProperty()) != null) continue;
            } catch (Exception ignored) {
                continue;
            }
            iterator.remove();

            String substring = sql.substring(offset, matcher.end());
            int before = substring.length();
            substring = substring.replaceFirst(" ?!= *\\?$| ?<> *\\?$",
                    isUpperCase ? " IS NOT NULL" : " is not null");
            if (substring.length() == before) {
                substring = substring.replaceFirst(" ?= *\\?$", isUpperCase ? " IS NULL" : " is null");
            }
            sqlBuilder.append(substring);
            offset = matcher.end();
        }
        sqlBuilder.append(sql, offset, sql.length());
        metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
    }
}
 
Example 10
Source File: OffsetLimitInterceptor.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
private MappedStatement copyFromMappedStatement(MappedStatement ms,SqlSource newSqlSource) {
	Builder builder = new Builder(ms.getConfiguration(),ms.getId(),newSqlSource,ms.getSqlCommandType());
	
	builder.resource(ms.getResource());
	builder.fetchSize(ms.getFetchSize());
	builder.statementType(ms.getStatementType());
	builder.keyGenerator(ms.getKeyGenerator());
	if(ms.getKeyProperties() != null && ms.getKeyProperties().length !=0){
           StringBuffer keyProperties = new StringBuffer();
           for(String keyProperty : ms.getKeyProperties()){
               keyProperties.append(keyProperty).append(",");
           }
           keyProperties.delete(keyProperties.length()-1, keyProperties.length());
		builder.keyProperty(keyProperties.toString());
	}
	
	//setStatementTimeout()
	builder.timeout(ms.getTimeout());
	
	//setStatementResultMap()
	builder.parameterMap(ms.getParameterMap());
	
	//setStatementResultMap()
       builder.resultMaps(ms.getResultMaps());
	builder.resultSetType(ms.getResultSetType());
    
	//setStatementCache()
	builder.cache(ms.getCache());
	builder.flushCacheRequired(ms.isFlushCacheRequired());
	builder.useCache(ms.isUseCache());
	
	return builder.build();
}
 
Example 11
Source File: PaginationMapperMethod.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 设置当前的参数的类型信息
 */
private void setupCommandType() {
    MappedStatement ms = config.getMappedStatement(commandName);
    type = ms.getSqlCommandType();
    if (type != SqlCommandType.SELECT) {
        throw new BindingException("Unsupport execution method for: " + commandName);
    }
}
 
Example 12
Source File: DataPermissionInterceptor.java    From DataPermissionHelper with Apache License 2.0 5 votes vote down vote up
private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource, String newMsId) {
    MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, newSqlSource,
            ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
        StringBuilder keyProperties = new StringBuilder();
        for (String keyProperty : ms.getKeyProperties()) {
            keyProperties.append(keyProperty).append(",");
        }
        keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
        builder.keyProperty(keyProperties.toString());
    }

    // setStatementTimeout()
    builder.timeout(ms.getTimeout());
    // setStatementResultMap()
    builder.parameterMap(ms.getParameterMap());
    // setStatementResultMap()
    builder.resultMaps(ms.getResultMaps());
    builder.resultSetType(ms.getResultSetType());
    // setStatementCache()
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());
    return builder.build();
}
 
Example 13
Source File: CustomInterceptor.java    From ml-blog with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    // 获取 SQL 命令
    SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
    // 获取参数
    Object parameter = invocation.getArgs()[1];
    if (parameter != null) {
        Field[] declaredFields = parameter.getClass().getDeclaredFields();

        for (Field field : declaredFields) {
            if (field.getAnnotation(CreateTime.class) != null) {
                if (SqlCommandType.INSERT.equals(sqlCommandType)) { // insert 语句插入 createTime
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, new Date());
                    }
                }
            }

            if (field.getAnnotation(UpdateTime.class) != null) { // insert 或 update 语句插入 updateTime
                if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, new Date());
                    }
                }
            }
        }
    }

    return invocation.proceed();
}
 
Example 14
Source File: InsertEnhancement.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    String sqlUpperCase = sql.toUpperCase();
    if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT &&
            !sqlUpperCase.startsWith("INSERT INTO ") && sqlUpperCase.startsWith("INSERT ")) {
        Matcher matcher = PATTERN_LITERAL_COLUMNS.matcher(sql = sql.substring(7));
        if (!matcher.find()) {
            throw new IllegalStateException("Found INSERT statement but no column is specified");
        }

        String literalColumns = matcher.group();
        Class<?> entityType = MapperUtils.getEntityTypeFromMapper
                (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");
        BinaryTuple<List<String>, List<String>> propertiesAndColumns =
                SqlUtils.getPropertiesAndColumnsFromLiteralColumns(literalColumns, entityType, mapUnderscoreToCamelCase);

        List<?> entities = boundSql.getParameterObject() instanceof Map ?
                (List<?>) ((Map) boundSql.getParameterObject()).get("param1") :
                Collections.singletonList(Objects.requireNonNull(boundSql.getParameterObject(),
                        "ParameterObject mustn't be null"));
        if (entities.isEmpty()) {
            throw new IllegalArgumentException("Can't insert empty list");
        } else {
            String additionalStatement = sql.substring(literalColumns.length());
            org.apache.ibatis.session.Configuration configuration =
                    (org.apache.ibatis.session.Configuration) metaObject.getValue("delegate.configuration");
            Object parameterObject = buildParameterObject(entities);
            metaObject.setValue("delegate.boundSql.sql",
                    buildSql(entityType, propertiesAndColumns.second(), entities.size(), additionalStatement));
            metaObject.setValue("delegate.boundSql.parameterMappings",
                    MyBatisUtils.getListParameterMappings(configuration, propertiesAndColumns.first(), entities.size()));
            metaObject.setValue("delegate.boundSql.parameterObject", parameterObject);
            MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
                    .setValue("parameterObject", parameterObject);
        }
    }
}
 
Example 15
Source File: EntityExecutor.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public int update(final MappedStatement ms, final Object parameter) throws SQLException {
  SqlCommandType commandType = ms.getSqlCommandType();
  if (commandType != SELECT && frozen.get()) {
    log.debug("Disallowing {} because the application is frozen", commandType);
    throw new FrozenException(commandType + " is not allowed while the application is frozen");
  }
  if (commandType == INSERT && parameter instanceof HasEntityId) {
    generateEntityId((HasEntityId) parameter);
  }
  return delegate.update(ms, parameter);
}
 
Example 16
Source File: MSUtils.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
/**
 * 新建count查询的MappedStatement
 *
 * @param ms
 * @param newMsId
 * @return
 */
public static MappedStatement newCountMappedStatement(MappedStatement ms, String newMsId) {
    MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, ms.getSqlSource(), ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
        StringBuilder keyProperties = new StringBuilder();
        for (String keyProperty : ms.getKeyProperties()) {
            keyProperties.append(keyProperty).append(",");
        }
        keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
        builder.keyProperty(keyProperties.toString());
    }
    builder.timeout(ms.getTimeout());
    builder.parameterMap(ms.getParameterMap());
    //count查询返回值int
    List<ResultMap> resultMaps = new ArrayList<ResultMap>();
    ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), Long.class, EMPTY_RESULTMAPPING).build();
    resultMaps.add(resultMap);
    builder.resultMaps(resultMaps);
    builder.resultSetType(ms.getResultSetType());
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());

    return builder.build();
}
 
Example 17
Source File: HaloInterceptor.java    From Milkomeda with MIT License 5 votes vote down vote up
private void invokeHandler(String tableName, HandlerMetaData handlerMetaData, String sql, MappedStatement mappedStatement, Object param, Object result) {
    try {
        // INSERT/UPDATE/DELETE/SELECT
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Method method = handlerMetaData.getMethod();
        Object target = handlerMetaData.getTarget();
        // 获取参数类型
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 1 && parameterTypes[0] == HaloMeta.class) {
            HaloMeta haloMeta = new HaloMeta(sqlCommandType, tableName, param, result);
            method.invoke(target, haloMeta);
        } else if (parameterTypes.length > 1) {
            // 检测参数是否有SqlCommandType
            if (parameterTypes[0] == SqlCommandType.class) {
                if (result == null) {
                    method.invoke(target, sqlCommandType, param);
                } else {
                    method.invoke(target, sqlCommandType, param, result);
                }
            } else {
                if (result == null) {
                    method.invoke(target, param, sqlCommandType);
                } else {
                    method.invoke(target, param, result, sqlCommandType);
                }
            }
        } else {
            method.invoke(target, param);
        }
    } catch (Exception e) {
        log.error("Halo invoke handler [{}] error: {}, with stmt id: {} and sql: {}", handlerMetaData.getTarget(), e.getMessage(), mappedStatement.getId(), sql, e);
    }
}
 
Example 18
Source File: PaginationHandler.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private MappedStatement customCountStatement(final MappedStatement ms, final String countStatementId, String querySql, PagingRequest pagingRequest) {
    MappedStatement countStatement = paginationConfig.enableCountCache() ? this.countStatementCache.getIfPresent(querySql) : null;
    if (countStatement == null) {
        final MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), countStatementId, ms.getSqlSource(), ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (Emptys.isNotEmpty(ms.getKeyProperties())) {
            final StringBuilder keyProperties = new StringBuilder();
            for (final String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        final List<ResultMap> resultMaps = new ArrayList<ResultMap>();
        final ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), Long.class, new ArrayList<ResultMapping>()).build();
        resultMaps.add(resultMap);
        builder.resultMaps(resultMaps);
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        boolean useCache = Objects.isNull(pagingRequest.getCacheCount()) ? ms.isUseCache() : pagingRequest.getCacheCount();
        builder.useCache(useCache);

        countStatement = builder.build();
        if (paginationConfig.enableCountCache() && useCache) {
            this.countStatementCache.set(querySql, countStatement);
        }
    }
    return countStatement;
}
 
Example 19
Source File: PaginationHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
/**
 * 新建count查询的MappedStatement
 *
 * @param ms
 * @return
 */
public MappedStatement getCountMappedStatement(MappedStatement ms) {

    String newMsId = ms.getId() + PAGE_COUNT_SUFFIX;

    MappedStatement statement = null;
    Configuration configuration = ms.getConfiguration();

    try {
        statement = configuration.getMappedStatement(newMsId);
        if (statement != null) { return statement; }
    } catch (Exception e) {
    }

    synchronized (configuration) {

        if (configuration.hasStatement(newMsId)) { return configuration.getMappedStatement(newMsId); }

        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(),
                newMsId, ms.getSqlSource(), ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        //count查询返回值int
        List<ResultMap> resultMaps = new ArrayList<ResultMap>();
        String id = newMsId + "-Inline";
        ResultMap resultMap = new ResultMap.Builder(configuration, id, Long.class,
                new ArrayList<ResultMapping>(0)).build();
        resultMaps.add(resultMap);
        builder.resultMaps(resultMaps);

        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        statement = builder.build();
        configuration.addMappedStatement(statement);
        return statement;
    }

}
 
Example 20
Source File: PaginationHandler.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
/**
   * 新建count查询的MappedStatement
   *
   * @param ms
   * @return
   */
  public MappedStatement getCountMappedStatement(MappedStatement ms) {
  	
  	String newMsId = ms.getId() + PAGE_COUNT_SUFFIX;
  	
  	MappedStatement statement = null;
  	Configuration configuration = ms.getConfiguration();
	
  	try {
  		statement = configuration.getMappedStatement(newMsId);
  		if(statement != null)return statement;
} catch (Exception e) {}
  	
  	synchronized (configuration) {   
  		
  		if(configuration.hasStatement(newMsId))return configuration.getMappedStatement(newMsId);
  		
  		MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, ms.getSqlSource(), ms.getSqlCommandType());
  		builder.resource(ms.getResource());
  		builder.fetchSize(ms.getFetchSize());
  		builder.statementType(ms.getStatementType());
  		builder.keyGenerator(ms.getKeyGenerator());
  		if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
  			StringBuilder keyProperties = new StringBuilder();
  			for (String keyProperty : ms.getKeyProperties()) {
  				keyProperties.append(keyProperty).append(",");
  			}
  			keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
  			builder.keyProperty(keyProperties.toString());
  		}
  		builder.timeout(ms.getTimeout());
  		builder.parameterMap(ms.getParameterMap());
  		//count查询返回值int
  		 List<ResultMap> resultMaps = new ArrayList<ResultMap>();
           String id = newMsId + "-Inline";
           ResultMap resultMap = new ResultMap.Builder(configuration, id, Long.class, new ArrayList<ResultMapping>(0)).build();
           resultMaps.add(resultMap);
           builder.resultMaps(resultMaps);
           
  		builder.resultSetType(ms.getResultSetType());
  		builder.cache(ms.getCache());
  		builder.flushCacheRequired(ms.isFlushCacheRequired());
  		builder.useCache(ms.isUseCache());
  		
  		statement = builder.build();
  		configuration.addMappedStatement(statement);
  		return statement;
  	}
  	
  }