读取项目中json配置文件并动态拼接sql

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.config.utils.IOUtils;

import java.io.InputStream;
import java.util.*;

public class Demo3 {
    private static Map> modelMap = new LinkedHashMap>();
    public static JSONObject fileToJson() {
        JSONObject json = null;
        try (
           //InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("package.json");
             InputStream is = ClassLoader.getSystemResourceAsStream("package.json");
        ) {
            json = JSONObject.parseObject(IOUtils.toString(is, "utf-8"));
        } catch (Exception e) {
            System.out.println(e);
        }
        return json;
    }

    public static String getSql(String tableName, Map params, List list) {
        if (modelMap.get(0) == null) {
            Map map = new LinkedHashMap<>();
            for (String key : fileToJson().keySet()) {
                String str = fileToJson().get(key).toString();
                map = (Map) JSONObject.parse(str);
                modelMap.put(key, map);
            }
        }
        String insert = "insert into " + tableName;
        String colums = "(";
        String values = "(";
        Map map = modelMap.get(tableName);
        for (String key : map.keySet()) {
            colums = colums + map.get(key) + ",";
            values = values + "?" + ",";
            list.add(params.get(key));
        }
        colums = colums.substring(0, colums.length() - 1) + ")";
        values = values.substring(0, values.length() - 1) + ")";
        return insert + colums + "  values" + values;
    }

    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("XH", "11111");
        map.put("WJ", "22222");
        List list = new LinkedList<>();
        System.out.println(getSql("rws", map, list));
        for (String str : list) {
            System.out.println(str);
        }
    }
}
//映射
{
  "rws": {"XH":"D_XH","WJ": "D_WJ"},
  "sjbg": {"XH":"D_XH","WJ": "D_FJ"}
}

你可能感兴趣的:(读取项目中json配置文件并动态拼接sql)