import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class BeanPropertyRowMapper<T> implements RowMapper<T>{
private Class<?> clazz;
public BeanPropertyRowMapper(Class<?> clazz) {
this.clazz = clazz;
}
@SuppressWarnings("unchecked")
@Override
public T mapRow(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
Object obj = null;
try {
obj = clazz.newInstance();
for(int i = 1;i <= rsmd.getColumnCount();i++) {
String columnName = rsmd.getColumnLabel(i);
Object columnValue = rs.getObject(columnName);
setPropertyValue(obj,columnName,columnValue);
}
} catch (Exception e) {
e.printStackTrace();
}
return (T)obj;
}
private void setPropertyValue(Object obj,String columnName, Object columnValue) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
String methodName = "set"+columnName.substring(0,1).toUpperCase()+columnName.substring(1);
Method[] methods = clazz.getMethods();
for(Method method : methods) {
if(methodName.equals(method.getName())) {
method.invoke(obj, columnValue);
break;
}
}
}
}
转载于:https://my.oschina.net/cshuangxi/blog/177027