首页 > 其他分享 >MyBatis操作数据表时自动设置创建时间和更新时间

MyBatis操作数据表时自动设置创建时间和更新时间

时间:2024-06-04 17:11:34浏览次数:13  
标签:insert updateTime update entity 数据表 时间 LocalDateTime MyBatis createTime

需求

     使用 MyBatis 插入或修改某条记录时,能自动设置数据表里的 create_time 和 update_time 字段,即自动给实体类对象的 createTime 和 updateTime 属性赋值。(如果使用 MyBatis-Plus,该功能很容易实现,现在针对的场景是仅使用 MyBatis)

解决方案

​    使用AOP的原理,在执行新增或修改前,用反射获取方法的第一个参数,给它的 createTime 和 updateTime 属性赋值 。(约定:方法的第一个参数是要操作的实体类)

代码

1、自定义注解:

/**
 * 标识 需要自动填充的方法
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    OperationType value();
}

2、枚举类:指定方法类型是 insert 还是 update,insert 操作需要 同时设置 createTime 和 updateTime,update操作只设置 updateTime 。

/**
 * 操作类型
 */
public enum OperationType {
    UPDATE,
    INSERT
}

3、切面:

/**
 * 自定义切面 自动填充公共字段
 */
@Aspect
@Component
public class AutoFillAspect {

    /**
     * 切入点
     *   * com.example.mapper.*.*(..)  需要能定位到mapper接口的位置
     *   com.example.autofill.AutoFill  是上面写的自定义注解的路径
     */
    @Pointcut("execution(* com.example.mapper.*.*(..)) && @annotation(com.example.autofill.AutoFill)")
    public void autoFillPointCut() {
    }


    /**
     * 前置通知,insert update之前 填充时间
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        //获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
        OperationType operationType = autoFill.value();//获得数据库操作类型   insert  update
        // insert  update  方法参数是实体类 需要放在第一个
        // 获取实体参数对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];
        // 为 createTime 和 updateTime 属性赋值
        LocalDateTime localDateTime = LocalDateTime.now();
        if (operationType == OperationType.INSERT) {
            // insert 操作 两个时间都赋值
            Method setCreateTime = entity.getClass().getMethod(SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = entity.getClass().getMethod(SET_UPDATE_TIME, LocalDateTime.class);
            setCreateTime.invoke(entity, localDateTime);
            setUpdateTime.invoke(entity, localDateTime);
        } else if (operationType == OperationType.UPDATE) {
            // update 操作 只设置更新时间
            Method setUpdateTime = entity.getClass().getMethod(SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateTime.invoke(entity, localDateTime);
        }
    }
}

测试案例

实体类:

import lombok.Data;
import java.time.LocalDateTime;

@Data
public class User{
    private Long id;
    private String name;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

mapper接口:

/**
 * 添加用户
 */
@AutoFill(value = OperationType.INSERT)
Integer addUser(User user);

xml文件:

<insert id="addUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
    insert into user(name, create_time, update_time)
    values (#{name}, #{createTime}, #{updateTime})
</insert>

测试方法:

@Resource
private UserMapper userMapper;

void test(){
    User user = new User();
    user.setName("张三");  // 无需手动设置 createTime 和 updateTime 属性
    userMapper.addUser(user);
}

标签:insert,updateTime,update,entity,数据表,时间,LocalDateTime,MyBatis,createTime
From: https://www.cnblogs.com/codermario/p/18231284

相关文章

  • MyBatis-Plus如何关闭SQL日志打印详解
    前言MyBatis-Plus配置关闭打印SQL日记失效追本溯源,关闭打印日记是真的失效吗?找到问题与解决问题 总结 前言前段时间公司的同事都过来问我,hua哥公司的项目出问题了,关闭不了打印sql日记,项目用宝塔自己部署的,磁盘满了才发现大量的打印sql日记,他们百度过都按照网上的配置......
  • zabbix监控域名到期时间
    #获取证书过期时间脚本cat/etc/zabbix/scripts/base/check-http-expire.sh#!/bin/bashhost=$1#end_date=`whois-H $host|grep"RegistryExpiryDate"|awk'{print$NF}'`end_date=`whois-H $host|egrep"RegistryExpiryDate|ExpirationTime&qu......
  • 数据库的增删改查、数据表的增删改查、数据相关的插入、查看、更改、删除
    【一】操作MySQL数据库【1】数据库相关(1)创建数据库createdatabase[ifnotexists]数据库名字[charsetset字符编码集];#例如:createdatabaseifnotexistsday01;#设置库的默认编码createdatabasesdb1charset='gbk';(2)查看当前所有数据库showdatabases;--......
  • mybatis逆向生成文件攻略
    pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache......
  • 粉笔科技扭亏为盈另面:一年时间股价跌超六成,消费者投诉问题不少
    《港湾商业观察》施子夫公开数据显示,2024年国考报名人数首破300万。在公考热度不减的背景下相对应公考培训领域的几家上市公司也备受大众关注。4月25日,粉笔有限公司(以下简称,粉笔或粉笔科技,02469.HK)披露023年度业绩公告,显示公司营收与净利双双增长。在教育培训赛道,以烧钱换......
  • 用 python 绘制不同时间序列数据的图表
    我有两个不同的时间序列数据,如下所示。我希望将这两组不同的时间序列值放在一个图表中。代码如下,不幸的是,这并不是我想要的效果。第二张图片就是我想要的效果......
  • 番茄时钟|FlowUs息流自带各种时间管理模版
    番茄时钟方法,又称为番茄工作法,是由弗朗西斯科·西里洛(FrancescoCirillo)在20世纪80年代末发明的一种时间管理工具。这个方法的核心是将工作时间分割成短小的、专注的时间段,通常为25分钟,称为一个“番茄时间”,之后休息5分钟,每完成四个番茄时间后,休息时间可以延长到15-30分钟。番......
  • springboot集成mybatis
    springboot集成mybatis1,整体结构2,需要的依赖<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>......
  • 安徽京准 NTP时间服务器(网络授时服务器)技术应用方案
    安徽京准NTP时间服务器(网络授时服务器)技术应用方案安徽京准NTP时间服务器(网络授时服务器)技术应用方案京准电子科技官微——ahjzsz摘要:药食品质量安全追溯系统中各计算机设备间必须保持精确的时间同步,才能保证对药品食品各种相关信息的记录准确可靠。基于网络时间协议(NTP),结......
  • 详解和实现数据表格中的行数据合并功能
    theme:smartblue前言需求场景:在提供了数据查看和修改的表格视图中(如table、a-table等…),允许用户自行选择多行数据,依据当前状态进行特定列数据的合并操作。选中的数据将统一显示为选中组的首条数据值。同时,页面会即时反馈显示合并后的效果,提供直观的操作反馈。效果......