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

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

在日常的插入和修改的时候要频繁的插入时间,浪费时间,可以通过实现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>

总结

然后就可以实现在实体里面自动设置创建时间和修改时间
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值