package com.achievo.ems.web.util;
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;
import com.achievo.core.common.ErrorCodes;
import com.achievo.core.exception.ServiceException;
import com.achievo.ems.web.dto.BaseDto;
import com.achievo.ems.web.dto.exam.ExamineeInfoDto;
import com.achievo.ems.web.dto.exam.PositionDto;
import com.achievo.ems.web.dto.score.PScoreOrigDto;
import com.achievo.ems.web.service.score.ConnUtils2;
/**
* 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();
filedsMap.put(filedNameTmp.toUpperCase(), filedNameTmp);
}
for (Map<String, Object> map : rows) {
try {
constructor = clazz.getConstructor(conargs);
dto = (T) constructor.newInstance();
} catch (SecurityException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalArgumentException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InstantiationException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
dtoList.add(dto);
keySet = map.keySet();
for (String key : keySet) {
try {
if (keySet.contains(key)) {
filedName = filedsMap.get(key.toUpperCase());
filedValue = map.get(key);
} else {
continue;
}
if (StringUtils.isNotBlank(filedName) && null != filedValue) {
JdbcTemplateRowMapper.setProperty(dto, filedName, filedValue);
}
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (Exception e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
}
}
filedsMap.clear();
filedsMap = null;
dto = null;
constructor = null;
conargs = null;
clazz = null;
filedName = null;
filedValue = null;
beanMap.clear();
beanMap = null;
// entrySet.clear();//UnsupportedOperationException
entrySet = null;
filedNameTmp = null;
keySet.clear();
keySet = null;
// int size = rows.size();
rows.clear();// 释放
rows = null;
// logger.debug(size + " rows be cleared.");
//
// logger.debug("多行记录转换为Dto集合-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
return dtoList;
}
/**
* 多行记录转换为Dto集合
*
* @param rows
* 多行记录
* @param baseDto
* baseDto实例
* @return Dto集合
*/
public static <T> 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();
filedsMap.put(filedNameTmp.toUpperCase(), filedNameTmp);
}
for (Map<String, Object> map : rows) {
try {
constructor = clazz.getConstructor(conargs);
dto = (T) constructor.newInstance();
} catch (SecurityException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalArgumentException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InstantiationException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
dtoList.add(dto);
keySet = map.keySet();
for (String key : keySet) {
try {
if (keySet.contains(key)) {
filedName = filedsMap.get(key.toUpperCase());
filedValue = map.get(key);
} else {
continue;
}
if (StringUtils.isNotBlank(filedName) && null != filedValue) {
JdbcTemplateRowMapper.setProperty(dto, filedName, filedValue);
}
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (Exception e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
}
}
filedsMap.clear();
filedsMap = null;
dto = null;
constructor = null;
conargs = null;
clazz = null;
filedName = null;
filedValue = null;
beanMap.clear();
beanMap = null;
// entrySet.clear();//UnsupportedOperationException
entrySet = null;
filedNameTmp = null;
keySet.clear();
keySet = null;
// int size = rows.size();
rows.clear();// 释放
rows = null;
// logger.debug(size + " rows be cleared.");
//
// logger.debug("多行记录转换为Dto集合-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
return dtoList;
}
public static void main(
String[] args) throws Throwable {
testReflect();
}
public static <T extends BaseDto> void setProperty(
T dto,
String filedName,
Object filedValue) throws Exception {
// byte(字节) 8 -128 -127 0
// short(短整型) 16 -32768 -32768 0
// int(整型) 32 -2147483648 -2147483648 0
// long(长整型) 64 -9233372036854477808 -9233372036854477808 0
// float(浮点型) 32 -3.40292347E+38 -3.40292347E+38 0.0f
// double(双精度) 64 -1.79769313486231570E+308 -1.79769313486231570E+308 0.0d
// char(字符型) 16 ‘ \u0000 - u\ffff ’ ‘\u0000 ’
// boolean(布尔型) 1 true/false false
//
Class<? extends BaseDto> dtoCls = dto.getClass();
Class<? extends Object> filedClass = filedValue.getClass();// jdbc返回的值类型
if (java.sql.Timestamp.class.isAssignableFrom(filedClass)) {
filedValue = new Date(((java.sql.Timestamp) filedValue).getTime());
filedClass = Date.class;
}
Field dtoField = null;
try {
dtoField = dtoCls.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
Field[] fields = dtoCls.getFields();
for (Field field : fields) {
if (field.getName().equals(filedName)) {
dtoField = field;// 获取超类中定义的Filed
break;
}
}
}
Class<?> dtoFiledType = dtoField.getType();
if (filedClass.isAssignableFrom(dtoFiledType)) {// 类型相同
;// noting to do.
} else {// 类型不相同
if (java.math.BigDecimal.class.isAssignableFrom(filedClass)) {// jdbc返回BigDecimal类型
if (short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = short.class;
} else if (int.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = int.class;
} else if (long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = long.class;
} else if (float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = float.class;
} else if (double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = double.class;
} else if (Short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = Short.class;
} else if (Integer.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = Integer.class;
} else if (Long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = Long.class;
} else if (Float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = Float.class;
} else if (Double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = Double.class;
} else if (String.class.isAssignableFrom(dtoFiledType)) {
filedValue = filedValue.toString();
filedClass = String.class;
} else {
throw new Exception("未定义的数据类型。");
}
}
}
// logger.debug("filedClass.getName()" + ":" + filedClass.getName());
Method method = dtoCls.getMethod(SET + StringUtils.capitalize(filedName), filedClass);
method.invoke(dto, filedValue);
dtoCls = null;
}
public static <T> void setProperty(
T dto,
String filedName,
Object filedValue) throws Exception {
// byte(字节) 8 -128 -127 0
// short(短整型) 16 -32768 -32768 0
// int(整型) 32 -2147483648 -2147483648 0
// long(长整型) 64 -9233372036854477808 -9233372036854477808 0
// float(浮点型) 32 -3.40292347E+38 -3.40292347E+38 0.0f
// double(双精度) 64 -1.79769313486231570E+308 -1.79769313486231570E+308 0.0d
// char(字符型) 16 ‘ \u0000 - u\ffff ’ ‘\u0000 ’
// boolean(布尔型) 1 true/false false
//
Class<?> dtoCls = dto.getClass();
Class<? extends Object> filedClass = filedValue.getClass();// jdbc返回的值类型
if (java.sql.Timestamp.class.isAssignableFrom(filedClass)) {
filedValue = new Date(((java.sql.Timestamp) filedValue).getTime());
filedClass = Date.class;
}
Field dtoField = null;
try {
dtoField = dtoCls.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
Field[] fields = dtoCls.getFields();
for (Field field : fields) {
if (field.getName().equals(filedName)) {
dtoField = field;// 获取超类中定义的Filed
break;
}
}
}
Class<?> dtoFiledType = dtoField.getType();
if (filedClass.isAssignableFrom(dtoFiledType)) {// 类型相同
;// noting to do.
} else {// 类型不相同
if (java.math.BigDecimal.class.isAssignableFrom(filedClass)) {// jdbc返回BigDecimal类型
if (short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = short.class;
} else if (int.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = int.class;
} else if (long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = long.class;
} else if (float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = float.class;
} else if (double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = double.class;
} else if (Short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = Short.class;
} else if (Integer.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = Integer.class;
} else if (Long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = Long.class;
} else if (Float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = Float.class;
} else if (Double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = Double.class;
} else if (String.class.isAssignableFrom(dtoFiledType)) {
filedValue = filedValue.toString();
filedClass = String.class;
} else {
throw new Exception("未定义的数据类型。");
}
}
}
// logger.debug("filedClass.getName()" + ":" + filedClass.getName());
Method method = dtoCls.getMethod(SET + StringUtils.capitalize(filedName), filedClass);
method.invoke(dto, filedValue);
dtoCls = null;
}
public static void testReflect() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
PScoreOrigDto dto = new PScoreOrigDto();
Class<? extends PScoreOrigDto> cls = dto.getClass();
Field[] fields = cls.getDeclaredFields();// 自身定义的所有字段。不包括继承自父类
// Method[] declaredMethods = cls.getDeclaredMethods();
String setter = "set";
String filedName = null;
Object filedValue = null;
Method method = null;
for (Field field : fields) {
filedName = field.getName();
filedValue = "1111";
Class<?> fieldType = field.getType();
// logger.debug("filedName" + ":" + filedName);
if (BaseDto.class.isAssignableFrom(fieldType) || fieldType.isArray() || List.class.isAssignableFrom(fieldType) || Set.class.isAssignableFrom(fieldType)) {
;// 排除BaseDto类型的字段
} else {
method = cls.getMethod(setter + StringUtils.capitalize(filedName), fieldType);
logger.debug("filedName" + ":" + filedName + "\t\t" + "fieldType" + ":" + fieldType);
if (BigDecimal.class.isAssignableFrom(fieldType)) {
filedValue = new BigDecimal(filedValue.toString());
} else if (Integer.class.isAssignableFrom(fieldType)) {
filedValue = new Integer(filedValue.toString());
} else if (Long.class.isAssignableFrom(fieldType)) {
filedValue = new Long(filedValue.toString());
} else if (Double.class.isAssignableFrom(fieldType)) {
filedValue = new Double(filedValue.toString());
} else if (Float.class.isAssignableFrom(fieldType)) {
filedValue = new Float(filedValue.toString());
} else if (Short.class.isAssignableFrom(fieldType)) {
filedValue = new Short(filedValue.toString());
} else if (Byte.class.isAssignableFrom(fieldType)) {
filedValue = new Byte(filedValue.toString());
} else if (Date.class.isAssignableFrom(fieldType)) {
filedValue = DateTimeUtils.parseDate(filedValue.toString());
}
method.invoke(dto, filedValue);
}
}
// method = cls.getMethod(setter + StringUtils.capitalize("createTime"), Date.class);
// method.invoke(dto, new Date());
// method = cls.getMethod(setter + StringUtils.capitalize("createBy"), String.class);
// method.invoke(dto, "createBy");
// method = cls.getMethod(setter + StringUtils.capitalize("updateTime"), Date.class);
// method.invoke(dto, new Date());
// method = cls.getMethod(setter + StringUtils.capitalize("updateBy"), String.class);
// method.invoke(dto, "createBy");
//
// logger.debug("dto.getApplyNo()" + ":" + dto.getApplyNo());
// logger.debug("dto.getCertNo()" + ":" + dto.getCertNo());
// logger.debug("dto.getCertType()" + ":" + dto.getCertType());
// logger.debug("dto.getCreateTime()" + ":" + dto.getCreateTime());
// logger.debug("dto.getCreateBy()" + ":" + dto.getCreateBy());
// logger.debug("dto.getUpdateTime()" + ":" + dto.getUpdateTime());
// logger.debug("dto.getUpdateBy()" + ":" + dto.getUpdateBy());
}
public static void main2(
String[] args) {
viewRuntimeMemory();
List<PScoreOrigDto> psoList = new ArrayList<PScoreOrigDto>();
PScoreOrigDto e = null;
long time_begin = System.currentTimeMillis();
for (int i = 0; i < 5 * 2; i++) {
for (int j = 0; j < 20000; j++) {
e = new PScoreOrigDto();
e.setApplyNo("");
e.setCertNo(null);
e.setCertType(" ");
// e.setClusterSubject(new ClusterSubjectDto());
e.setClusterSubjectId("String");
e.setCredtId("String");
e.setExamineeInfo(new ExamineeInfoDto());
e.setException(BigDecimal.ZERO);
e.setExamineeName("String");
e.setFlag(BigDecimal.TEN);
e.setId("String");
e.setPosition(new PositionDto());
e.setPositionClusterName("String");
e.setPositionId("String");
e.setScore(BigDecimal.TEN);
e.setSignature("String");
e.setSubjectId("String");
psoList.add(e);
}
logger.debug("根据导入日志ID删除导入的记录:" + i);
}
logger.debug("根据导入日志ID删除导入的记录-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
List<BaseDto> dtoList = new ArrayList<BaseDto>();
Map<String, String> filedsMap = new HashMap<String, String>();
PScoreOrigDto dto = null;
Constructor<PScoreOrigDto> constructor = null;
Class<?> conargs[] = {};
PScoreOrigDto template = new PScoreOrigDto();
Class<PScoreOrigDto> clazz = (Class<PScoreOrigDto>) template.getClass();
BeanMap beanMap = new BeanMap(template);
Set<String> keySet = beanMap.keySet();
String filedName = null;
Object filedValue = null;
@SuppressWarnings("unchecked")
Set<AbstractMapEntry> entrySet = beanMap.entrySet();
String filedNameTmp = null;
for (AbstractMapEntry entry : entrySet) {
filedNameTmp = entry.getKey().toString();
filedsMap.put(filedNameTmp.toUpperCase(), filedNameTmp);
}
time_begin = System.currentTimeMillis();
for (PScoreOrigDto pso : psoList) {
try {
constructor = clazz.getConstructor(conargs);
dto = constructor.newInstance();
} catch (SecurityException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalArgumentException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InstantiationException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
dtoList.add(dto);
for (String key : keySet) {
try {
filedName = key;
filedValue = BeanUtils.getProperty(pso, key);
if (StringUtils.isNotBlank(filedName) && null != filedValue) {
if ("position".equals(key) || "examineeInfo".equals(key) || "clusterSubject".equals(key)) {
} else {
BeanUtils.setProperty(dto, filedName, filedValue);
}
}
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
}
}
// logger.debug("转换(" + psoList.size() + ")个实体-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
filedsMap.clear();
filedsMap = null;
dto = null;
constructor = null;
conargs = null;
clazz = null;
filedName = null;
filedValue = null;
beanMap.clear();
beanMap = null;
// entrySet.clear();//UnsupportedOperationException
entrySet = null;
filedNameTmp = null;
// keySet.clear();//UnsupportedOperationException
keySet = null;
}
/**
* 查看运行时内存使用情况
*/
public static void viewRuntimeMemory() {
long maxMemory = java.lang.Runtime.getRuntime().maxMemory();// 这个方法返回的是java虚拟机(这个进程)能构从操作系统那里挖到的最大的内存,以字节为单位
long totalMemory = java.lang.Runtime.getRuntime().totalMemory();// 这个方法返回的是java虚拟机现在已经从操作系统那里挖过来的内存大小,也就是java虚拟机这个进程当时所占用的所有内存。
long freeMemory = java.lang.Runtime.getRuntime().freeMemory();// 从操作系统那里挖过来而又没有用上的内存,实际上就是 freeMemory()
logger.debug("从操作系统那里挖到的最大的内存:" + maxMemory / 1024 / 1024 + "M");
logger.debug("虚拟机这个进程当时所占用的所有内存:" + totalMemory / 1024 / 1024 + "M");
logger.debug("从操作系统那里挖过来而又没有用上的内存:" + freeMemory / 1024 / 1024 + "M");
}
}
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;
import com.achievo.core.common.ErrorCodes;
import com.achievo.core.exception.ServiceException;
import com.achievo.ems.web.dto.BaseDto;
import com.achievo.ems.web.dto.exam.ExamineeInfoDto;
import com.achievo.ems.web.dto.exam.PositionDto;
import com.achievo.ems.web.dto.score.PScoreOrigDto;
import com.achievo.ems.web.service.score.ConnUtils2;
/**
* 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();
filedsMap.put(filedNameTmp.toUpperCase(), filedNameTmp);
}
for (Map<String, Object> map : rows) {
try {
constructor = clazz.getConstructor(conargs);
dto = (T) constructor.newInstance();
} catch (SecurityException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalArgumentException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InstantiationException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
dtoList.add(dto);
keySet = map.keySet();
for (String key : keySet) {
try {
if (keySet.contains(key)) {
filedName = filedsMap.get(key.toUpperCase());
filedValue = map.get(key);
} else {
continue;
}
if (StringUtils.isNotBlank(filedName) && null != filedValue) {
JdbcTemplateRowMapper.setProperty(dto, filedName, filedValue);
}
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (Exception e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
}
}
filedsMap.clear();
filedsMap = null;
dto = null;
constructor = null;
conargs = null;
clazz = null;
filedName = null;
filedValue = null;
beanMap.clear();
beanMap = null;
// entrySet.clear();//UnsupportedOperationException
entrySet = null;
filedNameTmp = null;
keySet.clear();
keySet = null;
// int size = rows.size();
rows.clear();// 释放
rows = null;
// logger.debug(size + " rows be cleared.");
//
// logger.debug("多行记录转换为Dto集合-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
return dtoList;
}
/**
* 多行记录转换为Dto集合
*
* @param rows
* 多行记录
* @param baseDto
* baseDto实例
* @return Dto集合
*/
public static <T> 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();
filedsMap.put(filedNameTmp.toUpperCase(), filedNameTmp);
}
for (Map<String, Object> map : rows) {
try {
constructor = clazz.getConstructor(conargs);
dto = (T) constructor.newInstance();
} catch (SecurityException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalArgumentException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InstantiationException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
dtoList.add(dto);
keySet = map.keySet();
for (String key : keySet) {
try {
if (keySet.contains(key)) {
filedName = filedsMap.get(key.toUpperCase());
filedValue = map.get(key);
} else {
continue;
}
if (StringUtils.isNotBlank(filedName) && null != filedValue) {
JdbcTemplateRowMapper.setProperty(dto, filedName, filedValue);
}
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (Exception e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
}
}
filedsMap.clear();
filedsMap = null;
dto = null;
constructor = null;
conargs = null;
clazz = null;
filedName = null;
filedValue = null;
beanMap.clear();
beanMap = null;
// entrySet.clear();//UnsupportedOperationException
entrySet = null;
filedNameTmp = null;
keySet.clear();
keySet = null;
// int size = rows.size();
rows.clear();// 释放
rows = null;
// logger.debug(size + " rows be cleared.");
//
// logger.debug("多行记录转换为Dto集合-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
return dtoList;
}
public static void main(
String[] args) throws Throwable {
testReflect();
}
public static <T extends BaseDto> void setProperty(
T dto,
String filedName,
Object filedValue) throws Exception {
// byte(字节) 8 -128 -127 0
// short(短整型) 16 -32768 -32768 0
// int(整型) 32 -2147483648 -2147483648 0
// long(长整型) 64 -9233372036854477808 -9233372036854477808 0
// float(浮点型) 32 -3.40292347E+38 -3.40292347E+38 0.0f
// double(双精度) 64 -1.79769313486231570E+308 -1.79769313486231570E+308 0.0d
// char(字符型) 16 ‘ \u0000 - u\ffff ’ ‘\u0000 ’
// boolean(布尔型) 1 true/false false
//
Class<? extends BaseDto> dtoCls = dto.getClass();
Class<? extends Object> filedClass = filedValue.getClass();// jdbc返回的值类型
if (java.sql.Timestamp.class.isAssignableFrom(filedClass)) {
filedValue = new Date(((java.sql.Timestamp) filedValue).getTime());
filedClass = Date.class;
}
Field dtoField = null;
try {
dtoField = dtoCls.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
Field[] fields = dtoCls.getFields();
for (Field field : fields) {
if (field.getName().equals(filedName)) {
dtoField = field;// 获取超类中定义的Filed
break;
}
}
}
Class<?> dtoFiledType = dtoField.getType();
if (filedClass.isAssignableFrom(dtoFiledType)) {// 类型相同
;// noting to do.
} else {// 类型不相同
if (java.math.BigDecimal.class.isAssignableFrom(filedClass)) {// jdbc返回BigDecimal类型
if (short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = short.class;
} else if (int.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = int.class;
} else if (long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = long.class;
} else if (float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = float.class;
} else if (double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = double.class;
} else if (Short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = Short.class;
} else if (Integer.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = Integer.class;
} else if (Long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = Long.class;
} else if (Float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = Float.class;
} else if (Double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = Double.class;
} else if (String.class.isAssignableFrom(dtoFiledType)) {
filedValue = filedValue.toString();
filedClass = String.class;
} else {
throw new Exception("未定义的数据类型。");
}
}
}
// logger.debug("filedClass.getName()" + ":" + filedClass.getName());
Method method = dtoCls.getMethod(SET + StringUtils.capitalize(filedName), filedClass);
method.invoke(dto, filedValue);
dtoCls = null;
}
public static <T> void setProperty(
T dto,
String filedName,
Object filedValue) throws Exception {
// byte(字节) 8 -128 -127 0
// short(短整型) 16 -32768 -32768 0
// int(整型) 32 -2147483648 -2147483648 0
// long(长整型) 64 -9233372036854477808 -9233372036854477808 0
// float(浮点型) 32 -3.40292347E+38 -3.40292347E+38 0.0f
// double(双精度) 64 -1.79769313486231570E+308 -1.79769313486231570E+308 0.0d
// char(字符型) 16 ‘ \u0000 - u\ffff ’ ‘\u0000 ’
// boolean(布尔型) 1 true/false false
//
Class<?> dtoCls = dto.getClass();
Class<? extends Object> filedClass = filedValue.getClass();// jdbc返回的值类型
if (java.sql.Timestamp.class.isAssignableFrom(filedClass)) {
filedValue = new Date(((java.sql.Timestamp) filedValue).getTime());
filedClass = Date.class;
}
Field dtoField = null;
try {
dtoField = dtoCls.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
Field[] fields = dtoCls.getFields();
for (Field field : fields) {
if (field.getName().equals(filedName)) {
dtoField = field;// 获取超类中定义的Filed
break;
}
}
}
Class<?> dtoFiledType = dtoField.getType();
if (filedClass.isAssignableFrom(dtoFiledType)) {// 类型相同
;// noting to do.
} else {// 类型不相同
if (java.math.BigDecimal.class.isAssignableFrom(filedClass)) {// jdbc返回BigDecimal类型
if (short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = short.class;
} else if (int.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = int.class;
} else if (long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = long.class;
} else if (float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = float.class;
} else if (double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = double.class;
} else if (Short.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).shortValue();
filedClass = Short.class;
} else if (Integer.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).intValue();
filedClass = Integer.class;
} else if (Long.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).longValue();
filedClass = Long.class;
} else if (Float.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).floatValue();
filedClass = Float.class;
} else if (Double.class.isAssignableFrom(dtoFiledType)) {
filedValue = ((java.math.BigDecimal) filedValue).doubleValue();
filedClass = Double.class;
} else if (String.class.isAssignableFrom(dtoFiledType)) {
filedValue = filedValue.toString();
filedClass = String.class;
} else {
throw new Exception("未定义的数据类型。");
}
}
}
// logger.debug("filedClass.getName()" + ":" + filedClass.getName());
Method method = dtoCls.getMethod(SET + StringUtils.capitalize(filedName), filedClass);
method.invoke(dto, filedValue);
dtoCls = null;
}
public static void testReflect() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
PScoreOrigDto dto = new PScoreOrigDto();
Class<? extends PScoreOrigDto> cls = dto.getClass();
Field[] fields = cls.getDeclaredFields();// 自身定义的所有字段。不包括继承自父类
// Method[] declaredMethods = cls.getDeclaredMethods();
String setter = "set";
String filedName = null;
Object filedValue = null;
Method method = null;
for (Field field : fields) {
filedName = field.getName();
filedValue = "1111";
Class<?> fieldType = field.getType();
// logger.debug("filedName" + ":" + filedName);
if (BaseDto.class.isAssignableFrom(fieldType) || fieldType.isArray() || List.class.isAssignableFrom(fieldType) || Set.class.isAssignableFrom(fieldType)) {
;// 排除BaseDto类型的字段
} else {
method = cls.getMethod(setter + StringUtils.capitalize(filedName), fieldType);
logger.debug("filedName" + ":" + filedName + "\t\t" + "fieldType" + ":" + fieldType);
if (BigDecimal.class.isAssignableFrom(fieldType)) {
filedValue = new BigDecimal(filedValue.toString());
} else if (Integer.class.isAssignableFrom(fieldType)) {
filedValue = new Integer(filedValue.toString());
} else if (Long.class.isAssignableFrom(fieldType)) {
filedValue = new Long(filedValue.toString());
} else if (Double.class.isAssignableFrom(fieldType)) {
filedValue = new Double(filedValue.toString());
} else if (Float.class.isAssignableFrom(fieldType)) {
filedValue = new Float(filedValue.toString());
} else if (Short.class.isAssignableFrom(fieldType)) {
filedValue = new Short(filedValue.toString());
} else if (Byte.class.isAssignableFrom(fieldType)) {
filedValue = new Byte(filedValue.toString());
} else if (Date.class.isAssignableFrom(fieldType)) {
filedValue = DateTimeUtils.parseDate(filedValue.toString());
}
method.invoke(dto, filedValue);
}
}
// method = cls.getMethod(setter + StringUtils.capitalize("createTime"), Date.class);
// method.invoke(dto, new Date());
// method = cls.getMethod(setter + StringUtils.capitalize("createBy"), String.class);
// method.invoke(dto, "createBy");
// method = cls.getMethod(setter + StringUtils.capitalize("updateTime"), Date.class);
// method.invoke(dto, new Date());
// method = cls.getMethod(setter + StringUtils.capitalize("updateBy"), String.class);
// method.invoke(dto, "createBy");
//
// logger.debug("dto.getApplyNo()" + ":" + dto.getApplyNo());
// logger.debug("dto.getCertNo()" + ":" + dto.getCertNo());
// logger.debug("dto.getCertType()" + ":" + dto.getCertType());
// logger.debug("dto.getCreateTime()" + ":" + dto.getCreateTime());
// logger.debug("dto.getCreateBy()" + ":" + dto.getCreateBy());
// logger.debug("dto.getUpdateTime()" + ":" + dto.getUpdateTime());
// logger.debug("dto.getUpdateBy()" + ":" + dto.getUpdateBy());
}
public static void main2(
String[] args) {
viewRuntimeMemory();
List<PScoreOrigDto> psoList = new ArrayList<PScoreOrigDto>();
PScoreOrigDto e = null;
long time_begin = System.currentTimeMillis();
for (int i = 0; i < 5 * 2; i++) {
for (int j = 0; j < 20000; j++) {
e = new PScoreOrigDto();
e.setApplyNo("");
e.setCertNo(null);
e.setCertType(" ");
// e.setClusterSubject(new ClusterSubjectDto());
e.setClusterSubjectId("String");
e.setCredtId("String");
e.setExamineeInfo(new ExamineeInfoDto());
e.setException(BigDecimal.ZERO);
e.setExamineeName("String");
e.setFlag(BigDecimal.TEN);
e.setId("String");
e.setPosition(new PositionDto());
e.setPositionClusterName("String");
e.setPositionId("String");
e.setScore(BigDecimal.TEN);
e.setSignature("String");
e.setSubjectId("String");
psoList.add(e);
}
logger.debug("根据导入日志ID删除导入的记录:" + i);
}
logger.debug("根据导入日志ID删除导入的记录-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
List<BaseDto> dtoList = new ArrayList<BaseDto>();
Map<String, String> filedsMap = new HashMap<String, String>();
PScoreOrigDto dto = null;
Constructor<PScoreOrigDto> constructor = null;
Class<?> conargs[] = {};
PScoreOrigDto template = new PScoreOrigDto();
Class<PScoreOrigDto> clazz = (Class<PScoreOrigDto>) template.getClass();
BeanMap beanMap = new BeanMap(template);
Set<String> keySet = beanMap.keySet();
String filedName = null;
Object filedValue = null;
@SuppressWarnings("unchecked")
Set<AbstractMapEntry> entrySet = beanMap.entrySet();
String filedNameTmp = null;
for (AbstractMapEntry entry : entrySet) {
filedNameTmp = entry.getKey().toString();
filedsMap.put(filedNameTmp.toUpperCase(), filedNameTmp);
}
time_begin = System.currentTimeMillis();
for (PScoreOrigDto pso : psoList) {
try {
constructor = clazz.getConstructor(conargs);
dto = constructor.newInstance();
} catch (SecurityException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalArgumentException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InstantiationException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
dtoList.add(dto);
for (String key : keySet) {
try {
filedName = key;
filedValue = BeanUtils.getProperty(pso, key);
if (StringUtils.isNotBlank(filedName) && null != filedValue) {
if ("position".equals(key) || "examineeInfo".equals(key) || "clusterSubject".equals(key)) {
} else {
BeanUtils.setProperty(dto, filedName, filedValue);
}
}
} catch (IllegalAccessException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (InvocationTargetException e1) {
logger.error("JdbcTemplateRowMapper", e1);
} catch (NoSuchMethodException e1) {
logger.error("JdbcTemplateRowMapper", e1);
}
}
}
// logger.debug("转换(" + psoList.size() + ")个实体-共耗时:" + ConnUtils2.ms2Hms(System.currentTimeMillis() - time_begin));
filedsMap.clear();
filedsMap = null;
dto = null;
constructor = null;
conargs = null;
clazz = null;
filedName = null;
filedValue = null;
beanMap.clear();
beanMap = null;
// entrySet.clear();//UnsupportedOperationException
entrySet = null;
filedNameTmp = null;
// keySet.clear();//UnsupportedOperationException
keySet = null;
}
/**
* 查看运行时内存使用情况
*/
public static void viewRuntimeMemory() {
long maxMemory = java.lang.Runtime.getRuntime().maxMemory();// 这个方法返回的是java虚拟机(这个进程)能构从操作系统那里挖到的最大的内存,以字节为单位
long totalMemory = java.lang.Runtime.getRuntime().totalMemory();// 这个方法返回的是java虚拟机现在已经从操作系统那里挖过来的内存大小,也就是java虚拟机这个进程当时所占用的所有内存。
long freeMemory = java.lang.Runtime.getRuntime().freeMemory();// 从操作系统那里挖过来而又没有用上的内存,实际上就是 freeMemory()
logger.debug("从操作系统那里挖到的最大的内存:" + maxMemory / 1024 / 1024 + "M");
logger.debug("虚拟机这个进程当时所占用的所有内存:" + totalMemory / 1024 / 1024 + "M");
logger.debug("从操作系统那里挖过来而又没有用上的内存:" + freeMemory / 1024 / 1024 + "M");
}
}