package com.xinhuanet.cloudDesk.dao.impl;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowMapper;
public abstract class BaseRowMapper<T> implements RowMapper {
private static final Logger log = Logger.getLogger(BaseRowMapper.class);
@Override
public T mapRow(ResultSet rs, int index) throws SQLException {
try {
Class clazz = Class.forName(this.getClassName());
Object obj = clazz.newInstance();
for (Class clazztemp = clazz; clazztemp != Object.class; clazztemp = clazztemp
.getSuperclass()) {
Field[] fields = clazztemp.getDeclaredFields();
if (fields == null) {
return null;
}
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
Class fieldClass = fields[i].getType();
String methodName = "set"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
Method method = clazztemp.getDeclaredMethod(methodName,
new Class[] { fieldClass });
Object param = null;
try {
param = rs.getObject(fieldName.toLowerCase());
if(param != null) {
method.invoke(obj, param);
}
} catch (Exception e) {
log.error("fieldName:" + fieldName + "是" + fieldClass
+ "目标参数是:" + param.getClass());
log.error(e);
}
}
}
return (T) obj;
} catch (Exception e) {
log.error(e);
e.printStackTrace();
return null;
}
}
/**
* 子类的类名
*
* @return
*/
public abstract String getClassName();
}
使用反射封装RowMapper
最新推荐文章于 2024-03-20 10:53:27 发布