Mybatis-Plus自定义TypeHandler的使用

序号:02

  Mybatis-Plus可通过自定义的TypeHandler实现某个属性在插入数据库以及查询时的自动转换,本例中是要将Map类型的属性转化成CLOB,然后存入数据库。由于是复杂的Map,mp自带的json转换器会丢失部分信息。

类型转换器可以通过注解配置 java 类型和 jdbc 类型:

  • @MappedTypes:注解配置 java 类型
  • @MappedJdbcTypes:注解配置 jdbc 类型

定义:

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

@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class WeightListTypeHandler extends AbstractJsonTypeHandler<Object> {

private static Gson gson = new Gson();

private final Class<?> type;

public WeightListTypeHandler(Class<?> type) {
if (log.isTraceEnabled()) {
log.trace("WeightListTypeHandler(" + type + ")");
}
Assert.notNull(type, "Type argument cannot be null");
this.type = type;
}

@Override
protected Object parse(String json) {
Type type1 = new TypeToken<Map<String, List<WeightItem>>>(){}.getType();
return gson.fromJson(json, type1);
}

@Override
protected String toJson(Object obj) {
return gson.toJson(obj);
}

public static void setGson(Gson gson) {
Assert.notNull(gson, "Gson should not be null");
WeightListTypeHandler.gson = gson;
}
}

使用:
  注意@TableName 注解 autoResultMap 属性

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

@Data
@NoArgsConstructor
@TableName(value = "mix_target",autoResultMap = true)
public class MixTarget extends Model<MixTarget> {

@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
*指标描述
*/
@TableField("description")
private String description;
/**
* 指标名
*/
@TableField("name")
private String name;
/**
* 对应属性名
*/
@TableField("property_name")
private String propertyName;
/**
* 起始点类型
*/
@TableField("source_type")
private String sourceType;
/**
* 属性对应权值列表
* key 属性名 value指定条件下的权值
*/
@TableField(value = "weight_list",typeHandler = WeightListTypeHandler.class,jdbcType = JdbcType.CLOB)
private Map<String, List<WeightItem>> weightList;

/**
* 运行状态
* 0 新建未运行
* 1 运行中
* 2 已运行 成功
* 3 已运行 失败
*/
@TableField("status")
private Integer status;

/**
* 是否可用
* 1 true
* 0 false
*/
@TableField("enable")
private Integer enable;

@TableField("create_time")
private LocalDateTime createTime;
}

Mybatis-Plus自定义TypeHandler的使用

http://leofitz1024.github.io/2021/05/31/Mybatis-Plus/02/

作者

xchen

发布于

2021-05-31

更新于

2021-11-22

评论