包装字段名<br>
有时字段与SQL的某些关键字冲突，导致SQL出错，因此需要将字段名用单引号或者反引号包装起来，避免冲突
@param entity 被包装的实体
@return 包装后的字段名
6518
public Entity wrap(Entity entity){
		if(null == entity) {
			return null;
		}
		
		final Entity wrapedEntity = new Entity();
		
		//wrap table name
		wrapedEntity.setTableName(wrap(entity.getTableName()));
		
		//wrap fields
		for (Entry<String, Object> entry : entity.entrySet()) {
			wrapedEntity.set(wrap(entry.getKey()), entry.getValue());
		}
		
		return wrapedEntity;
	}
741201
public static String getMapperSql(SqlSession session, String fullMapperMethodName, Object... args) {
        if (args == null || args.length == 0) {
            return getNamespaceSql(session, fullMapperMethodName, null);
        }
        String methodName = fullMapperMethodName.substring(fullMapperMethodName.lastIndexOf('.') + 1);
        Class<?> mapperInterface = null;
        try {
            mapperInterface = Class.forName(fullMapperMethodName.substring(0, fullMapperMethodName
                    .lastIndexOf('.')));
            return getMapperSql(session, mapperInterface, methodName, args);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("参数" + fullMapperMethodName + "无效！");
        }
    }
973282
public <T> List<T>  sql(Class<T> beanType,  String entity) throws ElasticSearchException {
		SQLRestResponse result = this.client.executeRequest("/_xpack/sql",entity,   new SQLRestResponseHandler());
		return ResultUtil.buildSQLResult(result,beanType);
	}
804297
public static String getQualifiedName(HasMetadata entity) {
    if (entity != null) {
      return "" + getNamespace(entity) + "/" + getName(entity);
    } else {
      return null;
    }
  }
1079732
public String deleteByIds(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.deleteFromTable(entityClass, tableName(entityClass)));
        Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
        if (columnList.size() == 1) {
            EntityColumn column = columnList.iterator().next();
            sql.append(" where ");
            sql.append(column.getColumn());
            sql.append(" in (${_parameter})");
        } else {
            throw new MapperException("继承 deleteByIds 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
        }
        return sql.toString();
    }
102376
public int update(Connection conn, Entity record, Entity where) throws SQLException {
		checkConn(conn);
		if(CollectionUtil.isEmpty(record)){
			throw new SQLException("Empty entity provided!");
		}
		if(CollectionUtil.isEmpty(where)){
			//不允许做全表更新
			throw new SQLException("Empty where provided!");
		}
		
		//表名可以从被更新记录的Entity中获得，也可以从Where中获得
		String tableName = record.getTableName();
		if(StrUtil.isBlank(tableName)){
			tableName = where.getTableName();
			record.setTableName(tableName);
		}
		
		final Query query = new Query(SqlUtil.buildConditions(where), tableName);
		PreparedStatement ps = null;
		try {
			ps = dialect.psForUpdate(conn, record, query);
			return ps.executeUpdate();
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(ps);
		}
	}
1297081
public String getLayerName( DwgObject entity ) {
        String layerName = "";
        int layer = entity.getLayerHandle();
        for( int j = 0; j < layerTable.size(); j++ ) {
            Vector layerTableRecord = (Vector) layerTable.get(j);
            int lHandle = ((Integer) layerTableRecord.get(0)).intValue();
            if (lHandle == layer) {
                layerName = (String) layerTableRecord.get(1);
            }
        }
        /*
         * workaround for the cases in which the entity 
         * can't define it's own layer name: assign all the
         * objects to the layer 0
         */
        if (layerName.equals(""))
            return "0";
        return layerName;
    }
177204
@SuppressWarnings("unchecked")
    public String generateDocumentId(String databaseName, Object entity) {
        Class<?> clazz = entity.getClass();

        for (Tuple<Class, BiFunction<String, Object, String>> listOfRegisteredIdConvention : _listOfRegisteredIdConventions) {
            if (listOfRegisteredIdConvention.first.isAssignableFrom(clazz)) {
                return listOfRegisteredIdConvention.second.apply(databaseName, entity);
            }
        }

        return _documentIdGenerator.apply(databaseName, entity);
    }
870611
@Override
    public Long get(Entity entity) {
        Objects.requireNonNull(entity, "entity cannot be null");
        // return id()
        return entity.id();
    }
559263
@SuppressWarnings("unchecked")
	@Override
	public int delete(final Object entity) {
		@SuppressWarnings("rawtypes")
		EntityHandler handler = this.getEntityHandler();
		if (!handler.getEntityType().isInstance(entity)) {
			throw new IllegalArgumentException("Entity type not supported");
		}

		try {
			Class<?> type = entity.getClass();
			TableMetadata metadata = handler.getMetadata(this.transactionManager, type);
			SqlContext context = handler.createDeleteContext(this, metadata, type, true);
			context.setSqlKind(SqlKind.DELETE);
			handler.setDeleteParams(context, entity);
			return handler.doDelete(this, context, entity);
		} catch (SQLException e) {
			throw new EntitySqlRuntimeException(SqlKind.DELETE, e);
		}
	}
986033
public static String getEntityEncoding(HttpEntity entity) {
		final Header header = entity.getContentEncoding();
		if (header == null)
			return null;
		return header.getValue();
	}
572426
public static List<Condition> extractConditions(String alias, final Entity<?> entity) {
    if (null == entity) { return Collections.emptyList(); }
    final List<Condition> conditions = new ArrayList<Condition>();

    StringBuilder aliasBuilder = new StringBuilder(alias == null ? "" : alias);
    if (aliasBuilder.length() > 0 && !alias.endsWith(".")) aliasBuilder.append(".");
    alias = aliasBuilder.toString();
    String attr = "";
    try {
      final Set<String> props = PropertyUtils.getWritableProperties(entity.getClass());
      for (final Iterator<String> iter = props.iterator(); iter.hasNext();) {
        attr = iter.next();
        final Object value = PropertyUtils.getProperty(entity, attr);
        if (null == value) continue;
        if (!(value instanceof Collection<?>)) addAttrCondition(conditions, alias + attr, value);
      }
    } catch (Exception e) {
      logger.debug("error occur in extractConditions for  bean {} with attr named {}", entity, attr);
    }
    return conditions;
  }
476761
private static function getFields($entity, $type = 1): array
    {
        $changeFields = [];

        // 实体表结构信息
        list($table, $id, $idColumn, $fields) = self::getClassMetaData($entity);

        // 实体映射字段、值处理以及验证处理
        $idValue = null;
        foreach ($fields as $proName => $proAry) {
            $column  = $proAry['column'];
            $default = $proAry['default'];

            // 实体属性对应值
            $proValue = self::getEntityProValue($entity, $proName);

            self::validate($proAry, $proValue);

            if($type === 1 && $proValue === null){
                continue;
            }

            // insert逻辑
            if ($type === 1 && $id === $proName && $default === $proValue) {
                continue;
            }

            // update逻辑
            if ($type === 2 && null === $proValue) {
                continue;
            }

            // delete和find逻辑
            if ($type === 3 && $default === $proValue) {
                continue;
            }

            // id值赋值
            if ($idColumn === $column) {
                $idValue = $proValue;
            }

            $changeFields[$column] = $proValue;
        }

        // 如果是更新找到变化的字段
        if ($type === 2) {
            $oldFields    = $entity->getAttrs();
            $oldFields    = self::getDbOldFields(get_class($entity), $oldFields);
            $changeFields = self::getUpdateFields($oldFields, $changeFields);
        }
        return [$table, $idColumn, $idValue, $changeFields];
    }
338776
@Override
    public Long get(Entity entity) {
        Objects.requireNonNull(entity, "entity cannot be null");
        // return property value
        return entity.get(idFieldName).asLong();
    }
1301490
public SqlBuilder insert(Entity entity, DialectName dialectName) {
		// 验证
		validateEntity(entity);

		if (null != wrapper) {
			// 包装表名
			// entity = wrapper.wrap(entity);
			entity.setTableName(wrapper.wrap(entity.getTableName()));
		}

		final boolean isOracle = ObjectUtil.equal(dialectName, DialectName.ORACLE);// 对Oracle的特殊处理
		final StringBuilder fieldsPart = new StringBuilder();
		final StringBuilder placeHolder = new StringBuilder();

		boolean isFirst = true;
		String field;
		Object value;
		for (Entry<String, Object> entry : entity.entrySet()) {
			field = entry.getKey();
			value = entry.getValue();
			if (StrUtil.isNotBlank(field) /* && null != value */) {
				if (isFirst) {
					isFirst = false;
				} else {
					// 非第一个参数，追加逗号
					fieldsPart.append(", ");
					placeHolder.append(", ");
				}

				this.fields.add(field);
				fieldsPart.append((null != wrapper) ? wrapper.wrap(field) : field);
				if (isOracle && value instanceof String && StrUtil.endWithIgnoreCase((String) value, ".nextval")) {
					// Oracle的特殊自增键，通过字段名.nextval获得下一个值
					placeHolder.append(value);
				} else {
					placeHolder.append("?");
					this.paramValues.add(value);
				}
			}
		}
		sql.append("INSERT INTO ")//
				.append(entity.getTableName()).append(" (").append(fieldsPart).append(") VALUES (")//
				.append(placeHolder.toString()).append(")");

		return this;
	}
315474
protected void processKeySql(EntityTable entityTable, EntityColumn entityColumn, KeySql keySql) {
        if (keySql.useGeneratedKeys()) {
            entityColumn.setIdentity(true);
            entityColumn.setGenerator("JDBC");
            entityTable.setKeyProperties(entityColumn.getProperty());
            entityTable.setKeyColumns(entityColumn.getColumn());
        } else if (keySql.dialect() == IdentityDialect.DEFAULT) {
            entityColumn.setIdentity(true);
            entityColumn.setOrder(ORDER.AFTER);
        }  else if (keySql.dialect() != IdentityDialect.NULL) {
            //自动增长
            entityColumn.setIdentity(true);
            entityColumn.setOrder(ORDER.AFTER);
            entityColumn.setGenerator(keySql.dialect().getIdentityRetrievalStatement());
        } else if (StringUtil.isNotEmpty(keySql.sql())){

            entityColumn.setIdentity(true);
            entityColumn.setOrder(keySql.order());
            entityColumn.setGenerator(keySql.sql());
        } else if (keySql.genSql() != GenSql.NULL.class){
            entityColumn.setIdentity(true);
            entityColumn.setOrder(keySql.order());
            try {
                GenSql genSql = keySql.genSql().newInstance();
                entityColumn.setGenerator(genSql.genSql(entityTable, entityColumn));
            } catch (Exception e) {
                log.error("实例化 GenSql 失败: " + e, e);
                throw new MapperException("实例化 GenSql 失败: " + e, e);
            }
        } else if(keySql.genId() != GenId.NULL.class){
            entityColumn.setIdentity(false);
            entityColumn.setGenIdClass(keySql.genId());
        } else {
            throw new MapperException(entityTable.getEntityClass().getCanonicalName()
                    + " 类中的 @KeySql 注解配置无效!");
        }
    }
412919
private Sql getPreperSQLWithParameters(String query, Map<String, Object> parameters) {
		// 检索query语句中所有:key的标记
		Pattern pattern = Pattern.compile(":\\w+");
		Matcher matcher = pattern.matcher(query);

		// 构建<key, index>值对
		int index = 1;
		Map<String, Integer> keyIndexs = new HashMap<String, Integer>();
		while (matcher.find()) {
			String word = matcher.group();
			if (word.startsWith(":")) {
				keyIndexs.put(word.substring(1), index++);
			}
		}

		// 构建<index, value>值对
		Map<Integer, Object> prepareValue = new HashMap<Integer, Object>();
		Set<String> paramKeySet = parameters.keySet();
		for (String paramKey : paramKeySet) {
			Integer preIndex = keyIndexs.get(paramKey);
			Object preValue = parameters.get(paramKey);

			prepareValue.put(preIndex, preValue);
		}

		// 替换所有的变量为"?"
		query = matcher.replaceAll("?");

		Sql sql = new Sql(query, parameters);
		sql.setPreperStatement(true);
		sql.setKeyIndexs(keyIndexs);
		sql.setPreperValues(prepareValue);

		return sql;
	}