目录
- 一、引入相应的依赖
- 二、进行配置
- 三、新建数据库表
- 四、配置 Mybatis Plus 自动填充
- 五、实现User实体类、UserMapper、UserService
- 六、使用Restful风格实现CRUD功能
对数据库的操作是我们公司中必不可少的功能,Mybatis Plus是在Mybatis的基础上的增强,使得我们对一些基本的CRUD使用起来更方便等,这篇文章主要讲讲SpringBoot如何去整合Mybatis Plus,并实现基本的CRUD功能。
一、引入相应的依赖
<dependency> | |
<groupId>com.baomidou</groupId> | |
<artifactId>mybatis-plus-boot-starter</artifactId> | |
<version>3.5.3.1</version> | |
</dependency> | |
<dependency> | |
<groupId>mysql</groupId> | |
<artifactId>mysql-connector-java</artifactId> | |
<version>8.0.32</version> | |
</dependency> |
引入mybatis-plus
的依赖和mysql
驱动的依赖。
二、进行配置
spring: | |
datasource: | |
url: jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8&serverTimeZone=UTC | |
username: root | |
password: 123456 | |
driver-class-name: com.mysql.cj.jdbc.Driver | |
mybatis-plus: | |
configuration: | |
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl | |
global-config: | |
db-config: | |
id-type: auto | |
logic-delete-field: deleted | |
logic-delete-value: 1 | |
logic-not-delete-value: 0 |
spring.datasource
是对数据库的链接信息的配置
mybatis-plus
:
configuration.log-impl
: 配置打印sql日志id-type
: id主键生成策略,auto为自增logic-delete-field
: 逻辑删除的字段,线上数据库一般要配置逻辑删除logic-delete-value
: 逻辑删除已删除的值logic-not-delete-value
: 逻辑删除未删除的值
三、新建数据库表
这里我新建一张简单的user表
sql如下:
DROP TABLE IF EXISTS `user`; | |
CREATE TABLE `user` ( | |
`id` bigint(20) NOT NULL AUTO_INCREMENT, | |
`username` varchar(255) NOT NULL, | |
`age` int(3) NOT NULL, | |
`create_time` datetime DEFAULT NULL, | |
`update_time` datetime DEFAULT NULL, | |
`deleted` int(1) DEFAULT '0', | |
PRIMARY KEY (`id`) | |
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; |
可以看到表中有一些建表必须的字段create_time
、update_time
、deleted
,前两个字段我们需要在项目中配置一下Mybatis Plus
让他在我们新增数据,更新数据时自动插入值,deleted
逻辑删除字段因为我们已经在yml中配置了,后续我们都不需要再处理。
四、配置 Mybatis Plus 自动填充
配置 Mybatis Plus
自动填充来实现对create_time
、update_time
的值自动插入和更新。
- 新建
handler.mybatisplus.MyMetaObjectHandler
类 - 该类实现
MetaObjectHandler
接口 - 并重写
insertFille
和updateFill
方法
具体代码实现如下:
handler.mybatisplus.MyMetaObjectHandler:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; | |
import org.apache.ibatis.reflection.MetaObject; | |
import java.util.Date; | |
public class MyMetaObjectHandler implements MetaObjectHandler { | |
public void insertFill(MetaObject metaObject) { | |
setFieldValByName("createTime", new Date(), metaObject); | |
setFieldValByName("updateTime", new Date(), metaObject); | |
} | |
public void updateFill(MetaObject metaObject) { | |
setFieldValByName("updateTime", new Date(), metaObject); | |
} | |
} |
五、实现User实体类、UserMapper、UserService
- User实体类
domain.entity.User:
import com.baomidou.mybatisplus.annotation.FieldFill; | |
import com.baomidou.mybatisplus.annotation.TableField; | |
import com.baomidou.mybatisplus.annotation.TableId; | |
import com.baomidou.mybatisplus.annotation.TableName; | |
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
import lombok.experimental.Accessors; | |
import java.util.Date; | |
public class User { | |
private Long id; | |
private String username; | |
private Integer age; | |
private Date createTime; | |
private Date updateTime; | |
private Integer deleted; | |
} |
@TableName
:指定实体类对应的表名
@TableId
:指定为主键,我们配置的是auto
,即主键自增策略
@TableField
:指定该值使用我们的自动填充策略,INSERT
为插入时填充,INSERT_UPDATE
为插入和更新时填充
- UserMapper
mapper.UserMapper
:
import com.baomidou.mybatisplus.core.mapper.BaseMapper; | |
import com.jk.domain.entity.User; | |
import org.apache.ibatis.annotations.Mapper; | |
public interface UserMapper extends BaseMapper<User> { | |
} |
继承Mybatis Plus
提供的BaseMapper
,已经实现了一些基本的CRUD接口
- UserService
service.UserService
:
public interface UserService { | |
} |
service.impl.UserServiceImpl
:
import com.jk.service.UserService; | |
import org.springframework.stereotype.Service; | |
public class UserServiceImpl implements UserService { | |
} |
先把对应的service
建好,后面实现controller
时再一并实现。
六、使用Restful风格实现CRUD功能
- 前期准备
因为我们需要在查列表时需要使用分页功能,需要配置一下Mybatis Plus
分页插件
config.MybatisPlus
:
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; | |
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
public class MybatisPlus { | |
public MybatisPlusInterceptor mybatisPlusInterceptor() { | |
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); | |
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); | |
return mybatisPlusInterceptor; | |
} | |
} |
另外因为我们需要在新增和更新时是不需要全部的实体字段,需要创建对应的DTO来接收前端数据,返回时也不需要全部字段,需要对应的Vo对返回前端所需字段
domain.dto.AddUserDto
:
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
public class AddUserDto { | |
private String username; | |
private Integer age; | |
} |
domain.dto.UpdateUserDto
:
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
public class UpdateUserDto { | |
private Long id; | |
private String username; | |
private Integer age; | |
} |
domain.vo.UserVo
:
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
import java.util.Date; | |
public class UserVo { | |
private Long id; | |
private String username; | |
private Integer age; | |
private Date createTime; | |
} |
domain.vo.PageVo
:
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
import java.util.List; | |
public class PageVo { | |
private List result; | |
private Long total; | |
} |
PageVo
用来处理所有需要分页数据的响应
关于统一响应大家可以看 SpringBoot 中统一响应格式及统一异常处理,你应该这样做
关于Bean拷贝大家可以看SpringBoot 项目中 Bean 拷贝及工具类封装
CRUD
对应的controller
controller.UserController
:
import com.jk.domain.dto.AddUserDto; | |
import com.jk.domain.dto.UpdateUserDto; | |
import com.jk.service.UserService; | |
import com.jk.domain.vo.ResponseResult; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.web.bind.annotation.*; | |
@RestController | |
@RequestMapping("/user") | |
public class UserController { | |
@Autowired | |
private UserService userService; | |
@PostMapping | |
public ResponseResult addUser(@RequestBody AddUserDto addUserDto) { | |
return userService.addUser(addUserDto); | |
} | |
@PutMapping | |
public ResponseResult updateUser(@RequestBody UpdateUserDto updateUserDto) { | |
return userService.updateUser(updateUserDto); | |
} | |
@DeleteMapping("/{id}") | |
public ResponseResult deleteUser(@PathVariable("id") Long id) { | |
return userService.deleteUser(id); | |
} | |
@GetMapping | |
public ResponseResult getUser(@RequestParam(defaultValue = "1") Integer pageNum, | |
@RequestParam(defaultValue = "10") Integer pageSize) { | |
return userService.getUser(pageNum, pageSize); | |
} | |
} |
CRUD
对应的service
service.UserService
:
import com.jk.domain.dto.AddUserDto; | |
import com.jk.domain.dto.UpdateUserDto; | |
import com.jk.domain.vo.ResponseResult; | |
public interface UserService { | |
ResponseResult addUser(AddUserDto addUserDto); | |
ResponseResult updateUser(UpdateUserDto updateUserDto); | |
ResponseResult deleteUser(Long id); | |
ResponseResult getUser(Integer pageNum, Integer pageSize); | |
} |
CRUD
都应service实现类
service.impl.UserServiceImpl
:
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; | |
import com.jk.domain.dto.AddUserDto; | |
import com.jk.domain.dto.UpdateUserDto; | |
import com.jk.domain.entity.User; | |
import com.jk.domain.vo.UserVo; | |
import com.jk.mapper.UserMapper; | |
import com.jk.service.UserService; | |
import com.jk.domain.vo.PageVo; | |
import com.jk.domain.vo.ResponseResult; | |
import com.jk.utils.BeanCopyUtils; | |
import org.springframework.beans.BeanUtils; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Service; | |
import java.util.List; | |
public class UserServiceImpl implements UserService { | |
private UserMapper userMapper; | |
public ResponseResult addUser(AddUserDto addUserDto) { | |
User user = BeanCopyUtils.copyBean(addUserDto, User.class); | |
userMapper.insert(user); | |
return ResponseResult.okResult(); | |
} | |
public ResponseResult updateUser(UpdateUserDto updateUserDto) { | |
User user = new User(); | |
BeanUtils.copyProperties(updateUserDto, user); | |
userMapper.updateById(user); | |
return ResponseResult.okResult(); | |
} | |
public ResponseResult deleteUser(Long id) { | |
userMapper.deleteById(id); | |
return ResponseResult.okResult(); | |
} | |
public ResponseResult getUser(Integer pageNum, Integer pageSize) { | |
Page<User> userPage = new Page<>(pageNum, pageSize); | |
userMapper.selectPage(userPage, null); | |
List<UserVo> userVos = BeanCopyUtils.copyBeanList(userPage.getRecords(), UserVo.class); | |
PageVo pageVo = new PageVo(userVos, userPage.getTotal()); | |
return ResponseResult.okResult(pageVo); | |
} | |
} |