mybatis-plus实现对创建时间和更新时间的自动填充

我们在项目的开发当中,基本上没张表里都有创建时间和更新时间,而且我们每次在新增或修改数据的时候,也都要把这两个时间更新成当前时间,当然我们也可以在数据库层面设置更新时更新,否则就只能在代码中出现很多重复的如下代码:

xxx.setCreateTime(new Date());

xxx.setUpdateTime(new Date());

而mybatis-plus给我们提供一种方式,可以自动帮我们更新这两个字段,在写业务逻辑的时候就不用去关注类似上面这种重复的代码,一劳永逸,但是要注意的是,必须字段名称一致,就是每张表的创建时间都叫create_time ,更新时间叫update_time:好了,话不多说。给出代码:

1. 添加一个配置类:

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class MybatisPlusConf {
    /**
     * 自动填充功能
     */
    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new MetaHandler());
        return globalConfig;
    }

}

 

2. 添加一个Handler

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasSetter = metaObject.hasSetter("createTime");
        if (hasSetter) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }

    /**
     * 更新数据执行
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object val = getFieldValByName("updateTime", metaObject);
        if (val == null) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }

}

这里要注意:如果你的实体中日期是Date() 类型,上面 就用new Date(), 如果是LocalDateTime类型,就把new Date() 替换为 LocalDateTIme.now();

 

当然我们也可以使用上篇文章中提到的Mybatis拦截器,拦截instert 和 update方法: 配置如下; 

 

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.time.LocalDateTime;

import org.apache.ibatis.binding.MapperMethod.ParamMap;
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.Signature;
import org.springframework.stereotype.Component;


@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class CreateTimeSetInterceptor implements Interceptor {

	private static final String CREATE_TIME_SETTER = "setCreateTime";
	private static final String UPDATE_TIME_SETTER = "setUpdateTime";

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
		Object parameter = invocation.getArgs()[1];

		if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
			setTimeIfNeccesary(parameter, CREATE_TIME_SETTER);
			setTimeIfNeccesary(parameter, UPDATE_TIME_SETTER);
		} else if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
			setTimeIfNeccesary(parameter, UPDATE_TIME_SETTER);
		}
		return invocation.getMethod().invoke(invocation.getTarget(), invocation.getArgs());
	}

	private void setTimeIfNeccesary(Object param, String methodName) {
		Class<?> cls = param.getClass();

		if (cls == ParamMap.class) {
			@SuppressWarnings("unchecked")
			ParamMap<Object> map = (ParamMap<Object>) param;
			map.entrySet().forEach(entry -> {
				if (!entry.getKey().equals("et")) {
					setIfSetterExist(entry.getValue(), methodName);
				}
			});
		} else {
			setIfSetterExist(param, methodName);
		}
	}

	private void setIfSetterExist(Object param, String methodName) {
		Class<?> cls = param.getClass();
		try {
			Method m = null;
			try {
				m = cls.getDeclaredMethod(methodName, new Class[] { LocalDateTime.class });
				if (m != null) {
					m.setAccessible(true);
					m.invoke(param, LocalDateTime.now());
				}
			} catch (NoSuchMethodException e1) {
				m = cls.getDeclaredMethod(methodName, new Class[] { Timestamp.class });
				if (m != null) {
					m.setAccessible(true);
					m.invoke(param, new Timestamp(System.currentTimeMillis()));
				}
			}
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}

 

好了关于今天的内容就介绍到这里了。

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值