实体类
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import java.util.Date; import static com.baomidou.mybatisplus.annotation.FieldFill.*; @Data public class User { @TableId(type = IdType.AUTO)//自增 private Long id; private String name; private int age; private String email; @TableField(fill = INSERT)//插入时自动填充 private Date create_time; @TableField(fill = INSERT_UPDATE)//插入和更新时填充 private Date update_time; }
MyMetaObjectHandler
package com.atguigu.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 MyMetaObjectHandler implements MetaObjectHandler { //mybatisPlus执行添加操作,执行次方法 @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("create_time",new Date(),metaObject); this.setFieldValByName("update_time",new Date(),metaObject); } //mybatisPlus执行更新操作,执行次方法 @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("update_time",new Date(),metaObject); } }
测试代码
@Test public void addUser(){ User user = new User(); user.setName("zhangsan"); user.setAge(35); user.setEmail("[email protected]"); int insert = userMapper.insert(user); System.out.println(insert); }
@Test public void updateUserById(){ User user = new User(); user.setId(6L); user.setName("lucy"); user.setAge(30); int i = userMapper.updateById(user); System.out.println(i); }
标签:mybatisPlus,填充,private,自动,user,Date,import,com,public From: https://www.cnblogs.com/ixtao/p/17320867.html