利用反射生成Insert语句

 或许大家都会遇到写insert插入语句,会出现丢字段什么的问题, 但是我们呢可以通过给出一个实体类直接生成Insert语句,接下来我分享一下

public static String getSaveObjectSql(Object object) {
        // 定义一个sql字符串
        String sql = "insert into ";
        // 得到对象的类
        Class c = object.getClass();
        System.out.println("对象名是"+c.getName());
        // 得到对象中所有的方法
        Method[] methods = c.getMethods();
        // 得到对象中所有的属性
        Field[] fields = c.getFields();
        // 得到对象类的名字
        String cName = c.getName();
        // 从类的名字中解析出表名
        String tableName = cName.substring(cName.lastIndexOf(".") + 1,
                cName.length());
        sql += tableName + "(";
        List<String> mList = new ArrayList<String>();
        List vList = new ArrayList();
        for (Method method : methods) {
            String mName = method.getName();
            if (mName.startsWith("get") && !mName.startsWith("getClass")) {
                String fieldName = mName.substring(3, mName.length());
                mList.add(fieldName);
                System.out.println("字段名字----->" + fieldName);
                try {
                    Object value = method.invoke(object, null);

                    System.out.println("执行方法返回的值:" + value);
                    if (value instanceof String) {
                        vList.add("\'" + value + "\'");
                        System.out.println("字段值------>" + value);
                    } else {
                        vList.add(value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        for (int i = 0; i < mList.size(); i++) {
            if (i < mList.size() - 1) {
                sql += mList.get(i) + ",";
            } else {
                sql += mList.get(i) + ") values(";
            }
        }
        for (int i = 0; i < vList.size(); i++) {
            if (i < vList.size() - 1) {
                sql += vList.get(i) + ",";
            } else {
                sql += vList.get(i) + ")";
            }
        }

        return sql;
    }

注意   类名和表名的一致性, (大小写可以不一样)  

          列名和属性的一致性,(大小写可以不一样)

人无完人   所以我们的方法也不是可以适合所以的情况, 使用的时候注意

谢谢大家!  希望对大家有一定的帮助!

猜你喜欢

转载自www.cnblogs.com/514929hgy/p/9144710.html