最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring3整合MyBatis實現(xiàn)分頁查詢和搜索功能

 更新時間:2026年01月20日 14:32:08   作者:一直都在572  
本文詳細(xì)介紹了如何在SpringBoot和MyBatis框架下實現(xiàn)分頁查詢和搜索功能,結(jié)合Vue和ElementUI構(gòu)建前端界面,通過配置PageHelper插件,編寫動態(tài)SQL,封裝統(tǒng)一的請求工具,本文結(jié)合示例代碼講解的非常詳細(xì),感興趣的朋友一起看看吧

在實際項目開發(fā)中,數(shù)據(jù)庫數(shù)據(jù)量往往較大,直接查詢?nèi)繑?shù)據(jù)會導(dǎo)致性能下降、頁面加載緩慢;同時,用戶需要快速定位目標(biāo)數(shù)據(jù),搜索功能必不可少。本文基于 MyBatis 框架,結(jié)合前端 Vue+Element UI 與后端 SpringBoot 技術(shù)棧,詳細(xì)講解分頁查詢與搜索功能的完整實現(xiàn)流程,涵蓋后端插件配置、動態(tài) SQL 編寫、前端請求封裝與頁面展示,幫助開發(fā)者高效落地核心業(yè)務(wù)功能。

一、技術(shù)棧說明與環(huán)境準(zhǔn)備

1.1 核心技術(shù)棧

后端:SpringBoot(基礎(chǔ)框架)、MyBatis(持久層框架)、PageHelper(MyBatis 分頁插件)、MySQL(數(shù)據(jù)庫)

前端:Vue3(前端框架)、axios(HTTP 請求工具)、Element UI(UI 組件庫,含 el-table 表格、el-pagination 分頁、el-input 搜索框等組件)

1.2 環(huán)境準(zhǔn)備

后端:確保已完成 SpringBoot 與 MyBatis 的基礎(chǔ)整合(可參考前文 SpringBoot3 整合 MyBatis 步驟),引入 PageHelper 依賴;

前端:搭建 Vue3+Element UI 項目,安裝 axios 依賴,配置基礎(chǔ)請求攔截器。

二、安裝依賴

npm i axios -S

三、簡單測試axios

在Home.vue當(dāng)中配置

import axios from "axios";
axios.get("http://localhost:8080/user/findAll").then(res => {
  console.log(res.data);
});

四、SpringBoot設(shè)置跨域配置

前后端分離項目中,前端請求后端接口會存在跨域問題(瀏覽器同源策略限制),需在 SpringBoot 中添加跨域配置,允許前端域名的請求訪問。

package com.qcby.schoolshop.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        // 1. 創(chuàng)建CORS配置對象
        CorsConfiguration config = new CorsConfiguration();
        // 允許的源(前端地址,*表示允許所有源,生產(chǎn)環(huán)境建議指定具體地址)
        config.addAllowedOrigin("http://localhost:5173");
        // 允許的請求頭(*表示允許所有)
        config.addAllowedHeader("*");
        // 允許的請求方法(*表示允許所有,也可以指定GET、POST、PUT等)
        config.addAllowedMethod("*");
        // 允許攜帶Cookie(如果需要跨域傳遞Cookie,需要開啟這個,且前端請求也要配置withCredentials: true)
        config.setAllowCredentials(true);
        // 預(yù)檢請求的緩存時間(單位:秒,減少預(yù)檢請求的次數(shù))
        config.setMaxAge(3600L);
        // 2. 配置路徑映射(/**表示所有路徑)
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 3. 返回CORS過濾器
        return new CorsFilter(source);
    }
}

原因:前后端分離項目中,前端和后端通常運行在不同域名 / 端口(如前端 8081、后端 8080),瀏覽器的 “同源策略” 會禁止這種跨源請求,設(shè)置跨域是為了允許前端合法訪問后端接口,避免請求被攔截,確保數(shù)據(jù)正常交互。

重啟測試

五、封裝統(tǒng)一的請求工具:request.js

為了簡化重復(fù)代碼(不用每次請求都寫基礎(chǔ)配置)、統(tǒng)一管理請求規(guī)則(如基礎(chǔ) URL、超時時間、請求頭),還能集中處理請求 / 響應(yīng)攔截(如 Token 添加、錯誤提示),提升代碼復(fù)用性和可維護(hù)性,以后方便使用,我們新建一個request.js的文件來處理后臺發(fā)來的數(shù)據(jù)

 import axios from "axios";
 axios.get('http://localhost:8080/user/findAll').then(res=>{
     console.log(res)
 })

import axios from "axios";
import {ElMessage} from "element-plus";
const request = axios.create({
  baseURL: 'http://localhost:9999',
  timeout: 30000  // 后臺接口超時時間
})
// request 攔截器
// 可以自請求發(fā)送前對請求做一些處理
request.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json;charset=utf-8';
  return config
}, error => {
  return Promise.reject(error)
});
// response 攔截器
// 可以在接口響應(yīng)后統(tǒng)一處理結(jié)果
request.interceptors.response.use(
  response => {
    let res = response.data;
    // 兼容服務(wù)端返回的字符串?dāng)?shù)據(jù)
    if (typeof res === 'string') {
      res = res ? JSON.parse(res) : res
    }
    return res;
  },
  error => {
    if (error.response.status === 404) {
      ElMessage.error('未找到請求接口')
    } else if (error.response.status === 500) {
      ElMessage.error('系統(tǒng)異常,請查看后端控制臺報錯')
    } else {
      console.error(error.message)
    }
    return Promise.reject(error)
  }
)
export default request

六、設(shè)置查詢分頁

6.1 Mapper.xml文件

<!--注意最后別寫;-->
<select id="findAll" resultType="com.qcby.vuespringbootdemo.entity.User">
    select * from user order by id desc 
</select>

6.2 導(dǎo)入分頁的jar包 pom.xml

<!-- 分頁插件pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.6</version>
    <!--排除和我們引入的mybatis的影響-->
    <exclusions>
        <exclusion>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </exclusion>
    </exclusions>
</dependency>

6.3 service層開啟分頁查詢

public PageInfo<User> selectPage(Integer pageNum,Integer pageSize){
    //開啟分頁查詢
    PageHelper.startPage(pageNum,pageSize);
    List<User> users = userDao.findAll();
    return PageInfo.of(users);
}

6.4 Controller層

@GetMapping("/selectPage")
@ResponseBody
public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "5")Integer pageSize){
    PageInfo<User> userPageInfo = userService.selectPage(pageNum, pageSize);
    return Result.success(userPageInfo);
}

6.5 接口測試

http://localhost:8081/user/selectPage?pageNum=1&pageSize=5

6.6 前端展示

<div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" style="width: 100%" :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }">
        <!-- type="selection":這指定該列將包含用于行選擇的復(fù)選框。它允許用戶在表格中選擇一行或多行。 -->
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用戶名" width="180" />
        <el-table-column prop="birthday" label="生日" width="180" />
        <el-table-column prop="sex" label="性別" width="80" />
        <el-table-column prop="address" label="地址" width="180" />
      </el-table>
    </div>

6.7 前端請求數(shù)據(jù)

import { reactive } from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
const data = reactive({
  name: null,
  pageNum: 1,
  pageSize: 5,
  total:0,
  tableData: []
})
const load = () => {
  request.get('/user/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()

接下來處理一下時間的顯示問題

// 添加日期格式化函數(shù)
const dateFormat = (row, column, cellValue) => {
  if (!cellValue) return ''
  const date = new Date(cellValue)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

最后別忘了

<div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          :page-size="data.pageSize"
          layout="total, prev, pager, next"
          :total="data.total"
          @current-change="load"
          @size-change="load"
      />
    </div>

七、搜索設(shè)置

7.1 前端設(shè)置搜索框

<div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px; margin-right: 5px" v-model="data.username" placeholder="請輸入用戶名查詢" :prefix-icon="Search"></el-input>
      <el-input clearable @clear="load" style="width: 260px; margin-right: 5px" v-model="data.address" placeholder="請輸入地址查詢" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 詢</el-button>
      <el-button @click="reset">重 置</el-button>
</div>

7.2 前端設(shè)置入?yún)?/h3>

 params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      username: data.username,
      address: data.address
    }

7.3 設(shè)置重置

//搜索重置
const reset = () => {
  data.username = null
  data.address = null
  load()
}

7.4 Mapper.xml設(shè)置查詢

<select id="findAll" resultType="com.qcby.springboot.entity.User"
        parameterType="com.qcby.springboot.entity.User">
    select * from user
        <where>
           <if test="username!=null">
               username like concat('%', #{username}, '%')
           </if>
            <if test="address!=null">
                and address  like concat('%', #{address}, '%')
            </if>
        </where>
    order by id
</select>

7.5 service層

@Override
public PageInfo<User> selectPage(Integer pageNum, Integer pageSize,User user) {
    //開啟分頁查詢
    PageHelper.startPage(pageNum,pageSize);
    List<User> users = userDao.findAll(user);
    return PageInfo.of(users);
}

7.6 controller層

@GetMapping("/selectPage")
@ResponseBody
public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "5")Integer pageSize,
                         User user){
    System.out.println(user.toString());
    PageInfo<User> userPageInfo = userService.selectPage(pageNum, pageSize,user);
    return Result.success(userPageInfo);
}

到此這篇關(guān)于Spring3整合MyBatis實現(xiàn)分頁查詢和搜索功能的文章就介紹到這了,更多相關(guān)Spring3 MyBatis分頁查詢和搜索內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

韩城市| 科技| 西峡县| 闽清县| 张北县| 双辽市| 黄陵县| 漳平市| 海南省| 册亨县| 务川| 图片| 通化县| 旬阳县| 会宁县| 宜城市| 岚皋县| 诸城市| 三江| 龙岩市| 西乡县| 志丹县| 永城市| 藁城市| 奉化市| 江门市| 郎溪县| 房产| 嵊泗县| 达州市| 巴中市| 吴旗县| 常宁市| 隆昌县| 彩票| 广平县| 华坪县| 舒城县| 泸水县| 盐池县| 绵竹市|