GeXiangDong

精通Java、SQL、Spring的拼写,擅长Linux、Windows的开关机

0%

Mybatis通用JSON Type Handler

使用jackson来实现json和object之间转换。
使用的时候在resultMap中,对应的列配置,例如:

1
2
<result column="specs" property="specs" 
typeHandler="cn.devmgr.tutorial.typehandler.JsonTypeHandler" />
1
2
3
update table_xxx 
set colA=#{beanA.xxx, typeHandler=cn.devmgr.tutorial.typehandler.JsonTypeHandler}
where id=xx

JsonTypeHandler.java

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
package cn.devmgr.tutorial.typehandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
private final static Log log = LogFactory.getLog(JsonTypeHandler.class);

private static ObjectMapper objectMapper;
private Class<T> type;
static {
objectMapper = new ObjectMapper();
}

public JsonTypeHandler(Class<T> type) {
if(log.isTraceEnabled()) {
log.trace("JsonTypeHandler(" + type + ")");
}
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
}
this.type = type;
}

private T parse(String json) {
try {
if(json == null || json.length() == 0) {
return null;
}
return objectMapper.readValue(json, type);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private String toJsonString(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}

@Override
public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
return (T) parse(rs.getString(columnName));
}

@Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return (T) parse(rs.getString(columnIndex));
}

@Override
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return (T) parse(cs.getString(columnIndex));
}

@Override
public void setNonNullParameter(PreparedStatement ps, int columnIndex, T parameter, JdbcType jdbcType) throws SQLException {
ps.setString(columnIndex, toJsonString(parameter));

}

}