前言
在日常的插入和修改的时候要频繁的插入时间,浪费时间,可以通过实现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
总结
然后就可以实现在实体里面自动设置创建时间和修改时间
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。
