需求:字典实现类似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. 狂神说Java——Mybatis学习笔记

    前言:配合狂神老师的教学视频使用效果更佳: https://www.bilibili.com/video/BV1NE411Q7Nx/?spm_id_from=333.1007.top_right_ba ...

  2. leetcode每日一题:409. 最长回文串

    409. 最长回文串 给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串. 在构造过程中,请注意区分大小写.比如 "Aa" 不能当做一个回文字符串. 注意 ...

  3. 通过UI自动化方式获取文章、视频信息

    出于学习研究,对某账号的文章.视频分析一翻,尝试使用自动化方式看能否获取相应信息. 获取某号的文章有多重方法: 第一种是通过搜狗浏览器搜索账号(这种方式每天只能获取一篇文章,基本上没啥用.): 第二种 ...

  4. 争论不休的一个话题:金额到底是用Long还是BigDecimal?

    在网上一直流传着一个争论不休的话题:金额到底是用Long还是用BigDecimal?这个话题一出在哪都会引起异常无比激烈的讨论.... 比如说这个观点:算钱用BigDecimal是常识 有支持用Lon ...

  5. 学Windows批处理第一天:使用批处理命令生成一个文件并写入内容

    脚本功能:1.生成一个文件,文件名格式为:yyyymmddhhmmss 2.文件中写入一段文本 操作步骤:1.新建一个文本文档(txt格式) 2.修改文件名为任意名称(我的叫create_file), ...

  6. API 开发的后盾:平台工程提供强力动态支持

    过去几年,开发团队一直在发展传统的 DevOps.一些开发人员认为,CloudOps 或 DeploymentOps 等新实践的兴起将会导致回到孤岛问题.其他人则不愿意在承担所有其他职责之外构建.部署 ...

  7. 基于 EventBridge 构建 SaaS 应用集成方案

    ​简介:事件源是事件驱动的基石,如何获取更多事件源也是 EventBridge 一直在探索和尝试的方向.针对市场上其他云厂商和垂直领域的 Saas 服务,EventBridge 发布了 HTTP So ...

  8. 云原生数据仓库TPC-H第一背后的Laser引擎大揭秘

    简介: 作者| 魏闯先阿里云数据库资深技术专家 一.ADB PG 和Laser 计算引擎的介绍 (一)ADB PG 架构 ADB PG 是一款云原生数据仓库,在保证事务ACID 能力的前提下,主要解决 ...

  9. [FAQ] PHP Warning: json_encode(): double INF does not conform to the JSON spec

    如果待 json 编码元素的数值趋近无穷大,会有这个提示. 比如:小数位超出长度. 解决方式建议保留固定长度的位数,也可以四舍五入. round(sprintf('%.11f', xxxxx), 10 ...

  10. [Mobi] Android Studio NDK 安装

    通过 SDK Manager - SDK Tools 中勾选 NDK 进行安装. 注意,下载来源是 dl.google.com,请准备好能连接到国际互联网. 下载完成后在 sdk 工具里面可以看到 n ...