在使用QueryWrapper.inSql()查询时,传参是写死的SQL字符串。如果需要条件查询时需要手动拼接字符串,很不方便。所以可以利用QueryWrapper转化为所需要的条件SQL

package io.jujiang.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;

/**
 * @author xianhuiyi
 */
public class StringUtil {
    public static <T> String toSql(QueryWrapper<T> queryWrapper) {
        String customSqlSegment = queryWrapper.getCustomSqlSegment();
        for (Map.Entry<String, Object> entry : queryWrapper.getParamNameValuePairs().entrySet()) {
            customSqlSegment = customSqlSegment.replace("#{ew.paramNameValuePairs." + entry.getKey() + "}", StringUtil.formatParamValue(entry.getValue()));
        }
        return customSqlSegment;
    }


    public static String formatParamValue(Object arg) {
        String paramValue;
        if (arg instanceof String) {
            paramValue = "'" + arg.toString().replace("'", "\\'") + "'";
        } else if (arg instanceof Date) {
            paramValue = "'" + DateUtils.format((Date) arg, "yyyy-MM-dd HH:mm:ss") + "'";
        } else if (arg != null) {
            paramValue = arg.toString();
        } else {
            paramValue = null;
        }
        return paramValue;
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐