MyBatis拦截器如何自动设置创建时间和修改时间

 更新时间:2025年02月11日 11:09:36   作者:伦敦城下的小鞋匠  
文章介绍了如何通过实现MyBatis的Interceptor接口,在实体类中自动设置创建时间和修改时间,从而提高开发效率

前言

在日常的插入和修改的时候要频繁的插入时间,浪费时间,可以通过实现mybatis的 Intercepts注解来实现,获取实体,并且在实体里面插入日期

一、实现Interceptor接口,并写相关逻辑

package com.ruoyi.common.filter;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;


/**
 *  Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)   拦截执行器的方法
	ParameterHandler (getParameterObject, setParameters)	拦截参数的处理
	ResultSetHandler (handleResultSets, handleOutputParameters)	拦截结果集的处理
	StatementHandler (prepare, parameterize, batch, update, query) 拦截Sql语法构建的处理
 * @author Administrator
 *
 */
@Intercepts({@Signature(type = Executor.class,method = "update",args = {MappedStatement.class,Object.class})})
@Component
public class HandleTimeInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		 Object[] args = invocation.getArgs();
		 MappedStatement mappedStatement = (MappedStatement) args[0];
		 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		 if(sqlCommandType== SqlCommandType.UPDATE) {
			 if(args[1] instanceof BaseEntity) {
				BaseEntity baseEntity = (BaseEntity) args[1];
				baseEntity.setUpdateTime(new Date());
				String userId="";
				 try
				 {
					 userId= SecurityUtils.getUserId().toString();
				 }catch (Exception e){
					// throw new BaseException("当前没有登录人");

				 }
				baseEntity.setUpdateBy(userId);
			 }
		 }else if(sqlCommandType==SqlCommandType.INSERT) {
			 if(args[1] instanceof BaseEntity) {
				BaseEntity baseEntity = (BaseEntity) args[1];
				baseEntity.setCreateTime(new Date());
				String userId="";
				try
				{
				 userId= SecurityUtils.getUserId().toString();
				}catch (Exception e){
					//throw new BaseException("当前没有登录人");
				}
				baseEntity.setCreateBy(userId);
			}
		 }

		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}
}

二、将插件注册到mybatis 的配置文件 mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 全局参数 -->
    <settings>
        <!-- 使全局的映射器启用或禁用缓存 -->
        <setting name="cacheEnabled"             value="true"   />
        <!-- 允许JDBC 支持自动生成主键 -->
        <setting name="useGeneratedKeys"         value="true"   />
        <!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
        <setting name="defaultExecutorType"      value="SIMPLE" />
		<!-- 指定 MyBatis 所用日志的具体实现 -->
        <setting name="logImpl"                  value="SLF4J"  />
        <!-- 使用驼峰命名法转换字段 -->
		 <setting name="mapUnderscoreToCamelCase" value="true"/>
	</settings>
    <plugins>
        <plugin interceptor="com.ruoyi.common.filter.HandleTimeInterceptor"></plugin>

    </plugins>
</configuration>

总结

然后就可以实现在实体里面自动设置创建时间和修改时间

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java实现学生选课管理系统

    Java实现学生选课管理系统

    这篇文章主要为大家详细介绍了Java实现学生选课管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-07-07
  • SpringBoot 整合mybatis+mybatis-plus的详细步骤

    SpringBoot 整合mybatis+mybatis-plus的详细步骤

    这篇文章主要介绍了SpringBoot 整合mybatis+mybatis-plus的步骤,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • Springboot中@Value的使用详解

    Springboot中@Value的使用详解

    这篇文章主要介绍了Springboot中@Value的使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • 新版SpringBoot无法主动读取bootstrap.yml的原因和解决方法

    新版SpringBoot无法主动读取bootstrap.yml的原因和解决方法

    在使用新版 Springboot 搭建微服务时 发现配置数据源失败,依赖、配置、注解等所示所有均为正确,所以本文给大家介绍了新版SpringBoot无法主动读取bootstrap.yml的原因和解决方案,需要的朋友可以参考下
    2025-01-01
  • JAVA版排序算法之快速排序示例

    JAVA版排序算法之快速排序示例

    这篇文章主要介绍了JAVA版排序算法之快速排序,结合实例形式分析了基于java版的遍历、递归实现快速排序功能的具体步骤与操作技巧,需要的朋友可以参考下
    2017-01-01
  • java随机抽取指定范围不重复的数字

    java随机抽取指定范围不重复的数字

    这篇文章主要介绍了java随机抽取指定范围不重复的数字的相关资料,需要的朋友可以参考下
    2016-06-06
  • 基于JavaMail的常用类详细介绍

    基于JavaMail的常用类详细介绍

    以下是对JavaMail的常用类进行了详细分析的介绍,需要的朋友可以过来参考下
    2013-09-09
  • Java volatile的适用场景实例详解

    Java volatile的适用场景实例详解

    在本文里我们给大家整理了一篇关于Java volatile的适用场景实例内容和知识点,需要的朋友们可以学习下。
    2019-08-08
  • idea如何在service窗口中显示多个服务

    idea如何在service窗口中显示多个服务

    这篇文章主要介绍了idea如何在service窗口中显示多个服务问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • springboot集成springsecurity 使用OAUTH2做权限管理的教程

    springboot集成springsecurity 使用OAUTH2做权限管理的教程

    这篇文章主要介绍了springboot集成springsecurity 使用OAUTH2做权限管理的教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12

最新评论