背景:准备通过 JDBC 查询数据库,然后将数据库内容转为实体类
问题现象:数据库字段属性为id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
,在 java 中 debug 发现类型变为 Long
不应该是 int 吗。。。

代码:

public static synchronized Object query(String sql, String tab) throws Exception {
        Class aClass = Class.forName("com.springbootdata.demo.dal.entity." + tab);
        List<Object> objects = new ArrayList<>();
        try {
            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = getConnection().createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            //获取列相关信息
            ResultSetMetaData rsm = rs.getMetaData();
            while (rs.next()) {
                Object obj = aClass.newInstance();
                for (int i = 1; i < rsm.getColumnCount(); i++) {
                    System.out.println("列名:" + rsm.getColumnLabel(i) + "\t列值:" + rs.getObject(i));
                    String fieldName = "set" + StringUtils.capitalize(getName(rsm.getColumnLabel(i)));
                    Method method = null;
                    if (rs.getObject(i) instanceof BigInteger) {
                        method = obj.getClass().getMethod(fieldName, Long.class);
                        method.invoke(obj, ((BigInteger)rs.getObject(i)).longValue());
                    } else if (rs.getObject(i) instanceof Timestamp) {
                        method = obj.getClass().getMethod(fieldName, java.util.Date.class);
                        method.invoke(obj, new java.util.Date(((Timestamp)rs.getObject(i)).getTime()));
                    } else if (rs.getObject(i) instanceof java.sql.Date) {
                        method = obj.getClass().getMethod(fieldName, java.util.Date.class);
                        method.invoke(obj, new java.util.Date(((java.sql.Date)rs.getObject(i)).getTime()));
                    } else {
                        method = obj.getClass().getMethod(fieldName, rs.getObject(i).getClass());
                        method.invoke(obj, rs.getObject(i));
                    }
                }
                objects.add(obj);
            }
            close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            close();
        }
        return objects;
    }


↙↙↙阅读原文可查看相关链接,并与作者交流