前提:
在数据苦中添加 create_time 和 update_time字段
1、实体类
package com.wt.pojo; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; }
2、创建handler
package com.wt.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.util.Date; @Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { log.info("==== insert ============================="); this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("updateTime", new Date(), metaObject); } @Override public void updateFill(MetaObject metaObject) { log.info("==== update ============================="); this.setFieldValByName("updateTime", new Date(), metaObject); } }
3、测试
@Test public void insertSql(){ User user = new User(); user.setName("wt"); user.setAge(30); user.setEmail("13057122577@qq.com"); userMapper.insert(user); } @Test public void updateUser(){ User user = new User(); user.setId(1285437905490583554L); user.setName("tom"); userMapper.updateById(user); }