【Java】xml转实体

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Francis123580/article/details/79977044

引言

因为项目中需要把webservice接口提供的数据直接保存下来,一般字段少的就直接遍历,然后合成SQL存到数据库;

但是有的提供了30多个字段,遍历拼接就很繁琐,所以,写了一个简单的xml转实体,然后根据实体生成SQL;

 

代码

xml 转 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 转 Object 和 Object 转 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();
    }

 

调用方式

//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");

 

小结

这里用到了反射,因为并不知道获取了一个字段需要调用哪个setter,但是还是有一定联系;

在合成SQL字段和数据库又不是完全一致,单词一样,命名规范不一样,所以也需要进行转化;

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页