CustomJdbcTemplateRowMapper.java
2.18 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
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;
}
}