处理 MappedStatement

@param ms
16878
public void processMappedStatement(MappedStatement ms){
        MapperTemplate mapperTemplate = isMapperMethod(ms.getId());
        if(mapperTemplate != null && ms.getSqlSource() instanceof ProviderSqlSource) {
            setSqlSource(ms, mapperTemplate);
        }
    }
761732
public MapperTemplate isMapperMethod(String msId) {
        MapperTemplate mapperTemplate = getMapperTemplateByMsId(msId);
        if(mapperTemplate == null){
            //通过 @RegisterMapper 注解自动注册的功能
            try {
                Class<?> mapperClass = getMapperClass(msId);
                if(mapperClass.isInterface() && hasRegisterMapper(mapperClass)){
                    mapperTemplate = getMapperTemplateByMsId(msId);
                }
            } catch (Exception e){
            }
        }
        return mapperTemplate;
    }
410563
public static PreparedStatement prepareStatement(Connection conn, String sql, Object... params) throws SQLException {
		Assert.notBlank(sql, "Sql String must be not blank!");

		sql = sql.trim();
		SqlLog.INSTASNCE.log(sql, params);
		PreparedStatement ps;
		if (StrUtil.startWithIgnoreCase(sql, "insert")) {
			// 插入默认返回主键
			ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
		} else {
			ps = conn.prepareStatement(sql);
		}
		return fillParams(ps, params);
	}
977223
public static PreparedStatement setStrings(PreparedStatement stmt, String... params)
			throws SQLException {
		return setStrings(1, stmt, params);
	}
1049853
public static MappedStatement getExistedMappedStatement(Configuration configuration, String msId) {
        MappedStatement mappedStatement = null;
        try {
            mappedStatement = configuration.getMappedStatement(msId, false);
        } catch (Throwable t) {
            //ignore
        }
        return mappedStatement;
    }
1020294
public static PreparedStatement fillParams(PreparedStatement ps, Collection<Object> params) throws SQLException {
		return fillParams(ps, params.toArray(new Object[params.size()]));
	}
895112
public String updateByExample(MappedStatement ms) {
        Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        if (isCheckExampleEntityClass()) {
            sql.append(SqlHelper.exampleCheck(entityClass));
        }
        //安全更新，Example 必须包含条件
        if (getConfig().isSafeUpdate()) {
            sql.append(SqlHelper.exampleHasAtLeastOneCriteriaCheck("example"));
        }
        sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass), "example"));
        sql.append(SqlHelper.updateSetColumnsIgnoreVersion(entityClass, "record", false, false));
        sql.append(SqlHelper.updateByExampleWhereClause());
        return sql.toString();
    }
912486
@Override
    public void set(BindingSetStatementContext<JsonArray> ctx) throws SQLException {
        ctx.statement().setString(ctx.index(), Objects.toString(ctx.convert(converter()).value(), null));
    }
385829
public void initDelegateDialect(MappedStatement ms) {
        if (delegate == null) {
            if (autoDialect) {
                this.delegate = getDialect(ms);
            } else {
                dialectThreadLocal.set(getDialect(ms));
            }
        }
    }
640565
public String existsWithPrimaryKey(MappedStatement ms) {
        Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.selectCountExists(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.wherePKColumns(entityClass));
        return sql.toString();
    }
1142935
public int[] executeBatchPreparedStatement(String statement, Collection inParamsBatch) throws SQLException {
		return executeBatchPreparedStatement(statement, inParamsBatch, true);
	}
611371
public void bind(SQLiteStatement statement) {
		if (this.compiledStatement != null) {
			// already binded
			return;
		}

		int index = 1;

		statement.clearBindings();
		Object value;

		for (int j = 0; j < args.size(); j++) {
			value = args.get(j);
			switch (valueType.get(index - 1)) {
			case BOOLEAN:
				statement.bindLong(index, (long) (((Boolean) value) == true ? 1 : 0));
				break;
			case BYTE:
				statement.bindLong(index, (byte) value);
				break;
			case SHORT:
				statement.bindLong(index, (short) value);
				break;
			case INTEGER:
				statement.bindLong(index, (int) value);
				break;
			case CHARACTER:
				statement.bindLong(index, Character.getNumericValue((char)value));
				break;
			case LONG:
				statement.bindLong(index, (long) value);
				break;
			case BYTE_ARRAY:
				statement.bindBlob(index, (byte[]) value);
				break;
			case FLOAT:
				statement.bindDouble(index, (float) value);
				break;
			case DOUBLE:
				statement.bindDouble(index, (double) value);
				break;
			case NULL:
				statement.bindNull(index);
				break;
			case STRING:
				statement.bindString(index, (String) value);
				break;
			}
			index++;
		}

		for (int i = 0; i < whereArgs.size(); i++, index++) {
			statement.bindString(index, whereArgs.get(i));
		}
	}
1185445
private static String stmtAssignSqlParams(PreparedStatement stmt, List<SqlParam> sqlParams) throws SQLException {
		String cursorParam = null;
		if (sqlParams == null)
			return null;

		CallableStatement cstmt = null;
		if (stmt instanceof CallableStatement) {
			cstmt = (CallableStatement) stmt;
		}

		int pos = 0;
		for (SqlParam param : sqlParams) {
			pos++;
			boolean isPositionalParam = (param.code == null); // named vs positional param
			if (param.type == null)
				throw new SQLDataException("Please provide parameter type for param.code='" + param.code + "' pos=" + pos);
			if (isPositionalParam == false && cstmt == null)
				throw new SQLDataException("To use named params, need to use CallableStatement (param.code='" + param.code + "' pos=" + pos + ")");

			switch (param.type) {
				case CURSOR:
					if (cstmt == null)
						throw new SQLDataException("Param type CURSOR is not allowed for preparedStatement");
					cursorParam = param.code;
					if (param.code == null)
						cstmt.registerOutParameter(pos, JetJdbcParamType.CURSOR.oracleId);
					else
						cstmt.registerOutParameter(param.code, JetJdbcParamType.CURSOR.oracleId);
					break;
				case STRING:
					if (isPositionalParam)
						stmt.setString(pos, param.value == null ? null : param.value.toString());
					else
						cstmt.setString(param.code, param.value == null ? null : param.value.toString());
					break;
				case INTEGER: case LONG:
					if (param.value == null) {
						if (isPositionalParam)
							stmt.setNull(pos, Types.BIGINT);
						else
							cstmt.setNull(param.code, Types.BIGINT);
					} else {
						long val = 0;
						if (param.value.getClass().isAssignableFrom(Integer.class)) {
							val = (Integer) param.value;
						} else {
							val = (Long) param.value;
						}
						if (isPositionalParam)
							stmt.setLong(pos, val);
						else
							cstmt.setLong(param.code, val);
					}
					break;
				case TIMESTAMP:
					Date date1 = (Date) param.value;
					if (isPositionalParam)
						stmt.setTimestamp(pos, param.value == null ? null : new Timestamp(date1.getTime()));
					else
						cstmt.setTimestamp(param.code, param.value == null ? null : new Timestamp(date1.getTime()));
					break;
				case DATE:
					Date date2 = (Date) param.value;
					if (isPositionalParam)
						stmt.setDate(pos, param.value == null ? null : new java.sql.Date(date2.getTime()));
					else
						cstmt.setDate(param.code, param.value == null ? null : new java.sql.Date(date2.getTime()));
					break;
				case BLOB:
					if (param.value == null) {
						if (isPositionalParam)
							stmt.setBlob(pos, new ByteArrayInputStream(new byte[0]));
						else
							cstmt.setBlob(param.code, new ByteArrayInputStream(new byte[0]));
					} else {
						byte[] bytes = (byte[]) param.value;
						if (isPositionalParam)
							stmt.setBlob(pos, new ByteArrayInputStream(bytes), (int) bytes.length);
						else
							cstmt.setBlob(param.code, new ByteArrayInputStream(bytes), (int) bytes.length);
					}
					break;
				default:
					throw new IllegalStateException("Data type '" + param.type.toString() + "' is not supported yet");
			}
		}
		return cursorParam;
	}
727130
public final void setValues(PreparedStatement ps) throws SQLException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Setting parameters " + this.parameters + " on prepared statement " + ps);
        }
        
        int parameterIndex = 0;
        for (final Phrase parameterPhrase : this.parameters) {
            final Object parameter = parameterPhrase.evaluate(this.req, this.res);
            ps.setObject(++parameterIndex, parameter);
        }
    }
1112673
@Override
	public int[] doBatch(final SqlContext sqlContext, final PreparedStatement preparedStatement, final int[] result) {
		if (LOG.isDebugEnabled()) {
			int[] counts = result;
			try {
				counts = new int[] { preparedStatement.getUpdateCount() };
			} catch (SQLException ex) {
				ex.printStackTrace();
			}

			StringBuilder builder = new StringBuilder();
			for (int val : counts) {
				builder.append(val).append(", ");
			}
			LOG.debug("SQL:{} executed. Result:{}", sqlContext.getSqlName(), builder.toString());
		}
		return result;
	}
816352
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();
    }
653915
public String deleteByIdList(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.deleteFromTable(entityClass, tableName(entityClass)));
        appendWhereIdList(sql, entityClass, getConfig().isSafeDelete());
        return sql.toString();
    }