1.导入MybatisPlus依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
我的版本是3.5.3.1
2.实体类中加自动填充注解
这里我的实体类如下,我选择自动填充创建时间和更新时间
@TableName("goods_category")
@Data
@ApiModel(value = "GoodsCategory对象", description = "")
public class GoodsCategory implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "商品类型id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "商品类型名称")
private String categoryName;
@ApiModelProperty(value = "类型级别 1 一级 2二级 默认一级")
private Integer categoryType;
@ApiModelProperty(value = "上一级id")
private Integer parentId;
@ApiModelProperty(value = "创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT) // TableField注解中
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") // fill属性设置自动填充
private LocalDateTime createTime; //值是自动填充触发时机
@ApiModelProperty(value = "更新时间")
@TableField(value = "update_time", fill = FieldFill.UPDATE) //同上
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
}
3.创建Handler
!!这里需要确保,这个类能被扫描到并成功注册成bean
需要实现MetaObjectHandler接口,在重写方法中,根据字段名称去赋值
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时
@Override
public void insertFill(MetaObject metaObject) {
//metaObject为当前对象,根据"createTime"寻找对应字段,并赋值为"LocalDateTime.now()"
this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
}
//更新时
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
}
}
4.使用
值得注意的是,如果想触发字段自动填充,在对数据库操作时,必须要使用到对应实体才行
以下是service中的某个方法,作为示例
@Override
public void add(Integer parentId, String categoryName) {
/**
* 查询父类型
*/
GoodsCategory parent = goodsCategoryMapper.selectById(parentId);
if(parent.getCategoryType()==3){
throw new DataException("上级分类不允许是三级分类");
}
GoodsCategory goodsCategory = new GoodsCategory();
if(parentId==null||parentId==0){
goodsCategory.setParentId(0);
}else {
if(goodsCategoryMapper.selectOne(
new QueryWrapper<GoodsCategory>().eq("parent_id",parentId))
==null) throw new DataException("父类别不存在");
goodsCategory.setParentId(parentId);
}
goodsCategory.setCategoryName(categoryName);
goodsCategory.setCategoryType(parent.getCategoryType()+1);
/*--------------注意!这里一定操作的是对应实体,否则无法自动填充-----------------*/
goodsCategoryMapper.insert(goodsCategory);
}