CustomJdbcTemplateRowMapper.java
2.79 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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 <E> implements RowMapper<E>{
Log log = LogFactory.getLog(this.getClass());
private Map<String, Field> beanFielNameToField = new HashMap<String, Field>();
private Class<E> classInfo;
private Map<String, String> tableToBeanMap;
public CustomJdbcTemplateRowMapper(Class<E> classInfo, Map<String, String> 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;
}
}