반사3:java반사기술을 이용하여 조회결과를 대상으로 봉함

3185 단어 other
package cn.itcast.domain;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import cn.itcast.jdbc.JdbcUtils;

public class ORMTest {

    public static void main(String[] args) throws Exception {
        User user = getUser("select id as Id , name as Name , birthday as Birthday , money as Money from user where id = 1");
        System.out.println(user);
    }

    //  User , User 
    static User getUser(String sql) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            String[] colNames = new String[count];
            for (int i = 1; i <= count; i++) {
                colNames[i - 1] = rsmd.getColumnName(i);
            }

            User user = null;

            while (rs.next()) {
                user = new User();
                Method[] ms = user.getClass().getMethods();
                for (int i = 0; i < colNames.length; i++) {
                    String colName = colNames[i];
                    String methodName = "set" + colName; // set 
                    for (Method m : ms) {
                        if (methodName.equals(m.getName()))
                            m.invoke(user, rs.getObject(colName));
                    }
                }
            }
            return user;
        } finally {
            JdbcUtils.free(rs, ps, conn);
        }
    }
}

좋은 웹페이지 즐겨찾기