springboot從零開始:整合 mybatis-plus 和其分頁查詢功能

前言:

本系列博客記錄 springboot 求學之路:
寫接口肯定是繞不開數據庫連接,無論 mysql、redis、es都有涉及到,本博客討論 mysql 的基礎連接配置,多數據庫配置在引入 dynamic 整合多 mysql 數據源

1.聲明依賴
<!-- mysql 驅動庫 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- mybatis-plus 依賴 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>

tips:
mysql-connector-java 並沒有指定版本,所以我挺好奇用的是啥版本,
默認版本查看方式:按 ctrl 然後單擊 pom 文件相關依賴聲明行,可以查看。

2.配置數據庫連接源

在配置文件中添加數據庫連接信息(建議使用yml配置文件)

spring:
  datasource:
    url: jdbc:mysql://ip:port/db?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    username: user
    password: pwd
3.創建測試信息

先創建一個數據表 web_info,表結構如下

id             主鍵,自增
host           網站域名
web_name       網站名稱
插入第一條數據 :1 www.baidu.com 百度

工程裏面創建三個包,
一般約定 modle 放數據表實例,mapper 放查詢接口,service 放操作邏輯,如下:
在這裏插入圖片描述

4.在 modle 包下面創建數據表的實體類
package com.test.demo.modle;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(value = "web_info")
public class WebInfo {

    @TableId(value = "id", type = IdType.AUTO)
    private int id;

    private String host;

    //表字段 web_name 映射到 webName 字段
    @TableField(value = "web_name")
    private String webName;
}

5.在 mapper 包下面創建數據表的查詢接口,一般沒有特殊查詢就話就是一個空方法
package com.test.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.test.demo.modle.WebInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface WebInfoMapper extends BaseMapper<WebInfo> {
}

tips:
@Mapper 不能少,這個標明本接口在啓動 springboot 時會被掃描到,要不然會提示找不到相關 mapper。

6.在 service 包下面創建數據表的查詢邏輯實現
package com.test.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.demo.mapper.WebInfoMapper;
import com.test.demo.modle.WebInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WebInfoService{

    @Autowired
    private WebInfoMapper webInfoMapper;

    // 簡單查詢
    public WebInfo getById(Integer id) {
        return webInfoMapper.selectById(id);
    }
}
7. 在controller 包寫一個測試接口
package com.test.demo.controller;

import com.test.demo.service.WebInfoHandle;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private WebInfoService webInfoService;

    @GetMapping(path = "/get/db")
    public Object get(@RequestParam(value = "id", required = false, defaultValue = "1") Integer tableId) {
        return webInfoService.getById(tableId);
    }

}
8.啓動測試一下

在這裏插入圖片描述

9.分頁查詢

數據量比較大的情況下是需要接口做分頁,如果數據量小可以央求前端做一下分頁。

  1. 首先建一個 config 的包,用於存放 springboot 的配置類;在包裏面創建類對mybatis-plus 進行配置
package com.test.demo.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.test.demo.mapper")
public class MyBatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

tips: @MapperScan 不能少,其值標明這個配置對哪些 mapper 生效,這時候可以把步驟5的 @Mapper 註解去掉了

  1. 在 WebInfoService 裏面增加一個翻頁的查詢方法
package com.test.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.demo.mapper.WebInfoMapper;
import com.test.demo.modle.WebInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class WebInfoService {

    @Autowired
    private WebInfoMapper webInfoMapper;

    // 簡單查詢
    public WebInfo getById(Integer id) {
        return webInfoMapper.selectById(id);
    }

    // 分頁查詢
    public IPage<Map<String, Object>> getManyGtId(int id, int pageNum, int pageSize) {
        QueryWrapper<WebInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().gt(WebInfo::getId, id);
        Page<WebInfo> page = new Page<>(pageNum, pageSize);
        IPage<Map<String, Object>> iPage = webInfoMapper.selectMapsPage(page, queryWrapper);
        System.out.println(iPage);
        return iPage;
    }

}

  1. TestController 增加測試方法
package com.test.demo.controller;

import com.test.demo.service.WebInfoHandle;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private WebInfoService webInfoService;

    @GetMapping(path = "/get/db")
    public Object get(@RequestParam(value = "id", required = false, defaultValue = "1") Integer tableId,
                      @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNum,
                      @RequestParam(value = "size", required = false, defaultValue = "10") Integer pageSize) {

        return webInfoService.getManyGtId(tableId, pageNum, pageSize);
    }

}
  1. 測試
    瀏覽器輸入:http://127.0.0.1:8080/get/db?id=0&page=2&size=10
    返回樣例數據如下:
{
	"records": [{
		"host": "news.qq.com",
		"id": 11,
		"web_name": "騰訊新聞"
	}, {
		"host": "www.qq.com",
		"id": 12,
		"web_name": "騰訊網"
	}, {
		"host": "tech.qq.com",
		"id": 13,
		"web_name": "騰訊科技"
	}],
	"total": 13,
	"size": 10,
	"current": 2,
	"pages": 2
}
10.End
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章