我们在项目的开发当中,基本上没张表里都有创建时间和更新时间,而且我们每次在新增或修改数据的时候,也都要把这两个时间更新成当前时间,当然我们也可以在数据库层面设置更新时更新,否则就只能在代码中出现很多重复的如下代码:
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();
}
}
}
好了关于今天的内容就介绍到这里了。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有