JDBC+spring的对象Mapper封装类

本文介绍了一个Java实用类ObjectRowMapper,该类实现了Spring JDBC的ParameterizedRowMapper接口,用于将数据库查询结果集映射为Java对象。文章详细展示了如何通过反射机制设置对象属性值的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.dg11185.dgListerner.utils;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public class ObjectRowMapper implements ParameterizedRowMapper {
	private Class objClass;

	/**
	 * 得到对象的class类型
	 * 
	 * @param objClass
	 */
	public ObjectRowMapper(Class objClass) {
		this.objClass = objClass;
	}

	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		try {
			Object object = objClass.newInstance(); //实例化一个对象
			// 通过反射得到对象的字段名,注意:要使用getDeclaredFields(),不能是getFields()
			Field[] fields = object.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				field.setAccessible(true);// 设置访问权限
				this.typeMapper(field , object , rs);
				field.setAccessible(false);
			}
			return object;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 类型的映射
	 * @param field
	 * @param obj
	 * @param rs
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	private void typeMapper(Field field, Object obj, ResultSet rs)
			throws IllegalArgumentException, IllegalAccessException,
			SQLException {
		String typeName = field.getType().getName(); // 得到字段类型
		//设置值的
		//(所属对象,值), ResultSet的getString/getInt...里面的字段名是不分大小写的
		if (typeName.equals("java.lang.String")) {
			field.set(obj, rs.getString(field.getName()));
		} else if (typeName.equals("int")
				|| typeName.equals("java.lang.Integer")) {
			field.set(obj, rs.getInt(field.getName()));
		} else if (typeName.equals("long") || typeName.equals("java.lang.Long")) {
			field.set(obj, rs.getLong(field.getName()));
		} else if (typeName.equals("boolean")
				|| typeName.equals("java.lang.Boolean")) {
			field.set(obj, rs.getBoolean(field.getName()));
		} else if (typeName.equals("java.util.Date")) {
			field.set(obj, rs.getDate(field.getName()));
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值