开发环境
- JDK 1.8
- SpringBoot2.2.1
- Maven 3.2
- Mysql5.7.36
- 开发工具
- IntelliJ IDEA
- smartGit
项目场景
在项目中经常会遇到需要自动填充数据的情况,比如新增一个DO类,里面可能会有id
、create_time
、modify_time
、create_user
等等这些通用的字段,每一个接口我们都要去设置值,不仅代码冗余,而且不能统一管理
解决方案:
针对这种情况,可以使用Mybatis Plus来对通用数据的自动填充,在我之前的博客中,已经对怎么在Springboot2.0中集成Mybatis Plus做了比较详细的描述,下面给一个例子,看看自动填充的实现
创建数据库表
代码语言:javascript复制CREATE TABLE `user` (
`id` bigint NOT NULL,
`name` varchar(255) DEFAULT NULL,
`age` int DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`modify_time` datetime DEFAULT NULL,
`is_deleted` int DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
通用的BO类,里面有id
、createTime
、modifyTime
、is_deleted
等等,对于主键ID有如下的主键策略
- ASSIGN_ID(雪花算法)
- ASSIGN_UUID(排除中划线的UUID)
- AUTO(数据库ID自增)
- INPUT(插入前自行设置主键值)
- NONE(无状态)
package com.example.mybatisplus.model;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class BaseDO {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime modifyTime;
@TableLogic(value = "0", delval = "1")
@TableField(value = "is_deleted", select = false)
private Boolean deleted;
}
用户信息的DO类继承BaseDO
代码语言:javascript复制package com.example.mybatisplus.model;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
@TableName("user")
@EqualsAndHashCode(callSuper=true)
@Data
public class UserDO extends BaseDO implements Serializable {
private static final long serialVersionUID = -2767372720145830784L;
private String name;
private Integer age;
private String email;
}
在application.yml配置mybatis plus
代码语言:javascript复制mybatis-plus:
type-aliases-package: com.example.mybatisplus.*.*.model
mapper-locations: classpath*:mapper/*/*.xml
global-config:
db-config:
logic-not-delete-value: 1
logic-delete-value: 0
configuration:
map-underscore-to-camel-case: true
default-statement-timeout: 60
cache-enabled: true
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
对于创建日期等字段的自动填充,我们写一个handler类,实现MetaObjectHandler
接口,注意加上@Component
,才能被Spring容器管理
package com.example.mybatisplus.common.handlers;
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.time.LocalDateTime;
@Component
@Slf4j
public class FillMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("insertFill");
this.setFieldValByName("createTime" , LocalDateTime.now(), metaObject);
this.setFieldValByName("modifyTime" , LocalDateTime.now() , metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("updateFill");
this.setFieldValByName("modifyTime" , LocalDateTime.now(), metaObject);
}
}
Mapper接口
代码语言:javascript复制package com.example.mybatisplus.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplus.common.cache.MyBatisRedisCache;
import com.example.mybatisplus.model.UserDO;
import org.apache.ibatis.annotations.CacheNamespace;
@DS(value = "testDB")
@CacheNamespace(implementation = MyBatisRedisCache.class ,eviction = MyBatisRedisCache.class)
public interface UserMapper extends BaseMapper<UserDO>{
}
业务接口api
代码语言:javascript复制package com.example.mybatisplus.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.mybatisplus.model.UserDO;
public interface IUserService extends IService<UserDO> {
}
业务实现类
代码语言:javascript复制package com.example.mybatisplus.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatisplus.mapper.UserMapper;
import com.example.mybatisplus.model.UserDO;
import com.example.mybatisplus.service.IUserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper , UserDO> implements IUserService {
}
新增用户的api接口
代码语言:javascript复制 @PostMapping(value = "/user")
public ResultBean<UserDO> save(@RequestBody UserDto userDto) {
UserDO user = BeanUtil.copyProperties(userDto , UserDO.class);
boolean flag = userService.save(user);
if (flag) return ResultBean.ok(user);
return ResultBean.badRequest("新增失败");
}