将JDBC结果集转换成实体对象

第一步:在JDBC工具类中加入转换方法,用于结果集转换成对象

package lo.utils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * JDBC 工具类
 * @author pengYi
 *
 */
public class JDBCUtils {
	
	 public static Connection connection = null;
	 public static PreparedStatement preparedStatement = null;
	 public static ResultSet resultSet = null;
	 	
	 /**
	  * 连接数据库
	  * @return
	  */
	 public static Connection getConnection(){
		 String url = "jdbc:mysql://localhost:3306/chartroom";
		 String user = "root";
		 String password = "root";
		 try {
			 Class.forName("com.mysql.jdbc.Driver");
			 connection = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		 return connection;
	 }
	 /**
	  * 关闭资源
	  */
	 public static void close(){
		 try{
			 if(connection != null){
				connection.close();	
				connection = null;
			 }
			 if(preparedStatement != null){
				 preparedStatement.close();
				 preparedStatement = null;
			 }
			 if(resultSet!= null){
				 resultSet.close();
				 resultSet = null;
			 }
		 }catch(SQLException e){
			 e.printStackTrace();
		 }
		
	 }
	 /**
	  * 将结果集转换成实体对象集合
	  * @param res 结果集
	  * @param c 实体对象映射类
	  * @return
	 * @throws SQLException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	  */
	 public static List Populate(ResultSet rs,Class cc) throws SQLException, InstantiationException, IllegalAccessException{
		
		 //结果集 中列的名称和类型的信息
		 ResultSetMetaData rsm = rs.getMetaData();
		 int colNumber = rsm.getColumnCount();
		 List list = new ArrayList();
		 Field[] fields = cc.getDeclaredFields();
		
		 //遍历每条记录
		 while(rs.next()){
			 //实例化对象
			 Object obj = cc.newInstance(); 
			 //取出每一个字段进行赋值
			 for(int i=1;i<=colNumber;i++){
				 Object value = rs.getObject(i);
				 //匹配实体类中对应的属性
				 for(int j = 0;j<fields.length;j++){
					 Field f = fields[j];
					 if(f.getName().equals(rsm.getColumnName(i))){
						 boolean flag = f.isAccessible();
						 f.setAccessible(true);
						 f.set(obj, value);
						 f.setAccessible(flag);
						 break;
					 }
				 }
				 
			 }
			 list.add(obj);
		 }
		 return list;
	 }
}

  第二步:创建测试类

package lo.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import lo.user.vo.User;

public class Test{
	
	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		Connection conn = JDBCUtils.getConnection();      //JDBCUtils 自己定义的一个类
		PreparedStatement pre = null;
		ResultSet res = null;
		String sql = "select * from user where username=?";
		try {
			pre = conn.prepareStatement(sql);
			pre.setString(1,"wqq");
			res = pre.executeQuery();
			//调用将结果集转换成实体对象方法
			List list = JDBCUtils.Populate(res, User.class);
			//循环遍历结果
			for(int i=0;i<list.size();i++){
				User user = (User) list.get(i);
				System.out.println("[username = "+ user.getUsername()+",passwd = "+ user.getPassword()+"]");
			}
		
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

 总结:

  重点在于 populate (ResultSet res,Class cc)转换方法。

  根据穿过来的 cc 创建实例 cc.newInstance();

  ResultSetMetaData 获得结果集中列的名称和类型的信息。

  Field 用来放实体类中的字段,这里的每一个字段都是对象。可以通过set(Obj,value) 给字段赋值

    匹配思路:

    1.先遍历结果集中的每一条记录。

    2.用ResultSetMetaData 获得 getColumnCount 列数和getColumnName 列名

    3.结果集中的列名和Field中的字段名匹配。

posted @ 2017-03-30 19:30  苦海无涯、苦尽甘来  阅读(7810)  评论(0编辑  收藏  举报