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()));
}
}
}