欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot 中整合 MyBatis-Plus詳細步驟(最新推薦)

 更新時間:2025年01月03日 11:24:25   作者:顏淡慕瀟  
本文詳細介紹了如何在SpringBoot項目中整合MyBatis-Plus,包括整合步驟、基本CRUD操作、分頁查詢、批量操作、自定義SQL操作等,通過這些步驟,開發(fā)者可以快速實現(xiàn)數(shù)據(jù)庫操作,提高開發(fā)效率,感興趣的朋友一起看看吧

在 Spring Boot 中整合 MyBatis-Plus 可以按照以下步驟進行:

一、整合步驟

1. 創(chuàng)建 Spring Boot 項目

首先,使用 Spring Initializr(https://start.spring.io/)創(chuàng)建一個新的 Spring Boot 項目。在創(chuàng)建過程中,選擇以下依賴:

  • Spring Web
  • MySQL Driver
  • MyBatis-Plus

2. 配置項目依賴

如果手動創(chuàng)建 pom.xml 文件,確保添加以下依賴:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- MyBatis-Plus Starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>最新版本</version>
    </dependency>
    <!-- MySQL Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- Spring Boot Starter Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

請將 最新版本 替換為 MyBatis-Plus 的實際最新版本號。

3. 配置數(shù)據(jù)源

application.yml 文件中配置數(shù)據(jù)庫連接信息:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/yourdatabase
    username: yourusername
    password: yourpassword
    driver-class-name: com.mysql.cj.jdbc.Driver

yourdatabase、yourusernameyourpassword 替換為實際的數(shù)據(jù)庫名稱、用戶名和密碼。

4. 創(chuàng)建實體類

創(chuàng)建一個 Java 實體類,用于映射數(shù)據(jù)庫表。例如,創(chuàng)建一個 User 實體類:

package com.example.demo.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("user")
public class User {
    private Long id;
    private String username;
    private String password;
}

@Data 是 Lombok 注解,用于自動生成 getter、setter、equalshashCodetoString 方法。@TableName 注解指定實體類對應(yīng)的數(shù)據(jù)庫表名。

5. 創(chuàng)建 Mapper 接口

創(chuàng)建一個 Mapper 接口,繼承 BaseMapper 接口,BaseMapper 是 MyBatis-Plus 提供的基礎(chǔ)接口,包含了常用的 CRUD 方法。例如,創(chuàng)建一個 UserMapper 接口:

package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 可以在這里定義自定義的 SQL 方法
}

@Mapper 注解用于將該接口標記為 MyBatis 的 Mapper 接口。

6. 創(chuàng)建 Service 層

創(chuàng)建一個 Service 接口和其實現(xiàn)類。例如,創(chuàng)建一個 UserService 接口和 UserServiceImpl 實現(xiàn)類:

package com.example.demo.service;
import com.example.demo.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
public interface UserService extends IService<User> {
    // 可以在這里定義自定義的業(yè)務(wù)方法
}
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 如果需要,可以重寫或?qū)崿F(xiàn)自定義方法
}

ServiceImpl 是 MyBatis-Plus 提供的基礎(chǔ) Service 實現(xiàn)類,它提供了基本的 CRUD 方法實現(xiàn)。

7. 創(chuàng)建 Controller 層

創(chuàng)建一個 Controller 層,用于處理客戶端請求。例如,創(chuàng)建一個 UserController

package com.example.demo.controller;
import com.example.demo.entity.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> findAll() {
        return userService.list();
    }
    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        return userService.getById(id);
    }
    @PostMapping
    public boolean save(@RequestBody User user) {
        return userService.save(user);
    }
    @PutMapping
    public boolean update(@RequestBody User user) {
        return userService.updateById(user);
    }
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return userService.removeById(id);
    }
}

8. 配置 MyBatis-Plus 掃描

在 Spring Boot 主應(yīng)用類上添加 @MapperScan 注解,掃描 Mapper 接口所在的包:

package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

9. 測試

可以使用 Spring Boot 的測試框架來測試各個接口:

package com.example.demo;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    private UserService userService;
    @Test
    public void testFindAll() {
        assertTrue(userService.list().size() >= 0);
    }
    @Test
    public void testFindById() {
        User user = new User();
        user.setUsername("testuser");
        user.setPassword("testpassword");
        userService.save(user);
        assertNotNull(userService.getById(user.getId()));
    }
    @Test
    public void testSave() {
        User user = new User();
        user.setUsername("newuser");
        user.setPassword("newpassword");
        assertTrue(userService.save(user));
    }
    @Test
    public void testUpdate() {
        User user = new User();
        user.setUsername("updateuser");
        user.setPassword("updatepassword");
        userService.save(user);
        user.setPassword("newupdatepassword");
        assertTrue(userService.updateById(user));
    }
    @Test
    public void testDelete() {
        User user = new User();
        user.setUsername("deleteuser");
        user.setPassword("deletepassword");
        userService.save(user);
        assertTrue(userService.removeById(user.getId()));
    }
}

通過以上步驟,你就可以在 Spring Boot 項目中成功整合 MyBatis-Plus,并實現(xiàn)基本的 CRUD 操作。在實際項目中,你可以根據(jù)需求進一步擴展和優(yōu)化代碼。

二、 基本 CRUD 操作

在前面整合的基礎(chǔ)上,我們已經(jīng)有了基本的 CRUD 方法。

新增操作

UserService 中調(diào)用 save 方法:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 新增操作
    @Override
    public boolean saveUser(User user) {
        return this.save(user);
    }
}

查詢操作

根據(jù) ID 查詢:調(diào)用 getById 方法。

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 根據(jù) ID 查詢
    @Override
    public User getUserById(Long id) {
        return this.getById(id);
    }
}

查詢所有:調(diào)用 list 方法。

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 查詢所有
    @Override
    public List<User> getAllUsers() {
        return this.list();
    }
}

更新操作

調(diào)用 updateById 方法:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 更新操作
    @Override
    public boolean updateUser(User user) {
        return this.updateById(user);
    }
}

刪除操作

根據(jù) ID 刪除:調(diào)用 removeById 方法。

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 根據(jù) ID 刪除
    @Override
    public boolean deleteUserById(Long id) {
        return this.removeById(id);
    }
}

條件查詢

使用 QueryWrapper 構(gòu)建查詢條件。

簡單條件查詢

例如,查詢用戶名等于某個值的用戶:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public List<User> findUsersByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.list(queryWrapper);
    }
}

復雜條件查詢

多個條件組合,例如查詢用戶名包含某個字符串且年齡大于某個值的用戶:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public List<User> findComplexUsers(String usernameLike, Integer ageGreaterThan) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", usernameLike);
        queryWrapper.gt("age", ageGreaterThan);
        return this.list(queryWrapper);
    }
}

分頁查詢

使用 Page 類實現(xiàn)分頁查詢。

首先,在 UserService 中定義分頁查詢方法:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Page<User> getUserPage(int current, int size) {
        Page<User> page = new Page<>(current, size);
        return this.page(page);
    }
}

批量操作

批量插入

使用 saveBatch 方法批量插入用戶:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public boolean saveUserBatch(List<User> userList) {
        return this.saveBatch(userList);
    }
}

批量更新

使用 updateBatchById 方法批量更新用戶:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public boolean updateUserBatch(List<User> userList) {
        return this.updateBatchById(userList);
    }
}

批量刪除

使用 removeByIds 方法批量刪除用戶:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public boolean deleteUserBatch(List<Long> idList) {
        return this.removeByIds(idList);
    }
}

自定義 SQL 操作

如果 MyBatis-Plus 提供的內(nèi)置方法無法滿足需求,可以在 Mapper 接口中定義自定義 SQL 方法。

在 Mapper 接口中定義方法

@Mapper
public interface UserMapper extends BaseMapper<User> {
    @Select("SELECT * FROM user WHERE age > #{age}")
    List<User> findUsersByAge(int age);
}

在 Service 層調(diào)用自定義方法

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public List<User> findUsersByAge(int age) {
        return userMapper.findUsersByAge(age);
    }
}

示例代碼總結(jié)

上述示例展示了在 Spring Boot 中使用 MyBatis-Plus 進行各種數(shù)據(jù)庫操作的方法。在實際項目中,可以根據(jù)具體需求,在 Service 層和 Mapper 層靈活組合和擴展這些方法,以實現(xiàn)復雜的業(yè)務(wù)邏輯。

注意事項

  • 確保數(shù)據(jù)庫表結(jié)構(gòu)與實體類屬性對應(yīng),否則可能導致數(shù)據(jù)操作異常。
  • 在使用 QueryWrapper 構(gòu)建條件時,注意條件的正確性和安全性,防止 SQL 注入。
  • 對于分頁操作,要合理設(shè)置分頁參數(shù),避免數(shù)據(jù)量過大導致性能問題。

通過以上內(nèi)容,你可以全面掌握在 Spring Boot 中使用 MyBatis-Plus 進行數(shù)據(jù)庫操作的方法。

到此這篇關(guān)于Spring Boot 中整合 MyBatis-Plus詳細步驟的文章就介紹到這了,更多相關(guān)Spring Boot 整合 MyBatis-Plus內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中BigDecimal的equals方法和compareTo方法的區(qū)別詳析

    Java中BigDecimal的equals方法和compareTo方法的區(qū)別詳析

    這篇文章主要給大家介紹了關(guān)于Java中BigDecimal的equals方法和compareTo方法區(qū)別的相關(guān)資料,對于BigDecimal的大小比較,用equals方法的話會不僅會比較值的大小,還會比較兩個對象的精確度,而compareTo方法則不會比較精確度,只比較數(shù)值的大小,需要的朋友可以參考下
    2023-11-11
  • SpringBoot兩種方式刷新配置信息

    SpringBoot兩種方式刷新配置信息

    這篇文章主要介紹了SpringBoot兩種方式刷新配置信息,一種是@?ConfigurationProperties?不能自動刷新,需要手動調(diào)用contextRefresher.refresh()方法來刷新配置,第二種方法可以嘗試下,需要的朋友可以參考下
    2023-08-08
  • Springboot集成graylog及配置過程解析

    Springboot集成graylog及配置過程解析

    這篇文章主要介紹了Springboot集成graylog及配置過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-12-12
  • 代碼分析JAVA中PCM人聲音頻變聲處理

    代碼分析JAVA中PCM人聲音頻變聲處理

    本篇文章通過代碼實例給大家分析了JAVA中PCM人聲音頻變聲處理的問題,有興趣的朋友跟著學習分考下吧。
    2018-01-01
  • Java中LocalCache本地緩存實現(xiàn)代碼

    Java中LocalCache本地緩存實現(xiàn)代碼

    本篇文章主要介紹了Java中LocalCache本地緩存實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • java中計算集合的交差并集示例代碼

    java中計算集合的交差并集示例代碼

    今天突然想Java如何計算集合的交差并集,主要是看Python語言的時候想起來的。下面這篇文章主要給大家介紹了關(guān)于java中計算集合的交差并集的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-08-08
  • SpringBoot如何讀取xml配置bean(@ImportResource)

    SpringBoot如何讀取xml配置bean(@ImportResource)

    這篇文章主要介紹了SpringBoot如何讀取xml配置bean(@ImportResource),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • java 加密之RSA算法加密與解密的實例詳解

    java 加密之RSA算法加密與解密的實例詳解

    這篇文章主要介紹了java 加密之RSA算法加解密與解密的實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • mybatis新增save結(jié)束后自動返回主鍵id詳解

    mybatis新增save結(jié)束后自動返回主鍵id詳解

    這篇文章主要介紹了mybatis新增save結(jié)束后自動返回主鍵id詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Security中的@PostAuthorize、@PreFilter和@PostFilter詳解

    Security中的@PostAuthorize、@PreFilter和@PostFilter詳解

    這篇文章主要介紹了Security中的@PostAuthorize、@PreFilter和@PostFilter詳解,@PostAuthorize是在方法調(diào)用完成后進行權(quán)限檢查,它不能控制方法是否能被調(diào)用,只能在方法調(diào)用完成后檢查權(quán)限決定是否要拋出AccessDeniedException,需要的朋友可以參考下
    2023-11-11

最新評論