• java_jdbc_反射技术将查询结果封装为对象


    package cn.itcast.Reflect;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import cn.itcast.JdbcUtils;
    
    //反射获取数据库内容
    public class ORMTest {
    
    	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException, InstantiationException {
    
    		User2 user = (User2)getObject("select id as Id,username as Username,password as Password from t_user where id=1",User2.class);
    		System.out.println(user.getUsername());
    	}
    	
    	public static Object getObject(String sql,Class clazz) throws SQLException,
    			IllegalAccessException, IllegalArgumentException,
    			InvocationTargetException, InstantiationException {
    		Connection conn = null;
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		try {
    			conn = JdbcUtils.getConnection();
    			ps = conn.prepareStatement(sql);
    			rs = ps.executeQuery();
    
    			java.sql.ResultSetMetaData rsmd = rs.getMetaData();
    
    			int count = rsmd.getColumnCount();
    			String[] colNames = new String[count];
    
    			for (int i = 1; i <= count; i++) {
    				colNames[i - 1] = rsmd.getColumnLabel(i);
    
    			}
    
    			Object obj = null;
    			Method[] ms = clazz.getMethods();
    			if (rs.next()) {
    				obj = clazz.newInstance();
    				for (int i = 0; i < colNames.length; i++) {
    					String colName = colNames[i];
    					String methodName = "set" + colName;
    					
    					for (Method m : ms) {
    						if (methodName.equals(m.getName())) {
    							m.invoke(obj, rs.getObject(colName));
    						}
    					}
    
    				}
    			}
    			return obj;
    		} finally {
    			JdbcUtils.free(rs, ps, conn);
    		}
    	}
    }
    


     

  • 相关阅读:
    将博客搬至CSDN
    linux一部分常用的命令
    java实现qq邮箱每天定时发送邮件
    面向接口编程的小例子
    解决安装mysql的”A Windows service with the name MySQL already exists.“问题
    SpringCloud 随笔
    博客文章链接
    LocalDate与Date转化
    maven的配置以及使用
    windows系统下nginx+tomcat+redis做负载均衡和session粘滞附整套解决方案
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720418.html
Copyright © 2020-2023  润新知