SpringBoot整合Mybatis Plus實現(xiàn)基本CRUD的示例代碼
對數(shù)據(jù)庫的操作是我們公司中必不可少的功能,Mybatis Plus是在Mybatis的基礎(chǔ)上的增強(qiáng),使得我們對一些基本的CRUD使用起來更方便等,這篇文章主要講講SpringBoot如何去整合Mybatis Plus,并實現(xiàn)基本的CRUD功能。
一、引入相應(yīng)的依賴
<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驅(qū)動的依賴。
二、進(jìn)行配置
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: 0spring.datasource是對數(shù)據(jù)庫的鏈接信息的配置
mybatis-plus:
configuration.log-impl: 配置打印sql日志id-type: id主鍵生成策略,auto為自增logic-delete-field: 邏輯刪除的字段,線上數(shù)據(jù)庫一般要配置邏輯刪除logic-delete-value: 邏輯刪除已刪除的值logic-not-delete-value: 邏輯刪除未刪除的值
三、新建數(shù)據(jù)庫表
這里我新建一張簡單的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讓他在我們新增數(shù)據(jù),更新數(shù)據(jù)時自動插入值,deleted邏輯刪除字段因為我們已經(jīng)在yml中配置了,后續(xù)我們都不需要再處理。
四、配置 Mybatis Plus 自動填充
配置 Mybatis Plus 自動填充來實現(xiàn)對create_time、update_time的值自動插入和更新。
- 新建
handler.mybatisplus.MyMetaObjectHandler類 - 該類實現(xiàn)
MetaObjectHandler接口 - 并重寫
insertFille和updateFill方法
具體代碼實現(xiàn)如下:
handler.mybatisplus.MyMetaObjectHandler:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
setFieldValByName("createTime", new Date(), metaObject);
setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
setFieldValByName("updateTime", new Date(), metaObject);
}
}五、實現(xiàn)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;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@TableName("user")
public class User {
@TableId
private Long id;
private String username;
private Integer age;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Integer deleted;
}@TableName:指定實體類對應(yīng)的表名
@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;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}繼承Mybatis Plus提供的BaseMapper,已經(jīng)實現(xiàn)了一些基本的CRUD接口
- UserService
service.UserService:
public interface UserService {
}service.impl.UserServiceImpl:
import com.jk.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
}先把對應(yīng)的service建好,后面實現(xiàn)controller時再一并實現(xiàn)。
六、使用Restful風(fēng)格實現(xiàn)CRUD功能
- 前期準(zhǔn)備
因為我們需要在查列表時需要使用分頁功能,需要配置一下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;
@Configuration
public class MybatisPlus {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}另外因為我們需要在新增和更新時是不需要全部的實體字段,需要創(chuàng)建對應(yīng)的DTO來接收前端數(shù)據(jù),返回時也不需要全部字段,需要對應(yīng)的Vo對返回前端所需字段
domain.dto.AddUserDto:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AddUserDto {
private String username;
private Integer age;
}domain.dto.UpdateUserDto:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@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;
@Data
@AllArgsConstructor
@NoArgsConstructor
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;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageVo {
private List result;
private Long total;
}PageVo用來處理所有需要分頁數(shù)據(jù)的響應(yīng)
關(guān)于統(tǒng)一響應(yīng)大家可以看 SpringBoot 中統(tǒng)一響應(yīng)格式及統(tǒng)一異常處理,你應(yīng)該這樣做
關(guān)于Bean拷貝大家可以看SpringBoot 項目中 Bean 拷貝及工具類封裝
CRUD對應(yīng)的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對應(yīng)的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都應(yīng)service實現(xiàn)類
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;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public ResponseResult addUser(AddUserDto addUserDto) {
User user = BeanCopyUtils.copyBean(addUserDto, User.class);
userMapper.insert(user);
return ResponseResult.okResult();
}
@Override
public ResponseResult updateUser(UpdateUserDto updateUserDto) {
User user = new User();
BeanUtils.copyProperties(updateUserDto, user);
userMapper.updateById(user);
return ResponseResult.okResult();
}
@Override
public ResponseResult deleteUser(Long id) {
userMapper.deleteById(id);
return ResponseResult.okResult();
}
@Override
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);
}
}到此這篇關(guān)于SpringBoot整合Mybatis Plus實現(xiàn)基本CRUD的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot MybatisPlus實現(xiàn)CRUD內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用MyBatis實現(xiàn)數(shù)據(jù)的CRUD
- SpringBoot整合MyBatis實現(xiàn)CRUD操作項目實踐
- SpringBoot整合MyBatis Plus實現(xiàn)基本CRUD與高級功能
- SpringBoot之整合MyBatis實現(xiàn)CRUD方式
- springboot+mybatis-plus實現(xiàn)內(nèi)置的CRUD使用詳解
- SpringBoot+Mybatis+Vue 實現(xiàn)商品模塊的crud操作
- 詳解springboot+mybatis-plue實現(xiàn)內(nèi)置的CRUD使用詳情
- SpringBoot整合Mybatis實現(xiàn)CRUD
- Spring Boot整合MyBatis-Plus實現(xiàn)CRUD操作的示例代碼
相關(guān)文章
SpringBoot雪花算法主鍵ID傳到前端后精度丟失問題的解決
本文主要介紹了SpringBoot雪花算法主鍵ID傳到前端后精度丟失問題的解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
JavaSE的三大接口:Comparator,Comparable和Cloneable詳解
這篇文章主要介紹了詳解JavaSE中Comparator,Comparable和Cloneable接口的區(qū)別的相關(guān)資料,希望通過本文大家能徹底掌握這部分內(nèi)容,需要的朋友可以參考下2021-10-10
Springboot結(jié)合@validated優(yōu)化代碼驗證
這篇文章主要介紹了Springboot與@validated注解結(jié)合從而實現(xiàn)讓你的代碼驗證更清爽,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
mybatis教程之增刪改查_動力節(jié)點Java學(xué)院整理
這篇文章主要介紹了mybatis教程之增刪改查,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
Java servlet 使用 PrintWriter 時的編碼與亂碼的示例代碼
本篇文章主要介紹了Java servlet 使用 PrintWriter 時的編碼與亂碼的示例代碼,探討了 PrintWriter 的缺省編碼與普通字符流的缺省編碼的差異,具有一定的參考價值,有興趣的可以了解一下2017-11-11
Spring?Boot?優(yōu)雅整合多數(shù)據(jù)源
這篇文章主要介紹了Spring?Boot?優(yōu)雅整合多數(shù)據(jù)源,多數(shù)據(jù)源就是在一個單一應(yīng)用中涉及到了兩個及以上的數(shù)據(jù)庫,更多相關(guān)內(nèi)容需要的小伙伴可以參考下面文章介紹2022-05-05

