CustomJdbcTemplateRowMapper.java 1.41 KB
package com.taover.repository;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSetMetaData;

public class CustomJdbcTemplateRowMapper implements RowMapper{
	private Class classInfo;
	private Map<String, String> tableToBeanMap;	

	public CustomJdbcTemplateRowMapper(Class classInfo, Map<String, String> tableToBeanMap) {
		this.classInfo = classInfo;
		this.tableToBeanMap = tableToBeanMap;
	}

	@Override
	public Object mapRow(ResultSet rs, int index) throws SQLException {
		Object 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);
			try {
				if(null != value && beanFieldName != null){					
					Field beanField = this.classInfo.getDeclaredField(beanFieldName);
					beanField.setAccessible(true);
					beanField.set(targetObj, value);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return targetObj;
	}
}