JDBCTemplate converts the class into a table and inserts data

Table of Contents

    • background
    • Practical
      • create table
      • insert data
        • Notice:
    • Summarize

Background

The current requirement is to create a table in the database according to the text file of the class to obtain information such as type and attribute name.

Practice

Create table

General idea:
Obtain information such as attribute names and types in the class through reflection, and then form sql statements by concatenating strings, and use the JDBCTemplate.excute method to execute sql statements to achieve the table creation effect.

@Resource
private JdbcTemplate jdbcTemplate;

public static void main(String[] args) throws ClassNotFoundException {<!-- -->
        String classPath = "com.tfjybj.service.User";
        Class stu = Class. forName(classPath);
        List fieldsList = new ArrayList<Field[]>(); // Save the array of attribute objects to the list
        while (stu != null) {<!-- --> // traverse all parent class bytecode objects
            Field[] declaredFields = stu.getDeclaredFields(); // Get the attribute object array of the bytecode object
            fieldsList.add(declaredFields);

            stu = stu.getSuperclass(); // Get the bytecode object of the parent class
        }
        String classPathEnd = classPath. substring(classPath. lastIndexOf(".") + 1);
        StringBuffer stringSql = new StringBuffer();
        stringSql.append("create table " + classPathEnd + "(\r\\
") ;

        String sqlFieldType = "";
        String sqlFieldName = "";
        for (Object fields:fieldsList) {<!-- --> // Print multiple attribute objects of the current class and its parent class
            Field[] f = (Field[]) fields;
            for (Field field : f) {<!-- -->
                String type = field. getType(). toString();
                String typeEnd = type.substring(type.lastIndexOf(".") + 1);
                System.out.println(typeEnd);
                System.out.println(field.getName());
                sqlFieldName = field. getName();

                if(typeEnd == "String"){<!-- -->
                    sqlFieldType = "varchar(20)";
                }else if(typeEnd =="Long")
                {<!-- -->
                    sqlFieldType = "bigint(200)";
                } else {<!-- -->
                    sqlFieldType = "varchar(20)";
                }
                stringSql.append(sqlFieldName + " " + sqlFieldType + "," + "\r\\
");
            }
        }
        stringSql.deleteCharAt(stringSql.length()-3);
        stringSql.append("\\
)");
        String strEnd = stringSql. toString();
        System.out.println(strEnd);
    jdbcTemplate. execute(stringSQL);
    }

Insert data

Implementation idea:
The attribute in front of the insert statement corresponds to its real attribute value, so how to find the corresponding relationship Use spliced strings, find the get method, and reflect the corresponding attribute value of the object.

Class detailClass = user. getClass();
        List fieldsList = new ArrayList<Field[]>(); // Save the array of attribute objects to the list
        // while (detailClass != null) {<!-- --> // traverse all parent class bytecode objects
        Field[] declaredFields = detailClass.getDeclaredFields(); // Get the attribute object array of the bytecode object
        fieldsList.add(declaredFields);
        // detailClass = detailClass.getSuperclass(); // Get the bytecode object of the parent class
// }
        Map<String, String> map = new HashMap<>();
        String className = detailClass. getName();
        StringBuffer stringSql = new StringBuffer();
        stringSql.append("insert into " + "user" + " (");
        StringBuffer stringField = new StringBuffer();
        StringBuffer strWhat = new StringBuffer();
        StringBuffer endGoods = new StringBuffer();
        String sqlFieldType = "";
        String sqlFieldName = "";
        String fieldName1 = "";
// String endGoods = "";
       List<Object> args = new ArrayList<>();
        for (Object fields : fieldsList)
        {<!-- --> // Print the multi-attribute objects of the current class and its parent class
            Field[] f = (Field[]) fields;
            for (Field field : f)
            {<!-- -->
                String fieldname = field. getName();
                stringField.append(fieldname + ",");
                strWhat.append("?" + ",");
                fieldName1 = fieldname;
                fieldName1 = fieldName1.substring(0, 1).toUpperCase() + fieldName1.substring(1);
                String fieldMethod = "get" + fieldName1;
                Method method = detailClass. getMethod(fieldMethod);
                Object endThing = method. invoke(user);
                endGoods.append(""");
                endGoods.append(endThing);

                args. add(endThing);

                endGoods.append(""" + ",");
// endGoods.append(""" + endGoods + """ + ",");
// map.put(fieldname,endThing.toString());
            }
        }


        stringField. deleteCharAt(stringField. length() - 1);
        endGoods.deleteCharAt(endGoods.length() - 1);
        stringSql.append(stringField);
        stringSql.append(")");
        strWhat.deleteCharAt(strWhat.length() - 1);
        stringSql. append(" values " + "(");
        stringSql.append(strWhat);
        stringSql.append(")");

        System.out.println(stringSql.toString());
        System.out.println(endGoods.toString());
        String endGoodsStr = endGoods. toString();
        endGoodsStr = endGoodsStr. substring(1, endGoodsStr. length() - 1);

        List<String> detailValueList = new ArrayList<>();
        // String detailValue =
// String insertSql =
// //First splicing all the sql
// //Splice the input parameters
// // make the call
//
        String sql = stringSql.toString();
        System.out.println(sql);

// args[0]= "aaa";
// System.out.println(args);
// //Parameter 1: the SQL statement for inserting data, parameter 2: the corresponding placeholder in the SQL statement? parameters
        return jdbcTemplate. update(sql, args. toArray());


    }

Note:

When using JDBCTemplate to insert records, I encountered such a problem. I wanted to pass an array, but what I passed was a string. So when the JDBCTemplate method is called, an error will be reported.

The report cannot find the second parameter.
Below is ok.

In the end, it was found that a string was passed in, not an array.

The code is made and changed as follows:

You can plug in the library.

Summary

Learn the bottom layer.
1. List
Array
map
bottom layer
2. What does the [] in the array and the {} behind it mean? ? ? ?