需求:字典实现类似mybatis-plus中@EnumValue的功能,假设枚举类中应用使用code,数据库存储对应的value

思路:Mybatis支持对Executor、StatementHandler、PameterHandler和ResultSetHandler进行拦截,也就是说会对这4种对象进行代理。mybatis-plus实际上也是通过mybatis提供的拦截功能进行封装,我们在对数据库进行insert\query\update操作时,利用mybatis提供的拦截器对字典做转换

@Intercepts(
{
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
@Signature(type = StatementHandler.class, method = "getBoundSql", args = {}),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
}
)
public class MybatisPlusInterceptor implements Interceptor {
//....
}

写入、查询时参数作转换

@Component
public class DictionaryInterceptor implements InnerInterceptor { private final DictionaryService dictionaryService; public DictionaryInterceptor(@Lazy DictionaryService dictionaryService) {
this.dictionaryService = dictionaryService;
} /**
* {@link Executor#query(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)} 操作前置处理
* <p>
*
* @param executor Executor(可能是代理对象)
* @param ms MappedStatement
* @param parameter parameter
* @param rowBounds rowBounds
* @param resultHandler resultHandler
* @param boundSql boundSql
*/
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { try {
transClassFieldToValue(parameter);
} catch (Exception e) {
throw new RuntimeException(e);
} } /**
* {@link Executor#update(MappedStatement, Object)} 操作前置处理
* <p>
*
* @param executor Executor(可能是代理对象)
* @param ms MappedStatement
* @param parameter parameter
*/
@Override
public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
try {
transClassFieldToValue(parameter);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} private void transClassFieldToValue(Object param) throws IllegalAccessException {
if (param == null) {
return;
}
Object obj;
Field[] fields;
if (param instanceof MapperMethod.ParamMap<?>) {
handleParamMap((MapperMethod.ParamMap<?>) param);
return;
} else {
obj = param;
fields = param.getClass().getDeclaredFields();
} for (Field field : fields) {
if (!field.isAnnotationPresent(Dictionary.class)) {
continue;
} Dictionary annotation = field.getAnnotation(Dictionary.class);
field.setAccessible(true);
if (annotation != null && field.get(obj) != null) {
field.set(obj, dictionaryService.getByCode(annotation.dictionaryType(), (String) field.get(obj)).getValue());
} }
} private void handleParamMap(MapperMethod.ParamMap<?> param) throws IllegalAccessException {
for (Object value : param.values()) {
transClassFieldToValue(value);
}
} }

返回结果转译

@Slf4j
@Component
@Intercepts({@Signature(
type = ResultSetHandler.class,
method = "handleResultSets",
args = {Statement.class})})
public class DictionaryResultInterceptor implements Interceptor { private final DictionaryService dictionaryService; public DictionaryResultInterceptor(@Lazy DictionaryService dictionaryService) {
this.dictionaryService = dictionaryService;
} @Override
public Object intercept(Invocation invocation) throws Throwable {
Object result = invocation.proceed(); if (result instanceof List) {
for (Object line : (List) result) {
transClassFieldToCode(line);
}
} else {
transClassFieldToCode(result);
} return result;
} @Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
} private Object transClassFieldToCode(Object parameter) throws Exception { Field[] fields = parameter.getClass().getDeclaredFields();
for (Field field : fields) {
if (!field.isAnnotationPresent(Dictionary.class)) {
continue;
}
field.setAccessible(true);
Object value = field.get(parameter); Dictionary annotation = field.getAnnotation(Dictionary.class);
if (value != null) {
field.set(parameter, dictionaryService.getByValue(annotation.dictionaryType(), (String) value).getCode());
}
}
return parameter;
}

最后一步别忘了把自定义拦截器注册到mybaits-plus

    @Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(DictionaryInterceptor dictionaryInterceptor) {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(dictionaryInterceptor);
//...其他插件注册 return mybatisPlusInterceptor;
}
@TableName("dictionary")
@Data
public class Dictionary { @Id
private Long id; /**
* 编码,编码+类型唯一
*/
@NotBlank
private String code; /**
* 字典值
*/
@NotBlank
private String value; /**
* 类型
*/
@NotNull
private DictionaryType type; /**
* 描述,用于展示
*/
@TableField(value = "`desc`")
private String desc; }
public interface DictionaryService {

    /**
* 获取分类下所有kv
*
* @param type 分类
* @return
*/
List<Dictionary> listByType(DictionaryType type); /**
* code转换字典
*
* @param type 分类
* @param code 编码
* @return
*/
Dictionary getByCode(DictionaryType type, String code) throws NoSuchElementException; /**
* value转换字典
*
* @param type 分类
* @param value 字典值
* @return
*/
Dictionary getByValue(DictionaryType type, String value);
public enum DictionaryType  {

    USER_ROLE("000001", "用户角色");

    @EnumValue
final String code;
final String desc; DictionaryType(String code, String desc) {
this.code = code;
this.desc = desc;
} public String getCode() {
return code;
} public String getDesc() {
return desc;
}
}

mybaits-plus实现自定义字典转换的更多相关文章

  1. 字典转换成NSString(NSJson)

    //字典转换成字符串 NSDictionary *dict = [NSMutableDictionary dictionary]; NSData *data = [NSJSONSerializatio ...

  2. 数据分析:基于Python的自定义文件格式转换系统

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  3. 2、jeecg 笔记之 t:dictSelect 或 t:dgCol 自定义字典

    1.需求 先说一下需求场景吧,我们知道 jeecg 中提供了下拉,其中包含两种使用场景: 一种是直接通过 t:dictSelect 使用,再就是 t:dgCol  用于表头的列表工具条标签: 总之就是 ...

  4. python3 下列表与字典转换

    在写爬虫的时候,经常需要处理cookie,requests库里的cookie是dict,但是headers['cookie']却是一个key=value的字符串. 下面是几个用推导式实现的转换函数,供 ...

  5. mybatis自定义枚举转换类

    转载自:http://my.oschina.net/SEyanlei/blog/188919 mybatis提供了EnumTypeHandler和EnumOrdinalTypeHandler完成枚举类 ...

  6. MyBatis使用自定义TypeHandler转换类型的实现方法

    From: http://www.manongjc.com/article/15577.html 这篇文章主要介绍了MyBatis使用自定义TypeHandler转换类型的实现方法,本文介绍使用Typ ...

  7. MyBatis使用自定义TypeHandler转换类型

    MyBatis虽然有很好的SQL执行性能,但毕竟不是完整的ORM框架,不同的数据库之间SQL执行还是有差异. 笔者最近在升级 Oracle 驱动至 ojdbc 7 ,就发现了处理DATE类型存在问题. ...

  8. python2.7字典转换成json时中文字符串变成unicode的问题:

    参考:http://blog.csdn.net/u014431852/article/details/53058951 编码问题: python2.7字典转换成json时中文字符串变成unicode的 ...

  9. JS 自定义字典对象

    <script type="text/javascript" language="javascript"> //自定义字典对象 function D ...

  10. python爬虫cookies jar与字典转换

    #将CookieJar转为字典: cookies = requests.utils.dict_from_cookiejar(r.cookies) #将字典转为CookieJar: cookies = ...

随机推荐

  1. #莫比乌斯反演,整除分块,欧拉定理#U137539 虚伪的最小公倍数

    题目 \[\large\prod_{i_1=1}^n\prod_{i_2=1}^n\dots\prod_{i_k=1}^n\frac{i_1*i_2*\dots*i_k}{gcd(i_1,i_2,\d ...

  2. 使用OHOS SDK构建lua

    参照OHOS IDE和SDK的安装方法配置好开发环境. 从github下载源码. 执行如下命令: git clone --depth=1 https://github.com/lua/lua.git ...

  3. 8. Linear Transformations

    8.1 Linear Requires Keys: A linear transformation T takes vectors v to vectors T(v). Linearity requi ...

  4. 【Learning eBPF-3】一个 eBPF 程序的深入剖析

    从这一章开始,我们先放下 BCC 框架,来看仅通过 C 语言如何实现一个 eBPF.如此一来,你会更加理解 BCC 所做的底层工作. 在这一章中,我们会讨论一个 eBPF 程序被执行的完整流程,如下图 ...

  5. Hive设置map和reduce数量

    一.控制hive任务中的map数: 通常情况下,作业会通过input的目录产生一个或者多个map任务. 主要的决定因素有: input的文件总个数,input的文件大小,集群设置的文件块大小(目前为1 ...

  6. TeamViewer 9发布-在Linux下安装运行

    TeamViewer 9发布-在Linux下安装运行 来源:Linux中国  作者:未知 关注我们:    这篇指南介绍了怎么样在 RedHat. CentOS. Fedora 和 Debian. U ...

  7. k8s 深入篇———— 守护容器[九]

    前言 守护容器,也叫做deamonset, 只做整理 正文 顾名思义,DaemonSet 的主要作用,是让你在 Kubernetes 集群里,运行一个 Daemon Pod. 所以,这个 Pod 有如 ...

  8. signalr 应用于微信小程序(一)

    前言 在2017年基于signalr 和微信小程序 写的脚本. 正文 先安装signalr: 1.安装singalr,用nutget就行,用这个包管理就行. 2.使用singalr 3.根据singa ...

  9. 【Nano Framework ESP32篇】WS2812 彩色灯带实验

    地球人皆知,许多物联网教程作者的心中都深爱着一灯大师,所以第一个例程总喜欢点灯,高级一点的会来个"一闪一闪亮晶晶".老周今天要扯的也是和灯有关的,但不单纯地点个灯,那样实在不好玩, ...

  10. vue中 如何实现一个单文件组件

    前端开发人员只要了解过vue.js框架可能都知道单文件组件.vue.js中的单文件组件允许在一个文件中定义一个组件的所有内容.这是一个非常有用的解决方案,在浏览器网页中已经开始提倡这种机制.但是不幸的 ...