CustomJdbcTemplateRowMapper.java
1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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;
}
}