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篇-条件构造器的应用及总 ...
随机推荐
- fatal: HttpRequestException encountered 解决方法
fatal: HttpRequestException encountered解决方法 之前在windows下一段时间git push都没什么问题,最近一旦提交就会弹出 无论是push前先将远程 ...
- 用java代码将从数据库中取出的具有父子关系的数据转成json格式
思路:①.取出数据中的所有父节点放入一个集合中②.取出数据中所有为该父节点的子节点放入另一个集合中③.用到迭代的方法将子节点一层一层的遍历工具类:package com.assasion.test;i ...
- Android 应用加固(乐固)操作说明
此处引用腾讯云对加固的优点说明如下: 为什么应用需要加固? 若应用不做任何安全防护,极易被病毒植入.广告替换.支付渠道篡改.钓鱼.信息劫持等,严重侵害开发者的利益. 应用进行安全防护,防止应用分发后, ...
- json数组的解析
一直以来,经常会遇到json数据从前端或者我经常从网站上爬取的数据中会有json数据的存在,这样如果想要获取json数据就需要对json数据进行解析 在开发过程中,经常需要和别的系统交换数据,数据交换 ...
- Robot Framework 源码解析(1) - java入口点
一直很好奇Robot Framework 是如何通过关键字驱动进行测试的,好奇它是如何支持那么多库的,好奇它是如何完成截图的.所以就打算研究一下它的源码. 这是官方给出的Robot framework ...
- .net core 注入机制与Autofac
本来是要先出注入机制再出 管道 的,哈哈哈……就是不按计划来…… 这里扯扯题外话:为什么要注入(DI,dependency-injection),而不用 new 对象? 可能我们都很清楚,new 对象 ...
- 【Teradata SQL】从中文数字字母混合字符串中只提取数字regexp_substr
目标:从中文数字字母的字符串中只提取数字 sel regexp_substr('mint choc中文11国1','\d+')
- 看板记录工具wekan
wekan 1. 功能 看板工具 2. 安装 环境: centos7.4 安装链接 snap方式 安装脚本(root用户) #!/bin/bash yum makecache fast yum ins ...
- Mybatis高级查询之一对一查询的四种方法
目录 1. 一对一查询 1.1 一对一嵌套结果查询 1.2 使用resultMap配置一对一映射 1.3 使用resultMap的association标签配置一对一映射 1.4 associatio ...
- Python基础 列表介绍、使用
第3章 学习目标: 列表是什么以及如何使用列表元素.列表让你能够在一个地方存储成组的信息,其中可以只包含几个元素,也可以包含数百万个元素.列表是新手可直接使用的最强大的Python功能之一,它融合了众 ...