Mybatis 动态组装查询条件,仿SQL模式

目的: 以前比较习惯使用Hibernate,后来觉得mybatis不能按我想要的自动组装为SQL查询条件,所以提供该工具类;

效果图:

 

如图所示,根据条件自动组装查询条件,下面来说一下实现方法:

1. ServiceImpl书写注意项

        Page<SysLogin> resultPage = null;
        try {
            PageHelper.startPage(pager.getCurrentPage(), pager.getPageSize());
            // 判断是否有分页
            if (ObjectHelper.isNotEmpty(pager.getDirection())
                    && ObjectHelper.isNotEmpty(pager.getProperties())) {
                specification.addOrderBy(pager.getProperties(),
                        pager.getDirection());
            }
            // 判断是否存在逻辑删除筛选
            String sqlStr = specification.sql();
            if (sqlStr.indexOf("deleted") == -1) {
                specification.eq("deleted", "0");
            }
            resultPage = this.sysLoginMapper.page(specification.sql());
        } catch (Exception e) {
            result = Result.newFailure("数据错误", "在获取分页列表时发生异常。");
            log.error(SimpleLogFormater.formatException(result.getMessage(), e));
            return result;
        }

2. Mapper.java 书写,查询条件非Map对象,直接就是SQL语句了;

    /**
     * 分页查询数据
     * 
     * @return
     */
    Page<T> page(String sqlStr);

3. 关于XML的配置,会拼装SQL语句

 

附:SQL拼装工具类

/** 
 * @Description: (用一句话描述该文件做什么) 
 * @author heliang 
 * @date 2018-7-6 下午6:43:42 
 * @version V2.1 
 */

package com.onem2.base.common;

import com.onem2.base.helper.ObjectHelper;

/**
 * @ClassName: Specification
 * @Description: (这里用一句话描述这个类的作用)
 * @author heliang
 * @date 2018-7-6 下午6:43:42
 * @version V2.1 * Update Logs: * Name: * Date: * Description: 初始化
 */

public class Specification {

    private StringBuilder where = new StringBuilder();
    private String groupBy;
    private String having;
    private String orderBy;

    public StringBuilder getWhere() {
        return where;
    }

    public void setWhere(StringBuilder where) {
        this.where = where;
    }

    public String getGroupBy() {
        return groupBy;
    }

    public void setGroupBy(String groupBy) {
        this.groupBy = groupBy;
    }

    public String getHaving() {
        return having;
    }

    public void setHaving(String having) {
        this.having = having;
    }

    public String getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    public Specification addOrderBy(String sort, String order) {
        if (!isEmpty(sort) && !isEmpty(order)) {
            this.orderBy = ObjectHelper.underscoreName(sort) + " " + order;
        }
        return this;
    }

    public Specification orLike(String value, String columns) {
        if (!isEmpty(value)) {
            StringBuffer strBuf = new StringBuffer("");
            for (String column : columns.split(",")) {
                strBuf.append(ObjectHelper.underscoreName(column) + " like '%"
                        + value + "%' or ");
            }
            String orLikeStr = strBuf.substring(0, strBuf.lastIndexOf("or"));
            where.append(" and (" + orLikeStr + ")");
        }
        return this;
    }

    public Specification eq(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column) + " = '"
                    + sqlParam(value) + "'");
        }
        return this;
    }

    public Specification ne(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " != '" + sqlParam(value) + "'");
        }
        return this;
    }

    public Specification like(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " like '%" + sqlParam(value) + "%'");
        }
        return this;
    }

    public Specification notLike(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " not like '%" + sqlParam(value) + "%'");
        }
        return this;
    }

    public Specification in(String column, String... values) {
        if (!isEmpty(values)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " in (" + inValuesString(values) + ")");
        }
        return this;
    }

    public Specification notIn(String column, String... values) {
        if (!isEmpty(values)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " not in (" + inValuesString(values) + ")");
        }
        return this;
    }

    public Specification gt(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column) + " > '"
                    + sqlParam(value) + "'");
        }
        return this;
    }

    public Specification gte(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " >= '" + sqlParam(value) + "'");
        }
        return this;
    }

    public Specification lt(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column) + " < '"
                    + sqlParam(value) + "'");
        }
        return this;
    }

    public Specification lte(String column, String value) {
        if (!isEmpty(value)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " <= '" + sqlParam(value) + "'");
        }
        return this;
    }

    public Specification between(String column, String from, String to) {
        if (isEmpty(from) && isEmpty(to)) {
            return this;
        }
        if (isEmpty(to)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " >= '" + sqlParam(from) + "'");
        } else if (isEmpty(from)) {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " <= '" + sqlParam(to) + "'");
        } else {
            where.append(" and " + ObjectHelper.underscoreName(column)
                    + " between '" + sqlParam(from) + "' and '" + sqlParam(to)
                    + "'");
        }
        return this;
    }

    public String sql() {
        StringBuilder sql = new StringBuilder("");
        final int a = 4;
        final int b = 5;
        if (where.length() > a) {
            sql.append(" " + where.substring(b));
        }
        if (!isEmpty(groupBy)) {
            sql.append(" group by " + groupBy);
        }
        if (!isEmpty(having)) {
            sql.append(" having " + having);
        }
        if (!isEmpty(orderBy)) {
            sql.append(" order by " + orderBy);
        }
        return sql.toString();
    }

    public String toString() {
        return sql();
    }

    private static boolean isEmpty(String value) {
        return value == null || "".equals(value) || value.trim().length() == 0;
    }

    private static boolean isEmpty(String[] values) {
        if (values == null || values.length == 0) {
            return true;
        }
        for (String value : values) {
            if (!isEmpty(value)) {
                return false;
            }
        }
        return true;
    }

    private static String inValuesString(String[] values) {
        StringBuilder string = new StringBuilder();
        for (String value : values) {
            if (isEmpty(value)) {
                continue;
            }
            string.append('\'');
            string.append(value);
            string.append('\'');
            string.append(',');
        }
        if (string.length() > 0) {
            string.deleteCharAt(string.length() - 1);
        }
        return string.toString();
    }

    private static String sqlParam(String sqlParam) {
        return sqlParam.replaceAll("([';]+|(--)+)", "");
    }
}

附:ObjectHelper 工具源码:

package com.onem2.base.helper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Object帮助类 功能:此类提供处理 <Object>对象一系列方法
 * 
 * @author 贺亮
 * 
 */
public class ObjectHelper {

    /**
     * 将id数组转换为id集合
     * 
     * @param ids
     * @return
     */
    public static List<Long> initIds(String[] ids) {
        List<Long> list = new ArrayList<Long>();
        list.add(-1L);
        for (int i = 0; i < ids.length; i++) {
            list.add(Long.valueOf(ids[i]));
        }
        return list;
    }

    /**
     * 组装条件
     * 
     * @param str
     * @return
     */
    public static List<String> strToList(String str) {
        if (isEmpty(str)) {
            return null;
        }
        String[] strs = str.split(",");
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < strs.length; i++) {
            list.add(strs[i]);
        }
        return list;
    }

    /**
     * 判断这个Object是否为Null或长度为0
     * 
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).isEmpty();
        }

        if (obj instanceof String) {
            return ((String) obj).equalsIgnoreCase("null")
                    | ((String) obj).trim().toString().equals("");
        }

        if (obj instanceof StringBuffer) {
            return ((StringBuffer) obj).length() == 0;
        }

        if (obj.getClass().isArray()) {
            try {
                Object[] a = (Object[]) obj;

                boolean b = true;
                for (Object o : a) {
                    b = b & isEmpty(o);

                    if (!b) {
                        break;
                    }
                }

                return b;
            } catch (ClassCastException e) {
            }
        }
        return false;
    }

    /**
     * 判断这个Object是否不为Null或长度不为0
     * 
     * @param obj
     * @return
     */
    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

    /**
     * 返回首字母大写单词
     * 
     * @param str
     * @return
     */
    public static String lcyFirstLetterToUpper(String str) {
        return str.replaceFirst(str.substring(0, 1), str.substring(0, 1)
                .toUpperCase());
    }

    /**
     * 转换为下划线
     * 
     * @param camelCaseName
     * @return
     */
    public static String underscoreName(String camelCaseName) {
        StringBuilder result = new StringBuilder();
        if (camelCaseName != null && camelCaseName.length() > 0) {
            result.append(camelCaseName.substring(0, 1).toLowerCase());
            for (int i = 1; i < camelCaseName.length(); i++) {
                char ch = camelCaseName.charAt(i);
                if (Character.isUpperCase(ch)) {
                    result.append("_");
                    result.append(Character.toLowerCase(ch));
                } else {
                    result.append(ch);
                }
            }
        }
        return result.toString();
    }

    /**
     * 转换为驼峰
     * 
     * @param underscoreName
     * @return
     */
    public static String camelCaseName(String underscoreName) {
        StringBuilder result = new StringBuilder();
        if (underscoreName != null && underscoreName.length() > 0) {
            boolean flag = false;
            for (int i = 0; i < underscoreName.length(); i++) {
                char ch = underscoreName.charAt(i);
                if ("_".charAt(0) == ch) {
                    flag = true;
                } else {
                    if (flag) {
                        result.append(Character.toUpperCase(ch));
                        flag = false;
                    } else {
                        result.append(ch);
                    }
                }
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(underscoreName("loginName"));
    }
}

 

这样就可以做到动态生成查询条件,复杂的查询条件也不会去改动XML配置了。

 

 

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值