MyBatis-Plus通用CRUD操作的實(shí)現(xiàn)
MyBatis-Plus 是在 MyBatis 的基礎(chǔ)上開發(fā)的增強(qiáng)工具,旨在簡化 MyBatis 的使用,提升開發(fā)效率。它為開發(fā)者提供了許多開箱即用的功能,尤其是通用 CRUD 操作,極大地減少了開發(fā)中常見的 CRUD 代碼編寫工作。MyBatis-Plus 通過提供一系列基于注解和模板的通用方法,簡化了數(shù)據(jù)庫操作。
一、MyBatis-Plus 的優(yōu)勢(shì)
- 開箱即用的 CRUD 功能:MyBatis-Plus 提供了通用的 CRUD 方法,開發(fā)者無需手動(dòng)編寫常見的增刪改查 SQL。
- 豐富的分頁功能:內(nèi)置分頁插件,支持?jǐn)?shù)據(jù)庫級(jí)別的分頁查詢,性能優(yōu)越。
- 多種插件支持:提供各種插件支持,如分頁、性能分析、樂觀鎖等,開發(fā)者可以根據(jù)需要進(jìn)行擴(kuò)展。
- 自動(dòng)代碼生成器:可以根據(jù)數(shù)據(jù)庫表結(jié)構(gòu)自動(dòng)生成實(shí)體類、Mapper 接口、Service 和 Controller 層代碼,大大提高開發(fā)效率。
二、集成 MyBatis-Plus
1. 引入依賴
在 pom.xml 文件中引入 MyBatis-Plus 的依賴:
<dependencies>
<!-- MyBatis-Plus Starter for Spring Boot -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!-- MySQL 數(shù)據(jù)庫驅(qū)動(dòng) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
2. 配置數(shù)據(jù)庫連接
在 application.yml 文件中配置數(shù)據(jù)庫連接信息:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
3. 啟動(dòng)類配置
在 Spring Boot 的啟動(dòng)類中,需要添加 @MapperScan 注解,指定 Mapper 接口所在的包。
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper") // 掃描 Mapper 接口
public class MyBatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisPlusDemoApplication.class, args);
}
}
三、實(shí)體類定義
首先,我們需要定義實(shí)體類,它對(duì)應(yīng)數(shù)據(jù)庫中的表結(jié)構(gòu)。MyBatis-Plus 提供了自動(dòng)生成主鍵的注解 @TableId,并且支持多種主鍵生成策略。
package com.example.demo.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("users") // 對(duì)應(yīng)數(shù)據(jù)庫中的表名
public class User {
@TableId(type = IdType.AUTO) // 主鍵自增
private Long id;
private String name;
private String email;
}
@TableName:指定實(shí)體類對(duì)應(yīng)的數(shù)據(jù)庫表名。@TableId:指定主鍵,type = IdType.AUTO表示主鍵自增。
四、Mapper 接口
MyBatis-Plus 提供了通用的 BaseMapper<T> 接口,用戶只需繼承 BaseMapper,就可以自動(dòng)擁有常見的 CRUD 操作,無需再手動(dòng)編寫 SQL。
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.model.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 這里不需要定義方法,BaseMapper 已經(jīng)提供了常用的 CRUD 操作
}
BaseMapper<T> 中內(nèi)置了大量的 CRUD 方法,開發(fā)者無需再重復(fù)編寫增刪改查的 SQL。
五、Service 層
為了進(jìn)一步分離業(yè)務(wù)邏輯,我們可以在 Service 層使用 Mapper 進(jìn)行數(shù)據(jù)庫操作。通過繼承 MyBatis-Plus 提供的 IService<T> 接口,我們可以輕松地獲得常見的 CRUD 功能。
Service 接口:
package com.example.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.model.User;
public interface UserService extends IService<User> {
}
Service 實(shí)現(xiàn)類:
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
// 這里無需編寫額外代碼,通用 CRUD 功能已經(jīng)由 ServiceImpl 提供
}
通過繼承 ServiceImpl,我們可以快速獲得 CRUD 的操作,無需手動(dòng)實(shí)現(xiàn)。
六、Controller 層
在控制器中,可以調(diào)用 Service 層的方法來處理 HTTP 請(qǐng)求。例如,我們可以實(shí)現(xiàn)用戶的增刪改查操作。
package com.example.demo.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// 查詢所有用戶
@GetMapping
public List<User> getAllUsers() {
return userService.list();
}
// 根據(jù) ID 查詢用戶
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getById(id);
}
// 添加新用戶
@PostMapping
public String addUser(@RequestBody User user) {
userService.save(user);
return "用戶添加成功";
}
// 更新用戶
@PutMapping("/{id}")
public String updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
userService.updateById(user);
return "用戶更新成功";
}
// 刪除用戶
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
userService.removeById(id);
return "用戶刪除成功";
}
}
七、通用 CRUD 方法
MyBatis-Plus 內(nèi)置了一系列通用 CRUD 方法,這些方法被 BaseMapper 和 IService 提供。以下是常用的 CRUD 方法:
1. BaseMapper 通用方法
int insert(T entity):插入一條記錄。int deleteById(Serializable id):根據(jù) ID 刪除記錄。int updateById(T entity):根據(jù) ID 更新記錄。T selectById(Serializable id):根據(jù) ID 查詢記錄。List<T> selectList(Wrapper<T> queryWrapper):查詢所有記錄。
2. IService 通用方法
boolean save(T entity):保存或新增記錄。boolean saveOrUpdate(T entity):保存或更新記錄。boolean removeById(Serializable id):根據(jù) ID 刪除記錄。T getById(Serializable id):根據(jù) ID 查詢記錄。List<T> list():查詢所有記錄。boolean updateById(T entity):根據(jù) ID 更新記錄。
八、條件構(gòu)造器
MyBatis-Plus 提供了強(qiáng)大的 條件構(gòu)造器,可以通過 QueryWrapper 和 UpdateWrapper 靈活地構(gòu)建查詢條件,避免手動(dòng)拼接 SQL 語句。
示例:根據(jù)條件查詢
@GetMapping("/search")
public List<User> searchUsers(@RequestParam String name, @RequestParam String email) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name", name).eq("email", email);
return userService.list(queryWrapper);
}
示例:根據(jù)條件更新
@PutMapping("/update")
public String updateUserByCondition(@RequestBody User user) {
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("email", user.getEmail());
userService.update(user, updateWrapper);
return "用戶更新成功";
}
通過條件構(gòu)造器,MyBatis-Plus 提供了鏈?zhǔn)讲僮鱽韺?shí)現(xiàn)復(fù)雜的條件查詢和更新,大大簡化了 SQL 拼接的工作。
九、分頁查詢
MyBatis-Plus 通過分頁插件支持?jǐn)?shù)據(jù)庫級(jí)別的分頁查詢,開發(fā)者無需再手動(dòng)編寫分頁邏輯。
添加分頁插件
首先,在 Spring Boot 配置類中添加分頁插件:
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
使用分頁查詢
@GetMapping("/page")
public IPage<User> getUserPage(@RequestParam int pageNo, @RequestParam int pageSize) {
Page<User> page = new Page<>(pageNo, pageSize);
return userService.page(page);
}
MyBatis-Plus 自動(dòng)處理分頁參數(shù),并返回分頁結(jié)果。
十、總結(jié)
MyBatis-Plus 極大地簡化了 MyBatis 的使用,通過提供通用 CRUD 方法、分頁插件、條件構(gòu)造器等功能,大大減少了樣板代碼的編寫。在實(shí)際開發(fā)中,MyBatis-Plus 提供了高效的開發(fā)體驗(yàn),適合在多種場(chǎng)景下快速實(shí)現(xiàn)數(shù)據(jù)庫操作。
到此這篇關(guān)于MyBatis-Plus通用CRUD操作的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis-Plus通用CRUD操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java對(duì)接ansible自動(dòng)運(yùn)維化平臺(tái)方式
這篇文章主要介紹了Java對(duì)接ansible自動(dòng)運(yùn)維化平臺(tái)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
springboot學(xué)習(xí)筆記之 profile多環(huán)境配置切換的實(shí)現(xiàn)方式
這篇文章主要介紹了springboot profile多環(huán)境配置切換的實(shí)現(xiàn)方式,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-07-07
解決Java中的強(qiáng)制類型轉(zhuǎn)換和二進(jìn)制表示問題
這篇文章主要介紹了解決Java中的強(qiáng)制類型轉(zhuǎn)換和二進(jìn)制表示問題,需要的朋友可以參考下2019-05-05
Spring事件監(jiān)聽機(jī)制ApplicationEvent方式
這篇文章主要介紹了Spring事件監(jiān)聽機(jī)制ApplicationEvent方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09

