All Downloads are FREE. Search and download functionalities are using the official Maven repository.

tools.c3p0.orm.OrmUtil Maven / Gradle / Ivy

There is a newer version: 0.2.2
Show newest version
package tools.c3p0.orm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.xml.XmlUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class OrmUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrmUtil.class);

    private static XmlUtil xmlInstance = null;
    private static JSONObject jsonObject = null;

    public static void setXmlMapperPath(String xmlMapperPath){
        if (xmlMapperPath.startsWith("src")){
            xmlInstance = XmlUtil.getXMLInstance(xmlMapperPath);
        } else {
            xmlInstance = XmlUtil.getNewInstance();
            xmlInstance.loadFromResource(xmlMapperPath);
        }
    }

    public static JSONObject analyzeDbXml(){
        if (xmlInstance == null){
            LOGGER.error("请先设置mapperXmlPath。");
            return null;
        }
        Element xmlRootEle = xmlInstance.getRootElement();
        LOGGER.info("xmlRootEle name is {}", xmlRootEle.getName());
        String xmlNameSpace = xmlRootEle.attribute("namespace").getValue();
        LOGGER.info("xmlRootEle namespace is {}", xmlNameSpace);
        jsonObject = new JSONObject(true);
        jsonObject.put("namespace", xmlNameSpace);
        boolean selectFlag = xmlInstance.containsElement(xmlRootEle, "select");
        boolean insertFlag = xmlInstance.containsElement(xmlRootEle, "insert");
        boolean updateFlag = xmlInstance.containsElement(xmlRootEle, "update");

        if (selectFlag){
            List selectList = xmlInstance.getSubElementsByName(xmlRootEle, "select");
            if (selectList != null && !selectList.isEmpty()){
                jsonObject.put("select", eleListToJSONArray(selectList, xmlInstance));
            } else {
                LOGGER.warn("Xml 文件中没有 select 标签。");
            }
        }
        if (insertFlag){
            List insertList = xmlInstance.getSubElementsByName(xmlRootEle, "insert");
            if (insertList != null && !insertList.isEmpty()){
                jsonObject.put("insert", eleListToJSONArray(insertList, xmlInstance));
            } else {
                LOGGER.warn("Xml 文件中没有 insert 标签。");
            }
        }
        if (updateFlag){
            List updateList = xmlInstance.getSubElementsByName(xmlRootEle, "update");
            if (updateList != null && !updateList.isEmpty()){
                jsonObject.put("update", eleListToJSONArray(updateList, xmlInstance));
            } else {
                LOGGER.warn("Xml 文件中没有 update 标签。");
            }
        }

        return jsonObject;
    }

    private static JSONArray eleListToJSONArray(List elementList, XmlUtil xmlInstance){
        if (elementList != null && !elementList.isEmpty()){
            JSONArray jsonArray = new JSONArray();
            for (Element selectEle : elementList){
                JSONObject selectObject = new JSONObject();
                selectObject.put("attribute", JSON.parseObject(JSON.toJSONString(xmlInstance.getAttributeInfo(selectEle))));
                selectObject.put("text", selectEle.getText());
                selectObject.put("id", selectEle.attribute("id").getValue());
                jsonArray.add(selectObject);
            }
            return jsonArray;
        } else {
            return null;
        }
    }

    @Deprecated
    public static String getSQL(String id, JSONObject jsonObject) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        if (id.startsWith("select")){
            JSONArray selectJSONArray = jsonObject.getJSONArray("select");
            for (JSONObject currJSONObj : selectJSONArray.toJavaList(JSONObject.class)){
                if (id.contentEquals(currJSONObj.getString("id"))){
                    return currJSONObj.getString("text");
                } else {
                    LOGGER.error("[错误]:您输入的方法{},未能在指定的XML文件中找到。", id);
                    return "";
                }
            }
        } else if (id.startsWith("insert")){
            JSONArray insertJSONArray = jsonObject.getJSONArray("insert");
            for (JSONObject currJSONObj : insertJSONArray.toJavaList(JSONObject.class)){
                if (id.contentEquals(currJSONObj.getString("id"))){
                    return currJSONObj.getString("text");
                } else {
                    LOGGER.error("[错误]:您输入的方法{},未能在指定的XML文件中找到。", id);
                    return "";
                }
            }
        } else if (id.startsWith("update")){
            JSONArray updateJSONArray = jsonObject.getJSONArray("update");
            for (JSONObject currJSONObj : updateJSONArray.toJavaList(JSONObject.class)){
                if (id.contentEquals(currJSONObj.getString("id"))){
                    return currJSONObj.getString("text");
                } else {
                    LOGGER.error("[错误]:您输入的方法{},未能在指定的XML文件中找到。", id);
                    return "";
                }
            }
        } else {
            LOGGER.warn("[警告]:您输入的方法名非法。(要求方法名必须以select、insert、update开头。)");
            return "";
        }
        return "";
    }

    @Deprecated
    private static String analyzeParam(String sql, Map paramMap){
        if (!sql.contains("#{")){
            LOGGER.info("SQL 不包括 参数。");
            return sql.trim();
        }else {
            int index = 0;
            String realSql = sql.trim();
            String content = realSql;
            StringBuilder finalSqlBuilder = new StringBuilder();
            while (index < realSql.length()) {
//                LOGGER.info("index={},realSql.length={}", index, realSql.length());
                if (content.contains("#{")) {
                    int indexOfStart = realSql.indexOf("#{", index);
                    finalSqlBuilder.append(realSql.substring(index, indexOfStart));
                    int indexOfEnd = realSql.indexOf("}", indexOfStart);
                    String paramVal = realSql.substring(indexOfStart + 2, indexOfEnd);
                    String key = "";
                    if (paramVal.contains(",")) {
                        key = paramVal.trim().split(",")[0];
                    } else {
                        key = paramVal.trim();
                    }
                    String value = paramMap.getOrDefault(key, null).toString();
//                    LOGGER.info("key:value = {}:{}", key, value);
                    finalSqlBuilder.append(value);
                    index = indexOfEnd + 1;
                    content = realSql.substring(index);
                } else {
                    finalSqlBuilder.append(realSql.substring(index));
                }
                LOGGER.info("index={},realSql.length={}", index, realSql.length());
            }
            return finalSqlBuilder.toString();
        }
    }

    private static Map getStmtAndParamsForSelect(String sql, Map paramMap){
        Map stmtParamMap = new HashMap<>();
        List paramsList = new ArrayList<>();
        if (!sql.contains("#{")){
            LOGGER.info("SQL 不包括 参数。");
            stmtParamMap.put("Statement", sql.trim());
            return stmtParamMap;
        }else {
            int index = 0;
            String realSql = sql.trim();
            String content = realSql;
            StringBuilder finalSqlBuilder = new StringBuilder();
            while (content.contains("#{")) {
//                LOGGER.info("index={},realSql.length={}", index, realSql.length());
                int indexOfStart = realSql.indexOf("#{", index);
                finalSqlBuilder.append(realSql.substring(index, indexOfStart));
                int indexOfEnd = realSql.indexOf("}", indexOfStart);
                String paramVal = realSql.substring(indexOfStart + 2, indexOfEnd);
                String key = "";
                if (paramVal.contains(",")) {
                    key = paramVal.trim().split(",")[0];
                } else {
                    key = paramVal.trim();
                }
                Object value = paramMap.getOrDefault(key, null);
//                LOGGER.info("key:value = {}:{}", key, value);
                paramsList.add(value);
                finalSqlBuilder.append("?");
                index = indexOfEnd + 1;
                content = realSql.substring(index);
            }
            finalSqlBuilder.append(realSql.substring(index));
            LOGGER.info("index={},realSql.length={}", index, realSql.length());
            LOGGER.info("PreparedStatement = {}, Parameters = {}", finalSqlBuilder.toString(), paramsList);
            stmtParamMap.put("PreparedStatement", finalSqlBuilder.toString());
            stmtParamMap.put("Parameters", paramsList);
            return stmtParamMap;
        }
    }

    private static Map getStmtAndParamsForInsert(String sql, Object parameter){
        Map stmtParamMap = new HashMap<>();
        List paramsList = new ArrayList<>();
        if (!sql.contains("#{")){
            LOGGER.info("SQL 不包括 参数。");
            stmtParamMap.put("Statement", sql.trim());
            return stmtParamMap;
        }else {
            int index = 0;
            String realSql = sql.trim();
            String content = realSql;
            StringBuilder finalSqlBuilder = new StringBuilder();
            JSONObject paramJSONObject = JSON.parseObject(JSON.toJSONString(parameter));
            while (content.contains("#{")) {
//                LOGGER.info("index={},realSql.length={}", index, realSql.length());
                int indexOfStart = realSql.indexOf("#{", index);
                finalSqlBuilder.append(realSql.substring(index, indexOfStart));
                int indexOfEnd = realSql.indexOf("}", indexOfStart);
                String paramVal = realSql.substring(indexOfStart + 2, indexOfEnd);
                String key = "";
                if (paramVal.contains(",")) {
                    key = paramVal.trim().split(",")[0];
                } else {
                    key = paramVal.trim();
                }
                Object value = paramJSONObject.get(key);
//                LOGGER.info("key:value = {}:{}", key, value);
                paramsList.add(value);
                finalSqlBuilder.append("?");
                index = indexOfEnd + 1;
                content = realSql.substring(index);
            }
            finalSqlBuilder.append(realSql.substring(index));
            LOGGER.info("index={},realSql.length={}", index, realSql.length());
            LOGGER.info("PreparedStatement = {}, Parameters = {}", finalSqlBuilder.toString(), paramsList);
            stmtParamMap.put("PreparedStatement", finalSqlBuilder.toString());
            stmtParamMap.put("Parameters", paramsList);
            return stmtParamMap;
        }
    }

    public static Map analyzeSql(String sql, String parameterType, Object parameter){
        if ("java.util.Map".contentEquals(parameterType) && (parameter instanceof Map)){
            return getStmtAndParamsForSelect(sql, (Map) parameter);
        } else if (!(parameterType.startsWith("java.") || parameterType.startsWith("javax."))){
            return getStmtAndParamsForInsert(sql, parameter);
        }
        return null;
    }

    public static JSONObject getSqlInfo(String id) {
        if (id.startsWith("select")){
            JSONArray selectJSONArray = jsonObject.getJSONArray("select");
            for (JSONObject currJSONObj : selectJSONArray.toJavaList(JSONObject.class)){
                if (id.contentEquals(currJSONObj.getString("id"))){
                    return currJSONObj;
                }
            }
            LOGGER.error("[错误]:您输入的方法{},未能在指定的XML文件中找到。", id);
            return null;
        } else if (id.startsWith("insert")){
            JSONArray insertJSONArray = jsonObject.getJSONArray("insert");
            for (JSONObject currJSONObj : insertJSONArray.toJavaList(JSONObject.class)){
                if (id.contentEquals(currJSONObj.getString("id"))){
                    return currJSONObj;
                }
            }
            LOGGER.error("[错误]:您输入的方法{},未能在指定的XML文件中找到。", id);
            return null;
        } else if (id.startsWith("update")){
            JSONArray updateJSONArray = jsonObject.getJSONArray("update");
            for (JSONObject currJSONObj : updateJSONArray.toJavaList(JSONObject.class)){
                if (id.contentEquals(currJSONObj.getString("id"))){
                    return currJSONObj;
                }
            }
            LOGGER.error("[错误]:您输入的方法{},未能在指定的XML文件中找到。", id);
            return null;
        } else {
            LOGGER.warn("[警告]:您输入的方法名非法。(要求方法名必须以select、insert、update开头。)");
            return null;
        }
    }

    public static  List  mapResultToBean(String id, ResultSet resultSet, Class targetClazz) throws SQLException {
        if (id.startsWith("select")){
            JSONArray selectJSONArray = jsonObject.getJSONArray("select");
            for (JSONObject currJSONObj : selectJSONArray.toJavaList(JSONObject.class)){
                if (id.contentEquals(currJSONObj.getString("id"))){
                    String resultMapName = currJSONObj.getJSONObject("attribute").getString("resultMap");
                    List resultMapEleList = xmlInstance.getSubElementsByName(xmlInstance.getRootElement(), "resultMap");
                    if (resultMapEleList != null && !resultMapEleList.isEmpty()){
                        for (Element resultMapEle : resultMapEleList){
                            if (resultMapName.contentEquals(resultMapEle.attribute("id").getValue())){
                                LOGGER.info("在XML文件中找到了对应的resultMap标签。");
                                List javaObjectList = new ArrayList<>();
                                Map> columnAttrMap = analyzeResultMapElement(resultMapEle);
                                while (resultSet.next()){
                                    JSONObject javaBeanObject = new JSONObject(true);
                                    for (Map.Entry> entry : columnAttrMap.entrySet()){
                                        String jdbcType = entry.getValue().get("jdbcType");
                                        if ("INTEGER".contentEquals(jdbcType)){
                                            javaBeanObject.put(entry.getValue().get("property"), resultSet.getInt(entry.getKey()));
                                        } else if ("VARCHAR".contentEquals(jdbcType)){
                                            javaBeanObject.put(entry.getValue().get("property"), resultSet.getString(entry.getKey()));
                                        } else {
                                            javaBeanObject.put(entry.getValue().get("property"), resultSet.getObject(entry.getKey()));
                                        }
                                    }
                                    javaObjectList.add(JSON.parseObject(JSON.toJSONString(javaBeanObject), targetClazz));
                                }
                                return javaObjectList;
                            }
                        }
                    } else {
                        LOGGER.warn("[警告]:在指定的XML文件中找到 resultMap 标签。");
                        return new ArrayList<>();
                    }
                } else {
                    LOGGER.error("[错误]:您输入的方法{},未能在指定的XML文件中找到。", id);
                    return new ArrayList<>();
                }
            }
        }
        return new ArrayList<>();
    }

    private static Map> analyzeResultMapElement(Element resultMapEle) {
        Map> map = new LinkedHashMap<>();
        if (xmlInstance.containsElement(resultMapEle, "id")){
            Element idEle = xmlInstance.getSubElementsByName(resultMapEle, "id").get(0);
            map.put(idEle.attributeValue("column"), xmlInstance.getAttributeInfo(idEle));
        }
        if (xmlInstance.containsElement(resultMapEle, "result")){
            List resultElements = xmlInstance.getSubElementsByName(resultMapEle, "result");
            for (Element resultEle : resultElements){
                map.put(resultEle.attributeValue("column"), xmlInstance.getAttributeInfo(resultEle));
            }
        }
        return map;
    }
}