对于实体中的created_onupdated_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自动填充时间字段的更多相关文章

  1. 暑假撸系统3- petty热更新 mybatis自动填充时间字段!

    经过了昨天纠结技术选型,和一大堆xml配置,终于把架子搭好了.因为最近一次做java项目也在好多年以前了(毕竟用了pytohn以后谁也不想再回来java了),java的生态发生了长足的进步,本来想从原 ...

  2. MybatisPlus自动填充公共字段的策略

    背景:数据库中多个表有时间字段,并且字段名一致 需求:该时间字段由MybatisPlus自动插入和更新,业务代码无需处理 方法: 一.创建基础实体[BaseEntity],定义需要处理的公共字段(创建 ...

  3. 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 ...

  4. JPA新增entity时自动填充时间,例创建时间,修改时间

    背景:springboot项目,集成JPA,与数据库交互的entity,与用户交互的DTO 问题:添加酒店时,两个字段create_time,update_time,前端不传数据,如果赋值 解决: 1 ...

  5. mybatis plus 增删改自动填充字段值

    说明 本文实现以下需求效果 创建数据时自动填充 createUserId 和 createTime 更新数据时自动填充 updateUserId 和 updateTime(每次修改都自动填充新的 up ...

  6. MP的自动填充功能

    用来进行自动填充时间. 使用注解@TableTield(fill=FieldFill.insert)插入时进行性填充 使用注解@TableTield(fill=FieldFill.Update)更新时 ...

  7. Mybatis plus通用字段自动填充的最佳实践总结

    在进行持久层数据维护(新增或修改)的时候,我们通常需要记录一些非业务字段,比如:create_time.update_time.update_by.create_by等用来维护数据记录的创建时间.修改 ...

  8. mybatis-plus时间字段自动填充

    时间代码自动填充的2种方式 数据库方式 将数据库字段create_time和update_time设置CURRENT_TIMESTAMP,create_time字段后面不需要勾选更新,update_t ...

  9. 小书MybatisPlus第9篇-常用字段默认值自动填充

    本文为Mybatis Plus系列文章的第9篇,前8篇访问地址如下: 小书MybatisPlus第1篇-整合SpringBoot快速开始增删改查 小书MybatisPlus第2篇-条件构造器的应用及总 ...

随机推荐

  1. 如何解决开机出现Missing operating system的故障

    刚刚一哥们火急火燎的来找我,说他的笔记本开机出现一行字,进不了系统,好可怕,里面存了好多资料呢,让我给他看看,看能不能整好.看的出来,把他吓坏了.我开玩笑问他是不是遇到勒索的了,显示的那句话是不是&q ...

  2. 比较集合List<T>集合,前后多了哪些数据,少了哪些数据Except

    1.少了哪些数据 private List<int> GetRoleIdListReduce(List<int> roleIdListOld, List<int> ...

  3. bzoj3435 [Wc2014]紫荆花之恋

    如果这棵树不变的话,就是一个裸的点分树套平衡树,式子也很好推$di+dj<=ri+rj$,$ri-di>=dj-rj$ 平衡树维护$dj-rj$,然后查$ri-di$的$rank$即可. ...

  4. noip 2015 斗地主 大爆搜!!!

    反正肯定是大模拟 但是每一个可以出的牌都搜一定不是最优的 考虑最特殊的出牌方案:顺子(单,对,三) 每一种方案再加上暴力贪心打出剩下的牌的步数 #include<cstdio> #incl ...

  5. LoadRunner接口测试方法

    实际上到目前为止,我所做过的几个关于性能测试的项目,都是在UI页面上能正常访问结束所有的前期功能测试而开始的性能测试.但loadrunner不仅仅只能靠录制回放修改脚本进行性能测试. 往往需要对发送报 ...

  6. Python入门:购物车实例

    product_list=[('iphone',5800), ('pro',120000), ('python book',120), ('Bike',800), ('coffe',39)] #定义商 ...

  7. 利用FT232实现USB转串口

    FT232B数据手册:http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232BL_BQ.pdf 常用的USB转串口的芯片有F ...

  8. 深度学习之注意力机制(Attention Mechanism)和Seq2Seq

    这篇文章整理有关注意力机制(Attention Mechanism )的知识,主要涉及以下几点内容: 1.注意力机制是为了解决什么问题而提出来的? 2.软性注意力机制的数学原理: 3.软性注意力机制. ...

  9. 部署Chart应用并使用.net core读取Kubernetes中的configMap

    上一篇文章讲了 k8s使用helm打包chart并上传到腾讯云TencentHub,今天就讲一下使用Helm部署应用并使用configMap代替asp.net core 中的appsettings.j ...

  10. Boosting(提升方法)之GBDT

    一.GBDT的通俗理解 提升方法采用的是加法模型和前向分步算法来解决分类和回归问题,而以决策树作为基函数的提升方法称为提升树(boosting tree).GBDT(Gradient Boosting ...