mybatis-plus字典回写工具包
mybatis-plus-wrapper: 简化QueryWrapper的注解实现 (gitee.com)
字典回写就是将一些字典的实际值通过二次查询的方式在接口中把显示值赋值到对象中,避免多表联查,该工具包是通过拦截ResultSetHandler实现resultset的再次赋值
字典回写
第一步 处理插件配置
1@Bean
2public DictTextResultSetHandlerPlugin dictTextResultSetHandlerPlugin(){
3 return new DictTextResultSetHandlerPlugin();
4}
第二步 在实体类或VO中需要回写的字段上增加注解
1@Getter
2@Setter
3@Accessors(chain = true)
4public class Student {
5 private String id;
6
7 private String name;
8
9 @DictText(keyColumn = "id", textColumn = "dict_text", tableName = "sys_dict", target = "sexName")
10 private Integer sex;
11
12 @TableField(exist = false)
13 private String sexName;
14}
通过@DictText注解绑定需要回写的表和字段等属性,在数据查询完成后二次查询将显示值填充到对应字段中,避免频繁的连表查询
需要注意的是字典回写最好在分页接口或数据较少的接口中使用,字典表一定要加索引,否则性能影响较大
@DictText注解介绍
1/**
2 * 要查询的关联表的条件字段名
3 */
4String keyColumn() default "id";
5
6/**
7 * 要查询的关联表的回显字段名
8 */
9String textColumn() default "name";
10
11/**
12 * 实体类中要回写的字段名
13 */
14String target() default "";
15
16/**
17 * 要查询的关联表名称
18 */
19String tableName() default "";
20
21/**
22 * 关联表其他需要的条件字段名
23 */
24String otherColumn() default "dict_id";
25
26/**
27 * 关联表其他需要的条件字段值
28 */
29String otherValue() default "";
30
31/**
32 * 是否为逗号分割 如果设置为true 回写的字典名称同样为逗号分割
33 */
34boolean commaSeparate() default false;
这些属性主要是用来拼接sql,用sql来说明这些字段的意思应该更清楚
1select ${textColumn} from ${tableName} where ${keyColumn} = ${注解的字段的值}
如果有些字典表有dict_id或group_id的字典分组字段,可以用otherColumn和otherValue来查询
1select ${textColumn} from ${tableName} where ${keyColumn} = ${注解的字段的值} and ${otherColumn} = ${otherValue}
如果commaSeparate为true时,代表注解的值为逗号分割字符串,例如1,2,那么回写的结果同样为逗号分割字符串,比如男,女
1select group_concat(${textColumn}) from ${tableName} where ${keyColumn} in (${注解的字段的值})
这种方式同样可以拼接otherColumn = otherValue
当然,目前这种方式可能会导致1,1只返回男,不过感觉应该够用了,先这样吧
作者:wenbo