[Java] xml to entity

introduction

Because the data provided by the webservice interface needs to be saved directly in the project, the general field is traversed directly, and then synthesized SQL is stored in the database;

However, some provide more than 30 fields, and it is very cumbersome to traverse and splicing, so I wrote a simple xml to entity, and then generated SQL according to the entity;

 

code

xml to list

StringReader sr = new StringReader(data);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;

builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
NodeList list = doc.getElementsByTagName("typ:ArRecUser");
for (int i = 0; i < list.getLength(); i++) {
    NodeList child = list.item(i).getChildNodes();
    .... some code ....
}

 

list to Object and Object to SQL

// Util - list转Object
    private Object xmlToObject(NodeList list, Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            for (int j = 0; j < list.getLength(); j++) {
                if (list.item(j).getNodeName().substring(4).equals(fields[i].getName())) {
                    try {
                        Method method = object.getClass().getDeclaredMethod("set" + upperCase(fields[i].getName()),
                                String.class);
                        method.invoke(object, list.item(j).getTextContent());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return object;
    }

    // Util - 首字母大写
    public String upperCase(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    // Util - 根据对象生成插入SQL
    private String careteInsertSqlByObject(Object object, String tableName) {
        String sql = "";
        StringBuilder sqlFields = new StringBuilder();
        StringBuilder sqlVaule = new StringBuilder();
        Field[] fields = object.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            sqlFields.append(changeUpper(fields[i].getName()) + ",");
            try {
                Method method = object.getClass().getDeclaredMethod("get" + upperCase(fields[i].getName()));
                String str = (String) method.invoke(object);
                sqlVaule.append("'" + str + "',");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        sql = "INSERT INTO " + tableName + "(" + sqlFields.toString().substring(0, sqlFields.length() - 1) + ") VALUES("
                + sqlVaule.toString().substring(0, sqlVaule.length() - 1) + ")";
        return sql;
    }

    // Util - 根据对象生成更新sql
    private String careteUpdateSqlByObject(Object object, String tableName, HashMap<String, String> condition) {
        String sql = "";
        StringBuilder sqlSet = new StringBuilder();
        StringBuilder sqlWhere = new StringBuilder();

        Field[] fields = object.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            String value = "";
            try {
                Method method = object.getClass().getDeclaredMethod("get" + upperCase(fields[i].getName()));
                value = (String) method.invoke(object);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sqlSet.append(changeUpper(fields[i].getName()) + " = '" + value + "',");
        }

        Iterator<String> iterator = condition.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String val = condition.get(key);
            sqlWhere.append(" " + key + " = '" + val + "' AND");
        }

        sql = "UPDATE " + tableName + " SET " + sqlSet.toString().substring(0, sqlSet.length() - 1) + " WHERE "
                + sqlWhere.toString().substring(0, sqlWhere.length() - 3);
        return sql;
    }

    // Util - 大写转小写
    private String changeUpper(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (Character.isUpperCase(str.charAt(i))) {
                sb.append("_" + String.valueOf(str.charAt(i)).toLowerCase());
            } else {
                sb.append(str.charAt(i));
            }
        }
        return sb.toString();
    }

 

call method

//list转Object
Object userEntity = new revenueEntity();
Object object = xmlToObject(child, userEntity);

//Object赋值到具体的实体,对某些字段重新赋值
userEntity user = new userEntity();
BeanUtils.copyProperties(user, object);
user.setDate(date);

//根据实体合成UpdateSQL
HashMap<String, String> condition = new HashMap<String, String>();
condition.put("id", revenue.getId());
String sql_update = careteUpdateSqlByObject(user, "user_table", condition);

//根据实体合成InsertSQL
String sql_insert = careteInsertSqlByObject(user, "user_table");

 

summary

Reflection is used here, because I don't know which setter to call to get a field, but there is still a certain connection;

The synthetic SQL fields and the database are not exactly the same, the words are the same, and the naming conventions are different, so they also need to be converted;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325446787&siteId=291194637