mybaits-plus实现自定义字典转换
需求:字典实现类似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实现自定义字典转换的更多相关文章
- 字典转换成NSString(NSJson)
//字典转换成字符串 NSDictionary *dict = [NSMutableDictionary dictionary]; NSData *data = [NSJSONSerializatio ...
- 数据分析:基于Python的自定义文件格式转换系统
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
- 2、jeecg 笔记之 t:dictSelect 或 t:dgCol 自定义字典
1.需求 先说一下需求场景吧,我们知道 jeecg 中提供了下拉,其中包含两种使用场景: 一种是直接通过 t:dictSelect 使用,再就是 t:dgCol 用于表头的列表工具条标签: 总之就是 ...
- python3 下列表与字典转换
在写爬虫的时候,经常需要处理cookie,requests库里的cookie是dict,但是headers['cookie']却是一个key=value的字符串. 下面是几个用推导式实现的转换函数,供 ...
- mybatis自定义枚举转换类
转载自:http://my.oschina.net/SEyanlei/blog/188919 mybatis提供了EnumTypeHandler和EnumOrdinalTypeHandler完成枚举类 ...
- MyBatis使用自定义TypeHandler转换类型的实现方法
From: http://www.manongjc.com/article/15577.html 这篇文章主要介绍了MyBatis使用自定义TypeHandler转换类型的实现方法,本文介绍使用Typ ...
- MyBatis使用自定义TypeHandler转换类型
MyBatis虽然有很好的SQL执行性能,但毕竟不是完整的ORM框架,不同的数据库之间SQL执行还是有差异. 笔者最近在升级 Oracle 驱动至 ojdbc 7 ,就发现了处理DATE类型存在问题. ...
- python2.7字典转换成json时中文字符串变成unicode的问题:
参考:http://blog.csdn.net/u014431852/article/details/53058951 编码问题: python2.7字典转换成json时中文字符串变成unicode的 ...
- JS 自定义字典对象
<script type="text/javascript" language="javascript"> //自定义字典对象 function D ...
- python爬虫cookies jar与字典转换
#将CookieJar转为字典: cookies = requests.utils.dict_from_cookiejar(r.cookies) #将字典转为CookieJar: cookies = ...
随机推荐
- 部署解压版mysql
1.检查系统是否安装过mysql //检查系统中有无安装过mysql rpm -qa|grep mysql //查询所有mysql 对应的文件夹,全部删除 whereis mysql find / - ...
- C# sqlclient数据库事务BeginTransaction()详解
重载 重载 BeginTransaction() 开始数据库事务. BeginTransaction(IsolationLevel) 以指定的隔离级别启动数据库事务. BeginTransaction ...
- 如何跑各种check
如何进行 Fastcheck? 首先,导入环境变量: export CODE_BASE=/data/openGauss-server export BINARYLIBS=/data/openGauss ...
- 鸿蒙HarmonyOS实战-ArkUI组件(Navigation)
一.Navigation Navigation组件通常作为页面的根容器,支持单页面.分栏和自适应三种显示模式.开发者可以使用Navigation组件提供的属性来设置页面的标题栏.工具栏.导航栏等. 在 ...
- mysql 必知必会整理—sql 通配符[四]
前言 简单介绍一下sql 高级过滤. 正文 首先简单介绍一下通配符,用来匹配值的一部分的特殊字符. 搜索模式(search pattern)① 由字面值.通配符或两者组合构成的搜索条件. 前面介绍操作 ...
- 重新点亮linux 命令树————守护进程[二十三]
前言 简单整理一下守护进程. 正文 守护进程一般是开机启动的. 使用nohup 与 & 符号配合运行一个命令 nohup命令使进程忽略hangup(挂起)信号 使用tail 查看log文件. ...
- 远程主机可能不符合glibc和libstdc++ VS Code服务器的先决条件
报错信息 VSCode无法连接远程服务器,终端一直提醒: [22:46:01.906] > Waiting for server log... [22:46:01.936] > Waiti ...
- C#的基于.net framework的Dll模块编程(一) - 编程手把手系列文章
从此博文开始分几篇介绍C#的开发.这次讲讲C#的.net framework的Dll文件类库模块的编程方法. 对于Windows来说,要运行应用程序要基于Dll类库和Exe执行文件.对于笔者来说,模块 ...
- MySQL实战—更新过程
和查询流程不同的是,更新流程涉及两个重要的日志模块:redo log(重做日志)和 binlog(二进制日志). redo log redo log通常是物理日志,记录的是数据页的物理修改,而不是某一 ...
- EventBridge消息路由|高效构建消息路由能力
简介:企业数字化转型过程中,天然会遇到消息路由,异地多活,协议适配,消息备份等场景.本篇主要通过 EventBridge 消息路由的应用场景和应用实验介绍,帮助大家了解如何通过 EventBridg ...