ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

公共字段自动填充

公共字段自动填充 MyBatis‑Plus 公共字段自动填充场景创建时间、更新时间、创建人、更新人不用每次 setMP 自动赋值。核心TableField(fill FieldFill.xxx) 实现MetaObjectHandlermavendependency groupIdcom.baomidou/groupId artifactIdmybatis-plus-boot-starter/artifactId version3.5.3.1/version /dependencyTableField(fill FieldFill. ...)有三种1、TableField(fill FieldFill.INSERT只在新增时自动填充2TableField(fill FieldFill.UPDATE)只在修改时自动填充3TableField(fill FieldFill.INSERT_UPDATE) 在增加或修改时都自动填充1.先在pojo文件夹中 找到和数据库映射的文件把在修改操作或新增操作要改变得参数名前加上TableField如TableField(fill FieldFill.INSERT_UPDATE) JsonFormat(pattern yyyy-MM-dd HH:mm:ss) private LocalDateTime createTime; TableField(fill FieldFill.UPDATE) JsonFormat(pattern yyyy-MM-dd HH:mm:ss) private LocalDateTime updateTime; TableField(fill FieldFill.INSERT_UPDATE) private Long createUser; TableField(fill FieldFill.UPDATE) private Long updateUser;2.配置自动填充的配置在service层添加MyMetaObjectHandler文件要添加Component交给spring托管要继承MetaObjrxtHandler编写 insertFill和updateFill方法如Component public class MyMetaObjectHandler implements MetaObjectHandler { Override public void insertFill(MetaObject metaObject) { Long userId BaseContext.getCurrentId(); strictInsertFill(metaObject,createTime, LocalDateTime.class,LocalDateTime.now()); strictInsertFill(metaObject, updateTime, LocalDateTime.class, LocalDateTime.now()); strictInsertFill(metaObject,createUser, Long.class,userId); strictInsertFill(metaObject,updateUser, Long.class,userId); } Override public void updateFill(MetaObject metaObject) { Long userId BaseContext.getCurrentId(); strictUpdateFill(metaObject,updateTime, LocalDateTime.class, LocalDateTime.now()); strictUpdateFill(metaObject,updateUser, Long.class,userId); } }我的例子是手写ThreadLocal的 BaseContext.getCurrentId()用SecurityContextHolder的话可以Authentication authentication SecurityContextHolder.getContext().getAuthentication();Long userId ((LoginUser)authentication.getPrincipal()).getId();3使用时先在service接口中添加 extends IService类名如public interface EmployeeServiceextends IServiceEmployee{ Employee login(EmployeeLoginDTO employeeLoginDTO); PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO); void startOrStep(Integer status, Long id); Employee getById(Long id); void update(EmployeeDTO employeeDTO); void save(EmployeeDTO employeeDTO); }再到serviceimpl中继承ServiceImpl类名Mapper, 类名如public class EmployeeServiceImpl extends ServiceImplEmployeeMapper, Employee implements EmployeeService {}之后再把用了mapper的insert的地方改成save//如果和自定义的业务方法重名又要用service中的方法时save前加上supermapper.updateById直接用updateById
返回列表