PostgreSQLJavaMyBatisPostgreSQLSpring Boot
2025-10-08 09:01阅读:38评论:0
Mybatis PostgreSQL数据库 jsonb类型处理器
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
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;import org.postgresql.util.PGobject;import org.springframework.stereotype.Component; import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException; @Componentpublic class JOSNBTypeHandler extends BaseTypeHandler<JSON> { @Override public void setNonNullParameter(PreparedStatement ps, int i, JSON parameter, JdbcType jdbcType) throws SQLException { if(null != parameter){ PGobject pGobject = new PGobject(); pGobject.setType("jsonb"); pGobject.setValue(toJson(parameter)); ps.setObject(i, pGobject); } } @Override public JSON getNullableResult(ResultSet rs, String columnName) throws SQLException { String value = rs.getString(columnName); return convert(value); } @Override public JSON getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String value = rs.getString(columnIndex); return convert(value); } @Override public JSON getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String value = cs.getString(columnIndex); return convert(value); } private JSON convert(String value){ if(notNull(value)){ return (JSON) JSON.parse(value); } return null; } private boolean notNull(String value){ return (null != value && !value.isEmpty()); } public String toJson(Object obj) { return JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty); }}