- 爱易网页
-
数据库教程
- JdbcTemplate相助类-行记录转换成Dto
日期:2014-05-16 浏览次数:20487 次
JdbcTemplate帮助类-行记录转换成Dto
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.keyvalue.AbstractMapEntry;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JdbcTemplate帮助类-行记录转换成Dto
*
* @author vernon.chen
*
*/
public class JdbcTemplateRowMapper {
private static Logger logger = LoggerFactory.getLogger(JdbcTemplateRowMapper.class);
private final static String SET = "set";
public static <T extends BaseDto> List<T> resultSet2DtoList(ResultSet rs, T baseDto) {
try {
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
List<KeyValuePair2<Integer, String>> kvColList = new ArrayList<KeyValuePair2<Integer, String>>();
for (int column = 1; column <= columnCount; column++) {
int columnType = md.getColumnType(column);// 列类型
// String columnName = md.getColumnName(column);//field的原始名字
String columnLabel = md.getColumnLabel(column);// field的别名
KeyValuePair2<Integer, String> kvCol = new KeyValuePair2<Integer, String>(columnType, columnLabel);
kvColList.add(kvCol);
}
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
while (rs.next()) {
HashMap<String, Object> e = new HashMap<String, Object>();
for (KeyValuePair2<Integer, String> kvCol : kvColList) {
String colAlias = kvCol.getValue();// 列别名
Object object = rs.getObject(colAlias);// 列值
e.put(colAlias, object);
}
rows.add(e);
}
return JdbcTemplateRowMapper.rowMap2DtoList(rows, baseDto);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ServiceException(ErrorCodes.ERRORCODES_SYSTEM_ERROR.getStrVlue(), e);
}
}
/**
* 多行记录转换为Dto集合
*
* @param rows
* 多行记录
* @param baseDto
* baseDto实例
* @return Dto集合
*/
public static <T extends BaseDto> List<T> rowMap2DtoList(List<Map<String, Object>> rows, T baseDto) {
List<T> dtoList = new ArrayList<T>();
if (CollectionUtils.isEmpty(rows)) {
return dtoList;
}
Map<String, String> filedsMap = new HashMap<String, String>();
T dto = null;
Constructor<T> constructor = null;
Class<?> conargs[] = {};
Class<T> clazz = (Class<T>) baseDto.getClass();
Set<String> keySet = null;
String filedName = null;
Object filedValue = null;
BeanMap beanMap = new BeanMap(baseDto);
@SuppressWarnings("unchecked")
Set<AbstractMapEntry> entrySet = beanMap.entrySet();
String filedNameTmp = null;
for (AbstractMapEntry entry : entrySet) {
filedNameTmp = entry.getKey().toString();