码迷,mamicode.com
首页 > 数据库 > 详细

JDBC操作数据封装Java Bean

时间:2021-05-24 10:40:20      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:exe   cut   info   def   ring   getc   while   mapper   tor   

            Connection conn = DriverManager.getConnection(dbURL, properties);
            if (conn != null) {
                Statement statement = conn.createStatement();
                ResultSet resultSet = statement.executeQuery("  select * from student");

                BeanInfo beanInfo = Introspector.getBeanInfo(Student.class, Object.class);

                while (resultSet.next()) {
                    Student student = new Student();
                    for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
                        String propertyName = propertyDescriptor.getName();//属性名
                        Class<?> propertyType = propertyDescriptor.getPropertyType();//属性类型
                        String columnName = getTableMapperColumnName(propertyName);
                        String resultMethodStr = getResultMethod(propertyType.toString());//结果集取数方法
                        Method resultMethod = ResultSet.class.getMethod(resultMethodStr, String.class);
                        Object columnValue = resultMethod.invoke(resultSet, columnName);//结果集的值

                        Method writeMethod = propertyDescriptor.getWriteMethod();//Setter
                        writeMethod.invoke(student, columnValue);

                    }
                    System.out.println(student.toString());
                }

            }
    private static String getTableMapperColumnName(String propertyName) {
        if (propertyName.equals("firstName")) {
            return "first_name";
        } else if (propertyName.equals("lastName")) {
            return "last_name";
        } else {
            return propertyName;
        }
    }

    private static String getResultMethod(String propertyType) {

        //return "get"+propertyType.substring(0,1).toUpperCase()+propertyType.substring(1,propertyType.length());
        switch (propertyType) {
            case "Integer":
                return "getInteger";
            case "int":
                return "getInt";
            case "String":
                return "getString";
            case "Long":
                return "getLong";
            default:
                return "getString";
        }

    }

JDBC操作数据封装Java Bean

标签:exe   cut   info   def   ring   getc   while   mapper   tor   

原文地址:https://www.cnblogs.com/lanqie/p/14771760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!