package com.taover.repository.mapper; import java.lang.reflect.Field; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSetMetaData; public class CustomJdbcTemplateRowMapper implements RowMapper{ Log log = LogFactory.getLog(this.getClass()); private Map beanFielNameToField = new HashMap(); private Class classInfo; private Map tableToBeanMap; public CustomJdbcTemplateRowMapper(Class classInfo, Map tableToBeanMap) { this.classInfo = classInfo; this.tableToBeanMap = tableToBeanMap; Field[] fields = this.classInfo.getDeclaredFields(); for(Field item: fields) { try { item.setAccessible(true); this.beanFielNameToField.put(item.getName(), item); }catch (Exception e) { log.error("set field accessible:"+e.getMessage()); } } } @Override public E mapRow(ResultSet rs, int index) throws SQLException { E targetObj; try { targetObj = this.classInfo.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } ResultSetWrappingSqlRowSetMetaData wapping = new ResultSetWrappingSqlRowSetMetaData(rs.getMetaData()); int columnCount = wapping.getColumnCount(); for (int i = 1; i<=columnCount; i++) { String tableFieldName = wapping.getColumnLabel(i); String beanFieldName = this.tableToBeanMap.get(tableFieldName); Object value = rs.getObject(i); Field beanField = this.beanFielNameToField.get(beanFieldName); if(null == value || beanFieldName == null && beanField == null){ continue; } try { beanField.set(targetObj, value); } catch (IllegalArgumentException e) { if("Integer".equals(value.getClass().getSimpleName()) && "Long".equals(beanField.getType().getSimpleName())) { try { beanField.set(targetObj, Long.valueOf(value.toString())); } catch (IllegalArgumentException | IllegalAccessException e1) { log.error("map set object field error -> Integer convert Long:"+e.getMessage()); } }else if("Boolean".equals(value.getClass().getSimpleName()) && "Integer".equals(beanField.getType().getSimpleName())) { try { beanField.set(targetObj, value.toString().equals("true")?1:0); } catch (IllegalArgumentException | IllegalAccessException e1) { log.error("map set object field error -> Boolean convert Integer:"+e.getMessage()); } }else { log.error("map set object field error:"+e.getMessage()); } } catch (IllegalAccessException e) { log.error("map set object field error:"+e.getMessage()); } } return targetObj; } }