拼接sql字符串工具类

  1. 申明注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StrSqlAnnotation {
    /**
     * 表字段名称,如"create_name"
     *
     * @return
     */
    String filedName() default "";

    /**
     * 类型 STR-字符串 LIST-集合
     * {@link com.ltd.ccci.svc.transport.api.constant.CommonSymbolConstant}
     *
     * @return
     */
    String type() default CommonSqlKeyWordConstant.LIKE_IN_TYPE;

}

  1. 相关常量类
    a. sql拼接常量:CommonSqlKeyWordConstant
public class CommonSqlKeyWordConstant {
    public static final String AND = "AND ";

    public static final String OR = "OR";

    public static final String NOT = "NOT";

    public static final String IN = "IN";

    public static final String NOT_IN = "NOT IN";

    public static final String LIKE = "LIKE";

    public static final String NOT_LIKE = "NOT LIKE";

    public static final String EQ = "=";

    public static final String NE = "<>";

    public static final String GT = ">";

    public static final String GE = ">=";

    public static final String LT = "<";

    public static final String LE = "<=";

    /**
     * 搜索条件-like or eq
     */
    public static final String LIKE_IN_TYPE = "LIKE_IN_TYPE";

}

b. 符号常量:CommonSymbolConstant(可不使用)

public class CommonSymbolConstant {
    private CommonSymbolConstant() {
    }

    /**
     * 横杠
     */
    public static final String BAR = "-";

    /**
     * 波浪号
     */
    public static final String TILDE = "~";

    /**
     * 下划线
     */
    public static final String UNDERLINE = "_";


    /**
     * 斜杠
     */
    public static final String SLASH = "/";


    /**
     * 冒号
     */
    public static final String COLON = ":";


    /**
     * 分号
     */
    public static final String SEMICOLON = ";";


    /**
     * 逗号
     */
    public static final String COMMA = ",";

    /**
     * 点
     */
    public static final String POINT = ".";

    /**
     * 顿号
     */
    public static final String PAUSE = "、";

    /**
     * 点
     */
    public static final String EMPTY = "";

    /**
     * 空格
     */
    public static final String BLANK = " ";


    /**
     * 单引号
     */
    public static final String SINGLE_QUOTES = "'";

    /**
     * 正括号
     */
    public static final String OPEN_BRACKET = "(";
    /**
     * 反括号
     */
    public static final String CLOSE_BRACKET = ")";
}

  1. 工具类:SearchUtil
public class SearchUtil {


    /**
     * 翻译单个实体
     *
     * @param obj 实体信息(搜索条件实体)
     * @param ignoredClazz 实体信息(QueryWrapper泛型指定实体)
     */
    public static <T, V> QueryWrapper<V> getSearchWrapper(T obj, Class<V> ignoredClazz) {
        QueryWrapper<V> wrapper = new QueryWrapper<>();
        // 防止未传条件不拼接where条件
        if (!ObjectUtil.isEmpty(obj)) {
            try {
                Class<?> aClass = obj.getClass();
                Map<String, Field> fields = getAllFileds(aClass);
                for (Field field : fields.values()) {
                    if (field.isAnnotationPresent(StrSqlAnnotation.class)) {
                        field.setAccessible(true);
                        StrSqlAnnotation annotation = field.getAnnotation(StrSqlAnnotation.class);
                        String filedName = annotation.filedName();
                        if (StringUtils.isBlank(filedName)) {
                            filedName = StrUtil.toUnderlineCase(field.getName());
                        }
                        String type = annotation.type();
                        Object object = field.get(obj);
                        if (ObjectUtil.isNotEmpty(object)) {
                            Class<?> filedClass = object.getClass();
                            String str = object.toString().trim();
                            // 日期格式单独转化
                            if (filedClass.equals(LocalDateTime.class)) {
                                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
                                str = ((LocalDateTime) object).format(dateTimeFormatter);
                            } else if (filedClass.equals(LocalDate.class)) {
                                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN);
                                str = ((LocalDate) object).format(dateTimeFormatter);
                            }

                            switch (type) {
                                // like in
                                case CommonSqlKeyWordConstant.LIKE_IN_TYPE -> {
                                    String[] split = str.split(",");
                                    if (split.length > 1) {
                                        wrapper.in(filedName, Arrays.asList(split));
                                    } else {
                                        wrapper.like(filedName, str);
                                    }
                                }
                                // in
                                case CommonSqlKeyWordConstant.IN -> {
                                    String parse = JSONUtil.toJsonStr(object);
                                    List<String> list = JSONUtil.toList(parse, String.class);
                                    // LocalDateTime类型如果是集合传入,接收时类型为Long。时间集合建议传List<String>
                                    if (CollUtil.isNotEmpty(list)) {
                                        wrapper.in(filedName, list);
                                    }
                                }

                                // like
                                case CommonSqlKeyWordConstant.LIKE -> wrapper.like(filedName, str);

                                // =
                                case CommonSqlKeyWordConstant.EQ -> wrapper.eq(filedName, str);
                                // >=
                                case CommonSqlKeyWordConstant.GE -> wrapper.ge(filedName, str);

                                // <=
                                case CommonSqlKeyWordConstant.LE -> wrapper.le(filedName, str);
                                default -> {
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                throw new ApiException(MsgUtils.getMessage("biz.common.StrFiledError"));
            }
        }
        return wrapper;
    }

    /**
     * 获取所有字段含父级
     *
     * @param aClass 实体类
     * @return 所有字段信息
     */
    private static Map<String, Field> getAllFileds(Class<?> aClass) {
        // key-字段名  value-字段信息
        Map<String, Field> fileds = new HashMap<>();
        List<Field> fieldList = new ArrayList<>();
        Class<?> tempClass = aClass;
        //当父类为null的时候说明到达了最上层的父类(Object类).
        while (tempClass != null) {
            fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));
            //得到父类,然后赋给自己
            tempClass = tempClass.getSuperclass();
        }
        for (Field field : fieldList) {
            fileds.put(field.getName(), field);
        }
        return fileds;
    }
    
}
  1. 使用示例
    实体类注解使用
    @Schema(title = "线路编号")
    @StrSqlAnnotation(filedName = "no")
    private String no;


    @Schema(title = "物流供应商编码-单个查询-精确查询")
    @StrSqlAnnotation(type = CommonSqlKeyWordConstant.EQ)
    private String logisticsSupplierCode;

    @Schema(title = "物流合同号")
    @StrSqlAnnotation()
    private String logisticsContractNo;

   @Schema(title = "物流供应商编码")
    @StrSqlAnnotation(filedName = "logistics_supplier_code", type = CommonSqlKeyWordConstant.IN)
    private List<String> logisticsSupplierCodes;

LambdaQueryWrapper使用示例

private LambdaQueryWrapper<LineMainDO> dealSearchInfo(LinePageReq req, SFunction<LineMainDO, ?> sortFiled, boolean whetherAsc) {
        LambdaQueryWrapper<LineMainDO> lambdaQuery = SearchUtil.getSearchWrapper(req, LineMainDO.class).lambda();
        if (CollUtil.isEmpty(req.getSortItems())) {
            lambdaQuery.orderBy(true, whetherAsc, sortFiled);
        }
        return lambdaQuery;
    }

xml使用示例
service

    public CommonPage<ReceiptPageDTO> queryPage(ReceiptPageReq req) {
          QueryWrapper<ReceiptMainDO> searchWrapper = SearchUtil.getSearchWrapper(req, ReceiptMainDO.class);
        IPage<ReceiptPageDTO> page = receiptMainMapper.queryPage(MPPager.buildPage(req), searchWrapper);
        return MPCommonPage.restPage(page );
    }

mapper

  /**
     * 运输签收分页(明细联表)
     *
     * @param ipage 分页信息
     * @param sql   高级搜索条件sql
     * @return 分页信息
     */
    IPage<ReceiptPageDTO> queryPage(Page<ReceiptMainDO> ipage, @Param(Constants.WRAPPER) QueryWrapper<ReceiptMainDO> sql);

xml

 <select id="queryPage" resultType="com.ltd.ccci.svc.transport.api.dto.receipt.ReceiptPageDTO">
        <select id="queryPage" resultType="com.ltd.ccci.svc.transport.api.dto.receipt.ReceiptPageDTO">
        SELECT *
        FROM receipt_main m,
        receipt_detail d
        <choose>
            <when test="ew.customSqlSegment != null and ew.customSqlSegment != ''">
                ${ew.customSqlSegment} and
            </when>
            <otherwise>
                where
            </otherwise>
        </choose>
        m.id = d.receipt_main_id
        and d.del_flag = 0
        and m.del_flag = 0
        order by m.update_time, d.create_time, d.id
    </select>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 解析 SQL 替换数值的工具类通常可以用来将 SQL 语句中的参数值替换为具体的数值。下面是一个简单的实现: ```java public class SqlUtils { // 将 SQL 语句中的参数占位符替换为具体的数值 public static String replaceParams(String sql, Map<String, Object> params) { for (Map.Entry<String, Object> entry : params.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof Number) { sql = sql.replace(key, value.toString()); } else { sql = sql.replace(key, "'" + value.toString() + "'"); } } return sql; } public static void main(String[] args) { String sql = "SELECT * FROM table WHERE id = :id AND name = :name"; Map<String, Object> params = new HashMap<>(); params.put(":id", 1); params.put(":name", "John"); String replacedSql = replaceParams(sql, params); System.out.println(replacedSql); } } ``` 在上述代码中,`replaceParams` 方法接收一个 SQL 语句和一个参数 `Map`,循环遍历参数 `Map` 中的每个键值对,将 SQL 语句中的参数占位符替换为具体的数值。如果参数值是一个数字,直接使用 `toString()` 方法进行替换;如果参数值是一个字符串,需要在值的两侧添加单引号。 在 `main` 方法中,我们定义了一个 SQL 语句和一个参数 `Map`,调用 `replaceParams` 方法替换 SQL 语句中的参数,并打印替换后的 SQL 语句。 这样的工具类可以方便地用于拼接 SQL 语句,并将参数值替换为具体的数值,避免了直接拼接字符串导致的 SQL 注入的风险。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值