根据给定对象生成查询sql语句(工具类,练习版)

给定任意对象,解析非空字段作为查询条件,生成普通查询语句。

  • 未解析结果
  • 表名解析应解析实体类上@Table注解,此处练习仅解析类名
  • 示例代码生成结果
    • SELECT PAYBO.MERCHANT_ORDER, PAYBO.PAYMENT_ORDER, PAYBO.CHANNEL_TRADE, PAYBO.PAY, PAYBO.PAY_WAY FROM PAYBO WHERE PAYBO.CHANNEL_TRADE = '0000000' AND PAYBO.PAY = '123456' AND PAYBO.PAY_WAY = '11111';
import lombok.SneakyThrows;
import org.apache.commons.collections4.MapUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 2023/7/7 15:04
 *
 * @author radish.r.40@gmail.com
 */
public class Demo {
    @SneakyThrows
    private String toSql(Object obj) {
        Class<?> aClass = obj.getClass();
        String tableName = aClass.getName();
        Field[] declaredFields = aClass.getDeclaredFields();
        Set<String> nameSet = new HashSet<>();
        Map<String, Object> paramMap = new HashMap<>();
        for (Field field : declaredFields) {
            String n = field.getName();
            StringBuilder name = new StringBuilder();
            int index = 0;
            for (int i = 0; i < n.length(); i++) {
                // 驼峰命名解析为下划线命名
                if (n.charAt(i) >= 65 && n.charAt(i) <= 65 + 26) {
                    if (index != 0) {
                        name.append("_");
                    }
                    name.append(n, index, i);
                    index = i;
                }
            }
            // 查询字段
            nameSet.add(name.toString().toLowerCase());
            String methodNameEnd = n.substring(0, 1).toUpperCase() + n.substring(1);
            Method method = aClass.getMethod("get" + methodNameEnd);
            Object value = method.invoke(obj);
            if (value != null) {
                paramMap.put(name.toString().toLowerCase(), value);
            }
        }
        return getSql(tableName, nameSet, paramMap);
    }


    private String getSql(String tableName, Set<String> filedName, Map<String, Object> paramMap) {
        tableName = tableName.substring(tableName.contains(".") ? tableName.lastIndexOf(".") + 1 : 0);
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        // 字段值
        Iterator<String> iterator = filedName.iterator();
        while (iterator.hasNext()) {
            String name = iterator.next();
            sql.append(tableName).append(".").append(name);
            if (iterator.hasNext()) {
                sql.append(",");
            }
            sql.append(" ");
        }
        // 表名
        sql.append("FROM ").append(tableName).append(" ");

        // where 条件
        if (MapUtils.isNotEmpty(paramMap)) {
            sql.append("WHERE ");
            Iterator<Map.Entry<String, Object>> entryIterator = paramMap.entrySet().iterator();
            while (entryIterator.hasNext()) {
                Map.Entry<String, Object> entry = entryIterator.next();
                String field = entry.getKey();
                Object value = entry.getValue();
                sql.append(tableName).append(".").append(field).append(" ").append("=")
                        .append(" ").append("'").append(value).append("'");
                if (entryIterator.hasNext()) {
                    sql.append(" ").append("AND").append(" ");
                } else {
                    sql.append(";");
                }
            }

        }
        return sql.toString().toUpperCase();
    }

    public static void main(String[] args) {
        PayBO bo = new PayBO();
        bo.setPayTime(new Date());
        bo.setPayDetail("123456");
        bo.setChannelTradeNo("0000000");
        bo.setPayWayCode("11111");
        String s = new Demo().toSql(bo);
        System.out.println(s);
    }
}

posted @ 2023-07-07 16:35  萝卜不会抛异常  阅读(52)  评论(0编辑  收藏  举报