mybatis插件统一处理createTime,createBy,updateBy

前两天了解了一下mybatis插件这个东西,为了加深一下印象,突然想给当前代码做一个简化操作,通过插件的形式统一处理createTime,createBy,updateBy。
首先定义一个BaseEntity,里面放入这些参数,需要处理的实体类只需要继承即可

import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

@Data
public class BaseEntity implements Serializable{

	private static final long serialVersionUID = 1L;

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date updateTime;
	
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
	
	private String createBy;
	
	private String updateBy;
	
}

处理逻辑代码

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

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import com.spring.framework.entity.BaseEntity;
import com.spring.framework.utils.UserUtil;



/**
 *  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());
				baseEntity.setUpdateBy(UserUtil.getUsername());
			 }
		 }else if(sqlCommandType==SqlCommandType.INSERT) {
			 if(args[1] instanceof BaseEntity) {
					BaseEntity baseEntity = (BaseEntity) args[1];
					baseEntity.setCreateTime(new Date());
					baseEntity.setCreateBy(UserUtil.getUsername());
			}
		 }
	     
		return invocation.proceed();
	}

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

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

简单测试了一下,是没有问题的,具体还存在哪些bug暂时还不知道,先这样吧
参考地址:https://blog.csdn.net/weixin_43850799/article/details/106745494

2020-06-21,代码出bug了,项目中集成了mybatis-plus后,更新数据的时候发现updateBy和updateTime不会被赋值了,debug看了一下,发现由于使用的时候mp自带的修改方法,他把参数结构修改了,所以代码也要随之改变一下,增加个判断。(手写xml和使用tk的时候没有发现这个问题的出现)

import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 公共字段统一处理
 * @author ljw
 * 2021年6月19日14:56:21
 *
 */
@Intercepts({@Signature(type = Executor.class,method = "update",args = {MappedStatement.class,Object.class})})
public class HandleCommonInterceptor implements Interceptor {

	
	@SuppressWarnings("unchecked")
	@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) {
			System.err.println(args[1]);
			 if(args[1] instanceof BaseEntity) {
				BaseEntity baseEntity = (BaseEntity) args[1];
				baseEntity.setUpdateTime(new Date());
				if(SecurityUtils.getAuthentication()!=null) {//主要处理在执行插入日志的时候会获取不到用户信息,问题暂时不清楚为啥
					baseEntity.setUpdateBy(SecurityUtils.getUsername());
				}
				//调用mp的更新方法时,参数会变成如下形式:{param1=Receive(id=16, dh=1244, qzh=null, postId=1)} 正常的应该是Receive(id=16, dh=1244, qzh=null, postId=1)
			 }else if(args[1] instanceof Map){
				 Map<String,Object> map = (Map<String, Object>) args[1];
				 Object object = getFirstOrNull(map);
				 if(object instanceof BaseEntity) {
					BaseEntity baseEntity = (BaseEntity) object;
					baseEntity.setUpdateTime(new Date());
					if(SecurityUtils.getAuthentication()!=null) {//主要处理在执行插入日志的时候会获取不到用户信息,问题暂时不清楚为啥
						baseEntity.setUpdateBy(SecurityUtils.getUsername());
					}
				 }
				 
			 }
		 }else if(sqlCommandType==SqlCommandType.INSERT) {
			 if(args[1] instanceof BaseEntity) {
				BaseEntity baseEntity = (BaseEntity) args[1];
				baseEntity.setCreateTime(new Date());
				if(SecurityUtils.getAuthentication()!=null) {
					baseEntity.setCreateBy(SecurityUtils.getUsername());
				}
			}
		 }
		return invocation.proceed();
	}
	
	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}

	/**
	 * 获取第一个key的值
	 * @param map
	 * @return
	 */
	private static Object getFirstOrNull(Map<String, Object> map) {
        Object obj = null;
        for (Entry<String, Object> entry : map.entrySet()) {
            obj = entry.getValue();
            if (obj != null) {
                break;
            }
        }
        return  obj;
    }
}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
MyBatis Plus 中,可以为不同实体类设置不同的自动填充规则。取消指定实体类的createBy自动填充需要在实体类中使用注解 `@TableField(fill = FieldFill.DEFAULT)` 来标识该字段不进行自动填充。具体来说,可以按照以下步骤进行操作: 1. 在实体类中取消createBy的自动填充: ```java @TableField(fill = FieldFill.DEFAULT) private String createBy; ``` 2. 在MyBatis Plus配置中为该实体类设置自动填充策略: ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //创建拦截器链 List<Interceptor> interceptorList = new ArrayList<>(); //自动填充拦截器 Interceptor fillInterceptor = new MybatisPlusAutoFillInterceptor(); //为指定实体类设置自动填充策略 List<MetaObjectHandler> metaObjectHandlers = new ArrayList<>(); //指定实体类的自动填充策略 metaObjectHandlers.add(new MybatisPlusMetaObjectHandler()); fillInterceptor.setProperties(Collections.singletonMap("metaObjectHandlers", metaObjectHandlers)); interceptorList.add(fillInterceptor); interceptor.setInterceptors(interceptorList); return interceptor; } } ``` 其中,`MybatisPlusMetaObjectHandler`是自定义的MetaObjectHandler类,用于设置该实体类的自动填充规则。在该类中,使用注解 `@Override` 标识重写的方法,然后在方法中设置不需要自动填充的字段。例如: ```java public class MybatisPlusMetaObjectHandler extends BaseMetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { //设置createBy不进行自动填充 this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class); } @Override public void updateFill(MetaObject metaObject) { //设置updateBy不进行自动填充 this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); } } ``` 这样,就可以为指定实体类设置自动填充规则,并取消createBy的自动填充。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值