引言
插入数据时自动设置当前时间,更新数据时自动修改日期为修改时的日期。
使用MybatisPlus的扩展接口MetaObjectHandler
步骤
-
实现接口
-
实体类加注解
实现接口
package com.example.vueelementson.common;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;/*** @BelongsProject: blog-springboot* @BelongsPackage: com.example.vueelementson.common* @Author: Zww* @CreateTime: 2024-07-07 16:38* @Description: TODO* @Version: 1.0*/
@Component
public class ExtraDataHandle implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {// 第一个值填入你要设置的字段名,第二个值为每次自动填充的值metaObject.setValue("publishTime", new Date());metaObject.setValue("updateTime", new Date());}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", new Date(), metaObject);}
}
添加注解
不过这里的Date给到前端是时间戳格式的
,我们在前端增加一个 时间戳转换的js,引入并在method里调用
JS时间戳转时间代码
// 时间戳:1637244864707
/* 时间戳转换为时间 */
export default {timestampToTime(value, type = 0) {var time = new Date(value);// 2023-07-07 17:07:44var year = time.getFullYear();// 2023年var month = time.getMonth() + 1; // 0-11 +1表示1-12月var date = time.getDate();// 1-31号var hour = time.getHours();// 0-23时var minute = time.getMinutes();// 0-59分var second = time.getSeconds();// 0-59秒month = month < 10 ? "0" + month : month;// 如果小于10的月份,前面补0date = date < 10 ? "0" + date : date;hour = hour < 10 ? "0" + hour : hour;minute = minute < 10 ? "0" + minute : minute;second = second < 10 ? "0" + second : second;var arr = [year + "-" + month + "-" + date,year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second,year + "年" + month + "月" + date,year + "年" + month + "月" + date + "日" + " " + hour + ":" + minute + ":" + second,hour + ":" + minute + ":" + second]return arr[type];}
}
使用该js
结果