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

import java.lang.reflect.Field;
import java.lang.reflect.Method;
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 <E> implements RowMapper{
	private Class<E> classInfo;
	private Map<String, String> tableToBeanMap;	

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

	@Override
	public E mapRow(ResultSet rs, int index) throws SQLException {
		boolean hasImplementPointCut = false;
		Class[] interfaceArr = this.classInfo.getInterfaces();
		for(int i=0; i<interfaceArr.length; ++i){
			if(interfaceArr[i].getName().equals("com.taover.repository.EntityPointCut")){
				hasImplementPointCut = true;
				break;
			}
		}
		
		E targetObj;
		try {
			targetObj = this.classInfo.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		if(hasImplementPointCut){
			try{
				Method beforeMethod = this.classInfo.getDeclaredMethod("before");
				beforeMethod.setAccessible(true);
				beforeMethod.invoke(targetObj);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		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();
			}
		}
		
		if(hasImplementPointCut){
			try{
				Method afterMethod = this.classInfo.getDeclaredMethod("after");
				afterMethod.setAccessible(true);
				afterMethod.invoke(targetObj);
			}catch(Exception e){
				e.printStackTrace();
			}	
		}
		
		return targetObj;
	}
}