对于实体中的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. 安装Navicat for MySQL

    注: 以下内容引自 https://www.cnblogs.com/da19951208/p/6403607.html Navicat for MySQL下载.安装与破解   一:下载Navicat ...

  2. 在当前图纸中创建一个表格, AcDbTable 类

    Table 例子学习笔记在这个例子中,ARX向我们展示了ACDBTABLE类的一些基本操作方法,ACDBTABLE类是ACAD2005及其以后的产品,应该是说ACDBDATATABLE的升级产品,Ac ...

  3. BZOJ_1345_[Baltic2007]序列问题Sequence_单调栈

    BZOJ_1345_[Baltic2007]序列问题Sequence_单调栈 Description 对于一个给定的序列a1,…,an,我们对它进行一个操作reduce(i),该操作将数列中的元素ai ...

  4. appium 提示报错“TypeError: 'unicode' object is not callable”的解决方式!

    这里提到的这个报错,是小错误且容易经常会犯,有时需要特别注意使用. 目的要求结果:根据某个元素的id值获取到对应id的text值,并且将获取的text值与本身存在的text值做比较,查看text值是否 ...

  5. Android缓存机制——LruCache

    概述 LruCache的核心原理就是对LinkedHashMap的有效利用,它的内部存在一个LinkedHashMap成员变量,值得注意的4个方法:构造方法.get.put.trimToSize LR ...

  6. Failed to fetch URL http://dl-ssl.google.com/android/repository/addons_list-2.xml, reason:

    http://blog.csdn.net/gyming/article/details/8168166/ 最近接受的这个项目需要Android SDK Tools revision 22.6.2 or ...

  7. 5G+边缘计算,着眼可见的未来

    在 2019 年 2 月巴塞罗那举办的 MWC(世界移动通讯大会)上,华为手机带来了一款超薄的 5G 折叠屏手机 Mate X.这款手机将折叠屏和 5G 结合在一起,引起了不少人的关注与舆论,而昂贵的 ...

  8. MySQL 复制 - 性能与扩展性的基石 2:部署及其配置

    正所谓理论造航母,现实小帆船.单有理论,不动手实践,学到的知识犹如空中楼阁.接下来,我们一起来看下如何一步步进行 MySQL Replication 的配置. 为 MySQL 服务器配置复制非常简单. ...

  9. 「Continuous_integration, CI」为什么要持续集成?

    前言   什么是持续集成,为什么要持续集成?本文对持续集成前后两种开发实践做了对比分析,从而直观的感受到持续集成的好处. 在说持续集成之前,先说一下传统的开发模式: 传统模式: 传统模式过程如下: 传 ...

  10. TensorFlow从1到2(四)时尚单品识别和保存、恢复训练数据

    Fashion Mnist --- 一个图片识别的延伸案例 在TensorFlow官方新的教程中,第一个例子使用了由MNIST延伸而来的新程序. 这个程序使用一组时尚单品的图片对模型进行训练,比如T恤 ...