如何将ResultSet中得到的一行或多行结果集封装成对象

首先说一下这个使用场景,我们在使用jdbc连接数据库的时候,执行查询语句时候会得到一个结果集,如果想要再获取这个结果集中的值,就需要我们将他转换成一个对象,然后通过对象的get和set方法来获取到数据库中的值。

public class BaseDao <E> {
	private Class<?> cls;
	public BaseDao() {
		//得到父类的泛型
		Type sType=getClass().getGenericSuperclass();
		//得到实际的类型参数数组
		Type[] generics=((ParameterizedType) sType).getActualTypeArguments();
		 //得到第一个泛型的Class
		cls=(Class<?>) (generics[0]);
	}
/**
	 * 单表多条查询,将查询到的多条记录传入一个对象,然后再将这些存入一个集合中,返回这个集合
	 * @param sql 传入对应的sql查询语句
	 * @param parameters 传入对应的占位符的值
	 * @return 返回查询到的记录转化成的对象的集合
	 */
        //Object...parameters是sql语句中对应的占位符的值,是一个不定长可变参数,我们需要写一个函数来获取他
	public List<E> list(String sql,Object...parameters) {
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		List<E> list = new ArrayList<>();
		
		try {
			conn = JdbcUtil.getConnection();
			st = conn.prepareStatement(sql);
			setParameters(st, parameters);
			rs = st.executeQuery();
			while(rs.next()) {
                //将获取到的结果集存入一个对象中,这个我们也单独写一个函数来实现
				E obj = oneRowToObject(rs);
                //然后将对象存入一个集合中返回
				list.add(obj);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.closeAll(rs, st, conn);
		}	
		return list;
	}

首先来写一下获取不定长可变参数的方法

/**
	 * 设置占位符
	 * @param st 预处理
	 * @param parameters 占位符数组
         * @return 返回存储占位符对应的对象的数组
	 */
	private void setParameters(PreparedStatement st, Object[] parameters) {
                //判断是否有结果集,结果集中是否有记录
		if(parameters!=null&&parameters.length>0) {
			for(int i=0;i<parameters.length;i++) {
				try {
					st.setObject(i+1,parameters[i] );
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}	
		}
	}

然后再把一个结果集转化成一个对象的方法写一下

* 把得到的一列数据存入到一个对象中
	 * @param rs
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	@SuppressWarnings("unchecked")
	private E oneRowToObject(ResultSet rs) throws InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
		E obj;
		obj=(E) cls.newInstance();
		//获取结果集元数据(获取此 ResultSet 对象的列的编号、类型和属性。)
		ResultSetMetaData rd=rs.getMetaData();
		for (int i = 0; i < rd.getColumnCount(); i++) {
			//获取列名
			String columnName=rd.getColumnLabel(i+1);
			//组合方法名
			String methodName="set"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1);
			//获取列类型
			int columnType=rd.getColumnType(i+1);
			Method method=null;
			switch(columnType) {
			case java.sql.Types.VARCHAR:
			case java.sql.Types.CHAR:
				method=cls.getMethod(methodName, String.class);
				if(method!=null) {
					method.invoke(obj, rs.getString(columnName));	
				}
				break;			
			case java.sql.Types.INTEGER:
			case java.sql.Types.SMALLINT:
				method=cls.getMethod(methodName, int.class);
				if(method!=null) {
					method.invoke(obj, rs.getInt(columnName));	
				}
				break;
			case java.sql.Types.BIGINT:
				method=cls.getMethod(methodName, long.class);
				if(method!=null) {
					method.invoke(obj, rs.getLong(columnName));	
				}
				break;
			case java.sql.Types.DATE:
			case java.sql.Types.TIMESTAMP:
				try {
					method=cls.getMethod(methodName, Date.class);
					if(method!=null) {						
						method.invoke(obj, rs.getTimestamp(columnName));	
					}
				} catch(Exception e) {
					method=cls.getMethod(methodName, String.class);
					if(method!=null) {
						method.invoke(obj, rs.getString(columnName));	
					}
				}				
				break;
			case java.sql.Types.DECIMAL:
				method=cls.getMethod(methodName, BigDecimal.class);
				if(method!=null) {
					method.invoke(obj, rs.getBigDecimal(columnName));	
				}
				break;
			case java.sql.Types.DOUBLE:
			case java.sql.Types.NUMERIC:
				method=cls.getMethod(methodName, double.class);
				if(method!=null) {
					method.invoke(obj, rs.getDouble(columnName));	
				}
				break;
			case java.sql.Types.BIT:
				method=cls.getMethod(methodName, boolean.class);
				if(method!=null) {
					method.invoke(obj, rs.getBoolean(columnName));	
				}
				break;
			default:
				break;
			}	
		}
		return obj;
	}	

使用的话就是写一个实体类Dao继承BaseDao

public class UserDao extends BaseDao <User>{
	
}

测试一下:

public class test {
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, SQLException, IntrospectionException {
		UserDao userdao = new UserDao();
                List<User> list=userdao.list("select * from user");
		System.out.println("uid\t"+"uname\t"+"state\t"+"flag");
		for (User user : list) {
			System.out.println(user.getUid()+"\t"+user.getUname()+"\t"+user.getState()+"\t"+user.getFlag());
		}
}
}

猜你喜欢

转载自blog.csdn.net/qq_40180411/article/details/81697723