mybatis自动填充时间字段
对于实体中的created_on
和updated_on
来说,它没有必要被开发人员去干预,因为它已经足够说明使用场景了,即在插入数据和更新数据时,记录当前时间,这对于mybatis来说,通过拦截器是可以实现的,记得之前说过在jpa中实现的方法,主要通过jpa的注解实现的,因为今天的mybatis需要用到java的拦截器。
定义两个注解
@Retention(RetentionPolicy.RUNTIME)
@Target( {ElementType.FIELD})
public @interface CreatedOnFuncation {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target( {ElementType.FIELD})
public @interface UpdatedOnFuncation {
String value() default "";
}
使用这两个注解
@Getter
@Builder(toBuilder = true)
@ToString
public class UserInfo {
private Long id;
private String name;
private String email;
@CreatedOnFuncation
private LocalDateTime createdOn;
@UpdatedOnFuncation
private LocalDateTime updatedOn;
}
定义拦截器,重写赋值的语句
/**
* 时间拦截器.
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
@Intercepts({@Signature(
type = org.apache.ibatis.executor.Executor.class,
method = "update",
args = {MappedStatement.class, Object.class})})
public class CreateUpdateTimeInterceptor extends AbstractSqlParserHandler implements Interceptor {
private Properties properties;
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// 获取 SQL 命令
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
// 获取参数
Object parameter = invocation.getArgs()[1];
// 获取私有成员变量
Field[] declaredFields = parameter.getClass().getDeclaredFields();
if (parameter.getClass().getSuperclass() != null) {
Field[] superField = parameter.getClass().getSuperclass().getDeclaredFields();
declaredFields = ArrayUtils.addAll(declaredFields, superField);
}
// 是否为mybatis plug
boolean isPlugUpdate = parameter.getClass().getDeclaredFields().length == 1
&& parameter.getClass().getDeclaredFields()[0].getName().equals("serialVersionUID");
//兼容mybatis plus的update
if (isPlugUpdate) {
Map<String, Object> updateParam = (Map<String, Object>) parameter;
Class<?> updateParamType = updateParam.get("param1").getClass();
declaredFields = updateParamType.getDeclaredFields();
if (updateParamType.getSuperclass() != null) {
Field[] superField = updateParamType.getSuperclass().getDeclaredFields();
declaredFields = ArrayUtils.addAll(declaredFields, superField);
}
}
for (Field field : declaredFields) {
// insert
if (field.getAnnotation(CreatedOnFuncation.class) != null) {
if (SqlCommandType.INSERT.equals(sqlCommandType)) {
field.setAccessible(true);
field.set(parameter, new Timestamp(System.currentTimeMillis()));
}
}
// update
if (field.getAnnotation(UpdatedOnFuncation.class) != null) {
if (SqlCommandType.INSERT.equals(sqlCommandType)
|| SqlCommandType.UPDATE.equals(sqlCommandType)) {
field.setAccessible(true);
//兼容mybatis plus的update
if (isPlugUpdate) {
Map<String, Object> updateParam = (Map<String, Object>) parameter;
field.set(updateParam.get("param1"), new Timestamp(System.currentTimeMillis()));
} else {
field.set(parameter, new Timestamp(System.currentTimeMillis()));
}
}
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof org.apache.ibatis.executor.Executor) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties prop) {
this.properties = prop;
}
}
添加测试用例
@Test
public void insert() {
UserInfo userInfo = UserInfo.builder()
.name("lind")
.email("test@sina.com")
.build();
userInfoMapper.insert(userInfo);
System.out.println("userinfo:" + userInfo.toString());
}
解决是我们所预想的,created_on和updated_on被自动赋上值了。
userinfo:UserInfo
(
id=1085780948955959297,
name=lind,
email=test@sina.com,
createdOn=2019-01-17T14:08:45.665,
updatedOn=2019-01-17T14:08:45.665
)
mybatis自动填充时间字段的更多相关文章
- 暑假撸系统3- petty热更新 mybatis自动填充时间字段!
经过了昨天纠结技术选型,和一大堆xml配置,终于把架子搭好了.因为最近一次做java项目也在好多年以前了(毕竟用了pytohn以后谁也不想再回来java了),java的生态发生了长足的进步,本来想从原 ...
- MybatisPlus自动填充公共字段的策略
背景:数据库中多个表有时间字段,并且字段名一致 需求:该时间字段由MybatisPlus自动插入和更新,业务代码无需处理 方法: 一.创建基础实体[BaseEntity],定义需要处理的公共字段(创建 ...
- mybatis的判定时间字段问题 java.lang.IllegalArgumentException: invalid comparison: cn.hutool.core.date.DateTime and java.lang.String
今天听组员说: mybatis在3.30版本及以上判定时间时 <if test="date_time != null and date_time != '' "> da ...
- JPA新增entity时自动填充时间,例创建时间,修改时间
背景:springboot项目,集成JPA,与数据库交互的entity,与用户交互的DTO 问题:添加酒店时,两个字段create_time,update_time,前端不传数据,如果赋值 解决: 1 ...
- mybatis plus 增删改自动填充字段值
说明 本文实现以下需求效果 创建数据时自动填充 createUserId 和 createTime 更新数据时自动填充 updateUserId 和 updateTime(每次修改都自动填充新的 up ...
- MP的自动填充功能
用来进行自动填充时间. 使用注解@TableTield(fill=FieldFill.insert)插入时进行性填充 使用注解@TableTield(fill=FieldFill.Update)更新时 ...
- Mybatis plus通用字段自动填充的最佳实践总结
在进行持久层数据维护(新增或修改)的时候,我们通常需要记录一些非业务字段,比如:create_time.update_time.update_by.create_by等用来维护数据记录的创建时间.修改 ...
- mybatis-plus时间字段自动填充
时间代码自动填充的2种方式 数据库方式 将数据库字段create_time和update_time设置CURRENT_TIMESTAMP,create_time字段后面不需要勾选更新,update_t ...
- 小书MybatisPlus第9篇-常用字段默认值自动填充
本文为Mybatis Plus系列文章的第9篇,前8篇访问地址如下: 小书MybatisPlus第1篇-整合SpringBoot快速开始增删改查 小书MybatisPlus第2篇-条件构造器的应用及总 ...
随机推荐
- System.out.println()
System是java.lang中的类,out为System中的一个静态数据成员,out是java.io.PrintStream类的对象,而println()是java.io.PrintStream类 ...
- 【Richard 的刷(水)题记录】
大概想了想,还是有个记录比较好. 9/24 网络流一日游: 最大流:bzoj1711[Usaco2007 Open]Dining 拆点 BZOJ 3993 Sdoi2015 星际战争 二分 P.S.这 ...
- bzoj 3126 单调队列优化dp
能转移的最左是其左边完整区间的最右左端点,最右是能覆盖它的最左左端点-1 #pragma GCC optimize ("O3") #include<cstdio> #i ...
- noip 2015 斗地主 大爆搜!!!
反正肯定是大模拟 但是每一个可以出的牌都搜一定不是最优的 考虑最特殊的出牌方案:顺子(单,对,三) 每一种方案再加上暴力贪心打出剩下的牌的步数 #include<cstdio> #incl ...
- BZOJ_2073_[POI2004]PRZ_状压DP
BZOJ_2073_[POI2004]PRZ_状压DP 题意: 一只队伍在爬山时碰到了雪崩,他们在逃跑时遇到了一座桥,他们要尽快的过桥. 桥已经很旧了, 所以它不能承受太重的东西. 任何时候队伍在桥上 ...
- BZOJ_4197_[Noi2015]寿司晚宴_状态压缩动态规划
BZOJ_4197_[Noi2015]寿司晚宴_状态压缩动态规划 Description 为了庆祝 NOI 的成功开幕,主办方为大家准备了一场寿司晚宴.小 G 和小 W 作为参加 NOI 的选手,也被 ...
- subprocess实时获取结果和捕获错误
需要调用命令行来执行某些命令,主要是用 subprocess 实时获取结果和捕获错误,发现subprocess的很多坑. subprocess 普通获取结果方式,其需要命令完全执行才能返回结果: im ...
- Netty4.x整合SpringBoot2.x使用Protobuf3详解
前言 本篇文章主要介绍的是SpringBoot整合Netty以及使用Protobuf进行数据传输的相关内容.Protobuf会介绍下用法,至于Netty在netty 之 telnet HelloWor ...
- 初探奥尔良(Orleans)
由于工作上关系目前经常被各种并发数据问题搞得焦头烂额,要么要性能舍弃数据上得一致性,要么要一致性但是却得到了特别糟糕的响应.难道鱼和熊掌真的无法兼得吗? 然后找到了类似奥尔良这种基于Actor模型的k ...
- 5.1基于JWT的认证和授权「深入浅出ASP.NET Core系列」
希望给你3-5分钟的碎片化学习,可能是坐地铁.等公交,积少成多,水滴石穿,码字辛苦,如果你吃了蛋觉得味道不错,希望点个赞,谢谢关注. Cookie-Based认证 认证流程 我们先看下传统Web端的认 ...