极简Springboot+Mybatis-Plus+Vue零基础萌新都看得懂的分页查询(富含前后端项目案例)

目录

springboot配置相关

依赖配置

yaml配置

 MySQL创建与使用

(可拿软件包+项目系统)

创建数据库

创建数据表

mybatis-plus相关

 Mapper配置

​编辑

启动类放MapperScan

启动类中配置

添加config配置文件

Springboot编码

实体类

mapperc(Dao)层

Service层

Sevice接口

Controller层

vue相关

界面展现

代码展现

解决跨域问题

config包中添加一个跨域请求允许


springboot配置相关

依赖配置

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

     
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
    </dependencies>

yaml配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/你的数据库名字?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    username: 你的数据库账号
    password: 你的数据库密码
  
mybatis-plus:
  configuration:
    #这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    call-setters-on-nulls: true
  global-config:
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
      id-type: auto #ID自增
  

 MySQL创建与使用

(可拿软件包+项目系统)

Navicat软件那些数据库软件(公棕号 wmcode 自取) 随便搞个数据表

我这里就以日记系统(需要可以点进去看看)为例吧、

创建数据库

创建数据表

这里插个题外话,就是数据库有数据 删除部分之后 索引还是递增的解决方法

MySQL | 恢复数据表内的索引为初始值1(有兴趣点击查看)


mybatis-plus相关

(可以去官网复制也行)

MyBatis-Plus 🚀 为简化开发而生

 Mapper配置

继承Mybatis-Plus的接口

启动类放MapperScan

复制Mapper文件夹路径

启动类中配置

添加config配置文件

创建一个config包并创建类名任意,这里以官网给的为例

@Configuration

//这里启动类有的话 就不用写了 完全可以删了
@MapperScan("scan.your.mapper.package") 

public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

         // 这里一定要选好数据库类型
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        return interceptor;
    }
}

Springboot编码

实体类

package com.diarysytem.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@TableName("diary")
public class Diary {

    @TableField(value = "diary_pid")
    private Integer tasksPid;

    @TableField(value = "diary_title")
    private String diaryTitle;

    @TableField(value = "diary_content")
    private String diaryContent;

    @TableField(value = "diary_mood")
    private double diaryMood;

    @TableField(value = "diary_body")
    private double diaryBody;

    @TableField(value = "diary_time")
    private String diaryTime;

    @TableField(value = "diary_delete")
    private int diaryDelete;


}

mapperc(Dao)层

package com.diarysytem.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.diarysytem.entity.Diary;
import org.apache.ibatis.annotations.Mapper;


@Mapper
public interface DiaryMapper extends BaseMapper<Diary> {
}

Service层

package com.diarysytem.service;

import com.diarysytem.entity.Diary;


public interface DiaryService {

    public boolean userInsertDiary(Diary diary);
}

Sevice接口

package com.diarysytem.service.Impl;

import com.diarysytem.entity.Diary;
import com.diarysytem.mapper.DiaryMapper;
import com.diarysytem.service.DiaryService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DiaryServiceImpl implements DiaryService {

    private DiaryMapper diaryMapper;

    @Autowired
    public DiaryServiceImpl(DiaryMapper diaryMapper) {
        this.diaryMapper = diaryMapper;
    }

    @Override
    public boolean userInsertDiary(Diary diary) {
        return diaryMapper.insert(diary) > 0;
    }
}

Controller层

package com.diarysytem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diarysytem.entity.Diary;
import com.diarysytem.entity.WebDiary;
import com.diarysytem.mapper.DiaryMapper;
import com.diarysytem.service.DiaryService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
public class DirayController {
    private DiaryMapper diaryMapper;

    private DiaryService diaryService;

    // 写入日记
    @PostMapping("write")
    public Boolean userWriteDiary(@RequestBody WebDiary webDiary){
        Diary tempDiary = new Diary();
        tempDiary.setTasksPid(null);
        tempDiary.setDiaryTitle(webDiary.getDiaryTitle());
        tempDiary.setDiaryContent(webDiary.getDiaryContent());
        tempDiary.setDiaryMood(webDiary.getDiaryMood());
        tempDiary.setDiaryBody(webDiary.getDiaryBody());
        tempDiary.setDiaryTime(webDiary.getDiaryTime());
        tempDiary.setDiaryDelete(0);
        return diaryService.userInsertDiary(tempDiary);
    }

    //分页查询(这里方便演示就直接注入 service 了)
    @GetMapping("fpage")
    public Page<Diary> fenPages(int current,int size){
        Page<Diary> page = new Page<>(current,size);
        return diaryMapper.selectPage(page, null);
    }

}

vue相关

以我项目为例 有需要了解下面自取

Springboot+vue自制可爱英语日记系统

界面展现

代码展现

<script>
import dayjs from 'dayjs';
import axios from 'axios';

export default {
  data() {
    return {
      userDiaryList: [],
      currentPage: 1, // 当前页面
      totalPages: 0, // 总页面
      pageSize: 3 // 每个页面的数量
    };
  },
  created() {
    axios.get('http://127.0.0.1:8887/fpage', {
        params: {
          current: this.currentPage, // 页数 = sum / size
          size: this.pageSize //每页显示多少条
        }
      })
      .then(res => {
        console.log(res.data);
        const { records, pages, current } = res.data;
        this.userDiaryList = records;
        this.totalPages = pages;
        this.currentPage = current;
      });
  },
  methods: {
    getUpPage(){
        this.currentPage--;
        axios.get('http://127.0.0.1:8887/fpage', {
            params: {
            current: this.currentPage, // 页数 = sum / size
            size: this.pageSize //每页显示多少条
            }
        })
        .then(res => {
            console.log(res.data);
            const { records, pages, current } = res.data;
            this.userDiaryList = records;
            this.totalPages = pages;
            this.currentPage = current;
        });
    },
    getNextPage(){
        this.currentPage++;
        axios.get('http://127.0.0.1:8887/fpage', {
            params: {
            current: this.currentPage, // 页数 = sum / size
            size: this.pageSize //每页显示多少条
            }
        })
        .then(res => {
            console.log(res.data);
            const { records, pages, current } = res.data;
            this.userDiaryList = records;
            this.totalPages = pages;
            this.currentPage = current;
        });
    },
    userDiaryListClick(index){
        console.log(index);
        this.currentPage = index;
        axios.get('http://127.0.0.1:8887/fpage', {
            params: {
            current: this.currentPage, // 页数 = sum / size
            size: this.pageSize //每页显示多少条
            }
        })
        .then(res => {
            console.log(res.data);
            const { records, pages, current } = res.data;
            this.userDiaryList = records;
            this.totalPages = pages;
            this.currentPage = current;
        });
    },
    TImeZhuanHuan(time){
        try {
            console.log(time)
            const date = dayjs(time);
            if (!date.isValid()) {
            throw new Error('Invalid timestamp');
            }
            return this.formattedDate = date.format('YYYY-MM-DD HH:mm:ss');
        } catch (error) {
            console.error('Error formatting timestamp:', error);
            return this.formattedDate = 'Invalid timestamp';
        }
    }
    
  }
}
</script>

<template>

  <div>
    <main class="read">
      <h1 class="am_r_top_1 h1s">Search for diary<span class="pagsNumber">({{this.currentPage}}/{{ this.totalPages }})</span></h1>
      <div class="search am_r_1">
        <span>Search</span>
        <input type="text" placeholder="Search for diary" class="search_input">
      </div>
      
      <div class="userDiaryItems">
        <div class="userDiaryList am_r_5" v-for="(item, index) in userDiaryList" :key="index">
          <div class="userDiaryList_left">
            <span class="userDiaryList_left_number">No.{{ item.tasksPid }}</span>
            <h2>{{ item.diaryTitle }}</h2>
            <span class="userDiaryList_left_time">
                <span>{{ TImeZhuanHuan(item.diaryTime) }}</span>   
                <span class="userStatusImg"><img  src="/public/xiai.png" alt=""> {{ item.diaryMood}}</span>
                <span class="userStatusImg"><img  src="/public/tizhizhishu.png" alt="">  {{ item.diaryBody }}</span>
            </span>
          </div>
          <div class="userDiaryList_right">
            <span>browse</span>
            <span>------</span>
            <span>delete</span>
          </div>
        </div>
      </div>
    </main>
    <!-- 分页导航 -->

    <div class="pages am_r_3">
        <button @click="getUpPage" class="buts">上一页</button>

        <el-scrollbar style="width: 80%;padding: 10px 0;">
            <ul class="scrollbar-flex-content">
                <li v-for="index in totalPages" :key="index" class="scrollbar-demo-item" @click="userDiaryListClick(index)">{{index}}</li>
            </ul>
        </el-scrollbar>

        <button @click="getNextPage" class="buts">下一页</button>
    </div>


  </div>

</template>


<style scoped>
.userStatusImg{
    padding: 0 10px;
}
.userStatusImg img{
    margin: 0 0 -2px 0;
    width: 20px;
}
.pagsNumber{
    padding: 0 10px;
    font-size: 22px;
}
.pages{
    display: flex;
    justify-content: space-evenly;
    align-items: center;

}
.buts{
    border-radius: 10px;
    padding: 10px 5px;
    border: 0;
    background-color: rgb(248, 189, 144);
    color: #fff;

}
.buts:hover{
    cursor: pointer;
    background-color: rgb(254, 133, 40);

}

.scrollbar-flex-content {
    padding: 15px 0;
    display: flex;
}
.scrollbar-demo-item {
    padding: 5px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 5px;
    text-align: center;
    border-radius: 4px;
    font-size: 18px;
    color: rgb(159, 100, 32);
    background-color: rgb(255, 233, 209);

}
.scrollbar-demo-item:hover{
    cursor: pointer;
    background-color: rgb(255, 220, 183);


}


.userDiaryItems{
    height: 50vh;
}

.pagination a{
    text-decoration: none;
    font-weight: bold;
    font-size: 18px;
    color: rgb(212, 147, 77);

}
.userDiaryList{
    display: flex;
    justify-content: space-between;
    padding: 10px 10px 10px 10px;
    border-radius: 10px;
    margin: 10px 0;
    align-items: center;
    background-color: rgb(255, 233, 209);
}

.userDiaryList_left_number{
    font-size: 18px;
    font-weight: bold;
    color: rgb(204, 175, 141);
}
.userDiaryList_left h2{
    overflow: hidden;
    padding: 10px 0 0px 10px;
    font-size: 25px;
    font-weight: bold;
    color: rgb(159, 100, 32);
}


.userDiaryList_left_time{
    display: flex;
    padding: 5px 0 10px 10px;
    font-size: 18px;
    color: rgb(204, 175, 141);
}
.userDiaryList_right{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.userDiaryList_right span{
    font-size: 18px;
    font-weight: bold;
    color: rgb(204, 175, 141);
}
.search{
    display: flex;
    padding: 10px 10px 10px 10px;
    border-radius: 10px;
    margin: 10px 0;
    align-items: center;
    background-color: rgb(255, 233, 209);
}
.search span{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 15%;
    padding: 10px 0;
    margin: 0 5px 0 0;
    border-radius: 10px;
    font-weight: bold;
    font-size: 25px;
    color: rgb(255, 255, 255);
    background-color: rgb(254, 133, 40);
    box-shadow: 0 3px 10px rgba(201, 102, 27, 0.525);

}
.search input{
    width: 85%;
    border-radius: 10px;
    border: 0;
    padding: 15px;
    outline: none;
    font-size: 18px;
    font-weight: bold;
    color: rgb(121, 91, 33);

}
</style>

解决跨域问题

我前端是localhost:8888,后端是127.0.0.1:8887

我直接在后端进行跨域操作了

config包中添加一个跨域请求允许

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8888")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

(到底啦)

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小Mie不吃饭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值