SpringBoot | 3.3 整合MyBatis-Plus



前言

有了前面自動配置數據源、JDBC與MyBatis的基礎后,自動配置MyBatis就很簡單了。

注:在說明注解時,第一點加粗為注解中文含義,第二點為一般加在哪身上,縮進或代碼塊為示例,如:

@注解

  • 中文含義
  • 加在哪
  • 其他……
    • 語句示例
    //代碼示例
    

1. 什么是MyBatis-Plus

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

它提供兩大接口BaseMapper<T>IService<T>,方便我們操作數據庫與業務。

1.1 BaseMapper<T>接口

可以令XXXMapper接口繼承基類BaseMapper<T>,BaseMapper里實現了一些方法方便我們操作數據庫:

  • XXXMapper繼承該接口后,無需編寫mapper.xml文件,即可進行crud操作;

BaseMapper接口

1.2 IService<T>接口

同理對於service有頂層接口IService<T>

IService接口


2. 整合MyBatis-Plus以及CRUD功能

直接導入場景依賴即可。

2.1 導入場景依賴

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>

引入mybatis-plus-boot-starter后,其幫我們引入了mybatis-plus擴展包與核心包(核心包里引入了mybatis核心包、mybatis與spring整合的包)、starter-jdbc。

2.2 CRUD功能

Mybatis里對service層設有頂層接口IService<T>;而對IService<T>有實現類ServiceImpl<操作的基本表,返回類型>

在Bean類里

@TableName("數據庫名")

  • 數據庫表名
  • 標注在bean包下的類里;
  • mybatis-plus默認識別數據庫表名與類名相同的屬性進行綁定,當名字不同時,需要在bean包下的對應類上標注@TableName("數據庫名");
  • 當名字相同時可以不標注。

在Service層里

public interface UserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
}

IUserServiceImpl里的方法


3. Mabatis-plus實現分頁功能

續上面Service層里的配置。

要實現分頁功能首先要導入分頁插件

  • 在config包下,注意版本;
@Configuration
public class MyBatisConfig {

    /**
     * MybatisPlusInterceptor
     * @return
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

        //這是分頁攔截器
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 設置請求的頁面大於最大頁后操作, true調回到首頁,false 繼續請求  默認false
        paginationInnerInterceptor.setOverflow(true);
        // 設置最大單頁限制數量,默認 500 條,-1 不受限制
        paginationInnerInterceptor.setMaxLimit(500L);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);

        return mybatisPlusInterceptor;
    }  
}

在controller類里(分頁功能)

@Controller
public class TableController {

    @Autowired
    UserService userService;

    //刪除用戶
    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn",defaultValue = "1")Integer pn,
                             RedirectAttributes ra){

        userService.removeById(id);
	//重定向回到當前頁碼
        ra.addAttribute("pn",pn);
        //重定向
        return "redirect:/dynamic_table";
    }

    //請求參數pn表示跳轉到的頁數,並設置默認值為1
    @GetMapping("/dynamic_table")
    public String dynamic_table(@RequestParam(value="pn",defaultValue = "1") Integer pn,Model model){

        //構造分頁參數
        Page<User> page = new Page<>(pn, 2);
        //調用page進行分頁,返回page類型結果
        Page<User> userPage = userService.page(page, null);

//        userPage.getRecords()
//        userPage.getCurrent()
//        userPage.getPages()

        //將page設置進model屬性里
        model.addAttribute("users",userPage);

        return "table/dynamic_table";
    }

    @GetMapping("/responsive_table")
    public String responsive_table(){
        return "table/responsive_table";
    }

    @GetMapping("/editable_table")
    public String editable_table(){
        return "table/editable_table";
    }
}

在HTML里(分頁功能)

  • users.current:表示當前頁數
  • users.pages:總頁數
  • users.total:總記錄數
<div class="adv-table">
    <table class="display table table-bordered table-striped" id="dynamic-table">
        <thead>
            <tr>
                <th>#</th>
                <th>name</th>
                <th>age</th>
                <th>email</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr class="gradeX" th:each="user: ${users.records}">
                <td th:text="${user.id}"></td>
                <td>[[${user.name}]]</td>
                <td th:text="${user.age}">Win 95+</td>
                <td th:text="${user.email}">4</td>
                <td>
                    <a th:href="@{/user/delete/{id}(id=${user.id},pn=${users.current})}" class="btn btn-danger btn-sm" type="button">刪除</a>
                </td>
            </tr>
        </tfoot>
    </table>

    <div class="row-fluid">
        <div class="span6">
            <div class="dataTables_info" id="dynamic-table_info">
                當前第[[${users.current}]]頁  總計 [[${users.pages}]]頁  共[[${users.total}]]條記錄
            </div>
        </div>
        <div class="span6">
            <div class="dataTables_paginate paging_bootstrap pagination">
                <ul>
                    <li class="prev disabled"><a href="#">← 前一頁</a></li>
                    <li th:class="${num == users.current?'active':''}" th:each="num:${#numbers.sequence(1,users.pages)}" >
                        <a th:href="@{/dynamic_table(pn=${num})}">[[${num}]]</a>
                    </li>
                    <li class="next disabled"><a href="#">下一頁 → </a></li>
                </ul>
            </div>
        </div>
    </div>
</div>

4. *MyBatis-Plus自動配置源碼分析

源碼分析,跟前面文章類似,這里不做過多解釋。

  • 引入mybatis-plus-boot-starter后,首先找到META-INF包下的spring.factories工廠,通過讀取EnableAutoConfiguration獲取啟動時加載的類 :MybatisPlusAutoConfiguration配置類;進而找到配置項 MybatisPlusProperties
  • 通過自動配置項得知:通過mybatis-plus:xxx對mybatis-plus進行定制;
  • 通過自動配置類得知:給我們自動配置好了哪些組件:
    • SqlSessionFactory自動配置好:使用配置過的數據源dataSource,配置MyBatis的全局配置文件configLocation;
    • mapperLocations自動配置好:有默認值 classpath*:/mapper/**/*.xml,即:任意包的類路徑下的所有mapper文件夾下任意路徑下的所有xml都是sql映射文件。 建議以后sql映射文件,放在mapper路徑下。
    • SqlSessionTemplate自動配置好
    • MapperScannerRegistrarNotFoundConfiguration自動配置好: @Mapper 標注的接口也會被自動掃描;可以直接@MapperScan("com.atguigu.admin.mapper") 批量掃描就行


最后

新人制作,如有錯誤,歡迎指出,感激不盡!
歡迎關注公眾號,會分享一些更日常的東西!
如需轉載,請標注出處!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM