zl程序教程

您现在的位置是:首页 >  其他

当前栏目

MyBatisPlusConfig中配置分页插件以及分页案例

案例配置插件 以及 分页
2023-09-27 14:26:04 时间

1、MyBatisPlusConfig中配置分页插件

依赖参考:https://www.cnblogs.com/konglxblog/p/16793936.html

package com.stu.service.base.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 分页功能
 */
@Configuration
@MapperScan("com.stu.service.*.mapper")
public class MyBatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }


}

2、方式一

业务层调用baseMapper封装的selectPage接口,返回IPage<Teacher>(不涉及mapper.java文件和sql.xml文件)

controller

package com.stu.service.edu.controller.admin;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.service.base.result.R;
import com.stu.service.edu.entity.Teacher;
import com.stu.service.edu.entity.vo.ChapterVo;
import com.stu.service.edu.entity.vo.TeacherQueryVo;
import com.stu.service.edu.service.TeacherService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author stu
 * @since 2022-04-11
 */
@RestController
@RequestMapping("/admin/edu/teacher")
//@CrossOrigin
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    /***********************************
     * 用途说明:批量删除
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @DeleteMapping("batchRemoveTeacher")
    public R batchRemoveTeacher(@RequestBody List<String> idList) {

        boolean result = teacherService.removeByIds(idList);
        if (result) {
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    /***********************************
     * 用途说明:删除讲师
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @DeleteMapping("deleteTeacher/{id}")
    public R deleteTeacher(@PathVariable String id) {

        /*        if (true) {
            throw new CustomException(ResultCodeEnum.DIVIDE_ZERO);
        }*/

        boolean result = teacherService.removeById(id);
        if (result) {
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    /***********************************
     * 用途说明:修改讲师
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @PostMapping("updateTeacher")
    public R updateTeacher(@RequestBody Teacher teacher) {
        boolean result = teacherService.updateById(teacher);
        if (result) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }

    /***********************************
     * 用途说明:添加讲师
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @ApiOperation("添加讲师")
    @PostMapping("addTeacher")
    public R addTeacher(@ApiParam("讲师对象") @RequestBody Teacher teacher) {
        boolean result = teacherService.save(teacher);
        if (result) {
            return R.ok().message("保存成功");
        }
        return R.error().message("保存失败");
    }

    /***********************************
     * 用途说明:查询讲师表所有数据
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @GetMapping("findAll")
    public R findAllTeacher() {
        List<Teacher> list = teacherService.list();
        return R.ok().data("list", list);
    }

    /***********************************
     * 用途说明:查询
     * 返回值说明: com.stu.service.edu.entity.Teacher
     ***********************************/
    @GetMapping("get/{id}")
    public R getTeacher(@PathVariable String id) {

        return R.ok().data("dataInfo", teacherService.getById(id));

    }

    /***********************************
     * 用途说明:查询讲师表所有数据
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @GetMapping("pageList/{page}/{limit}")
    public R pageList(@PathVariable long page, @PathVariable long limit, TeacherQueryVo teacherQueryVo) {
        Page<Teacher> pageParam = new Page<>(page, limit);
        teacherService.listPage(pageParam, teacherQueryVo);
        Map<String, Object> map = new HashMap<String, Object>();
        long total = pageParam.getTotal();
        List<Teacher> list = pageParam.getRecords();
        map.put("total", total);
        map.put("list", list);
        return R.ok().data(map);

    }
}

service接口

package com.stu.service.edu.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.service.edu.entity.Teacher;
import com.baomidou.mybatisplus.extension.service.IService;
import com.stu.service.edu.entity.vo.ChapterVo;
import com.stu.service.edu.entity.vo.TeacherQueryVo;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 讲师 服务类
 * </p>
 *
 * @author stu
 * @sinc e 2022-04-11
 */
public interface TeacherService extends IService<Teacher> {

    /***********************************
     * 用途说明:分页
     * @param pageParam
     * @param teacherQueryVo
     * 返回值说明:
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.stu.service.edu.entity.Teacher>
     ***********************************/
    IPage<Teacher> listPage(Page<Teacher> pageParam, TeacherQueryVo teacherQueryVo);

    /***********************************
     * 用途说明:取得推荐讲师
     * 返回值说明:
     * @return java.util.List<com.stu.service.edu.entity.Teacher>
     ***********************************/
    List<Teacher> listHotTeacher();

    /***********************************
     * 用途说明:前台讲师分页
     * @param pageParam
     * 返回值说明:
     * @return java.util.Map<java.lang.String, java.lang.Object>
     ***********************************/
    Map<String,Object> listPageTeachers(Page<Teacher> pageParam);

}

service实现类

package com.stu.service.edu.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stu.service.edu.entity.Teacher;
import com.stu.service.edu.entity.vo.TeacherQueryVo;
import com.stu.service.edu.mapper.TeacherMapper;
import com.stu.service.edu.service.TeacherService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 讲师 服务实现类
 * </p>
 *
 * @author stu
 * @since 2022-04-11
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Autowired
    private TeacherService teacherService;

    /***********************************
     * 用途说明:分页
     * @param pageParam
     * @param teacherQueryVo
     * 返回值说明:
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.stu.service.edu.entity.Teacher>
     ***********************************/
    @Override
    public IPage<Teacher> listPage(Page<Teacher> pageParam, TeacherQueryVo teacherQueryVo) {

        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort", "id");

        if (teacherQueryVo == null) {
            return baseMapper.selectPage(pageParam, queryWrapper);
        }

        String name = teacherQueryVo.getName();
        Integer level = teacherQueryVo.getLevel();
        String begin = teacherQueryVo.getBegin();
        String end = teacherQueryVo.getEnd();

        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }

        if (null != level) {
            queryWrapper.eq("level", level);
        }

        if (!StringUtils.isEmpty(begin)) {
            queryWrapper.ge("gmt_create", begin);
        }

        if (!StringUtils.isEmpty(end)) {
            queryWrapper.le("gmt_create", end);
        }

        return baseMapper.selectPage(pageParam, queryWrapper);
    }

    /***********************************
     * 用途说明:取得推荐讲师
     * 返回值说明:
     * @return java.util.List<com.stu.service.edu.entity.Teacher>
     ***********************************/
    @Cacheable(value = "index", key = "'listHotTeacher'")
    @Override
    public List<Teacher> listHotTeacher() {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("sort");
        queryWrapper = queryWrapper.last("limit 4");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Map<String, Object> listPageTeachers(Page<Teacher> pageParam) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_modified").orderByDesc("sort");
        baseMapper.selectPage(pageParam,queryWrapper);

        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("items", pageParam.getRecords());//当前页记录
        mapParam.put("current", pageParam.getCurrent());//当前页
        mapParam.put("pages", pageParam.getPages());//共有多少页
        mapParam.put("size", pageParam.getSize());//每页的记录数
        mapParam.put("total", pageParam.getTotal());//总记录数
        mapParam.put("hasNext", pageParam.hasNext());//是否有上一页
        mapParam.put("hasPrevious", pageParam.hasPrevious());//是否有下一页

        return mapParam;
    }
}

vue

vue.js

import request from '@/utils/request'

export default {
    pageList(page, limit, teacher) {
        return request({
            url: `/admin/edu/teacher/pageList/${page}/${limit}`,
            method: 'get',
            params: teacher
        })
    },
    removeById(id) {
        return request({
            url: `/admin/edu/teacher/deleteTeacher/${id}`,
            method: 'delete'
        })
    },
    batchRemove(idList) {
        return request({
            url: '/admin/edu/teacher/batchRemoveTeacher',
            method: 'delete',
            data: idList
        })
    },
    save(teacher) {
        return request({
            url: '/admin/edu/teacher/addTeacher',
            method: 'post',
            data: teacher
        })
    },
    //讲师详情
    getDetail(id) {
        return request({
            url: `/admin/edu/teacher/get/${id}`,
            method: 'get'
        })
    },
    update(teacher) {
        return request({
            url: '/admin/edu/teacher/updateTeacher',
            method: 'post',
            data: teacher
        })
    },

    //取得讲师的集合
    listAllTeachers() {
        return request({
            url: '/admin/edu/teacher/findAll',
            method: 'get'
        })
    },
}

vue页面

<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchData.name" placeholder="讲师" />
      </el-form-item>

      <el-form-item>
        <el-select v-model="searchData.level" clearable placeholder="头衔">
          <el-option value="1" label="高级讲师" />
          <el-option value="2" label="首席讲师" />
        </el-select>
      </el-form-item>

      <el-form-item label="入驻时间">
        <el-date-picker
          v-model="searchData.begin"
          placeholder="开始时间"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="-">
        <el-date-picker
          v-model="searchData.end"
          placeholder="结束时间"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="pageList()"
          >查询</el-button
        >
        <el-button type="default" @click="resetData()">清空</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-button type="danger" size="mini" @click="batchRemove()"
        >批量删除</el-button
      >
    </div>
    <!-- 表格 -->
    <el-table
      :data="list"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column label="ID" width="50">
        <!-- 使用连续的序号 -->
        <template slot-scope="scope">
          {{ (currentPage - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="80" />
      <el-table-column label="头衔" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.level === 1">
            <el-tag type="primary" size="mini">高级讲师</el-tag>
          </span>
          <span v-else>
            <el-tag type="success" size="mini">首席讲师</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="资历" />
      <el-table-column prop="sort" label="排序" width="50" />
      <el-table-column prop="joinDate" label="入驻时间" width="160" />
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="toUpdate(scope.row.id)"
            >更改</el-button
          >
          <el-button type="danger" size="mini" @click="removeById(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :current-page="currentPage"
      :page-size="limit"
      :total="total"
      :page-sizes="[5, 10, 15, 20]"
      style="padding: 12px 8px; text-align: center"
      layout="sizes, prev, pager, next, jumper, ->, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
 

<script>
import teacherApi from "@/api/teacher";
export default {
  data() {
    return {
      list: [], //列表数据
      total: 0,
      currentPage: 1, //当前页
      limit: 10, //每页记录数
      searchData: {},
      idList: null,
    };
  },
  created() {
    this.pageList();
  },
  methods: {
    //跳转到修改页面
    toUpdate(id) {
      this.$router.push({ path: `/teacher/editTeacher/${id}` });
    },
    //批量删除
    batchRemove() {
      
      if (!this.idList || this.idList.length <= 0) {
        this.$message({
          type: "info",
          message: "请先选择要删除的数据!",
        });
        return false;
      }
      let arrayIds = [];
      this.idList.forEach((element) => {
        arrayIds.push(element.id);
      });

      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除api
          teacherApi.batchRemove(arrayIds).then((res) => {
         
            if (res.code === 20000 && res.data) {
              this.$message({
                type: "info",
                message: "刪除成功: ",
              });
              this.pageList();
            } else {
              this.$message({
                type: "info",
                message: "刪除失败: ",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //多选
    handleSelectionChange(idList) {
      this.idList = idList;
    },
    //删除
    removeById(data) {
      this.$confirm("此操作将永久删除" + data.name + ", 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除api
          teacherApi.removeById(data.id).then((res) => {
            if (res.code === 20000 && res.data) {
              this.$message({
                type: "info",
                message: "刪除成功: ",
              });
              this.pageList();
            } else {
              this.$message({
                type: "info",
                message: "刪除失败: ",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    resetData() {
      this.searchData = {};
      this.pageList();
    },
    //改变数量
    handleSizeChange(size) {
      this.limit = size;
      this.pageList();
    },
    //改变页码
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.pageList();
    },

    //分页查询
    pageList() {
      teacherApi
        .pageList(this.currentPage, this.limit, this.searchData)
        .then((res) => {
          if (res.code === 20000 && res.data) {
            this.$message({
              type: "info",
              message: "查询成功: ",
            });
            this.list = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message({
              type: "info",
              message: "查询失败: ",
            });
          }
        })
        .catch((e) => {
          this.$message({
            type: "info",
            message: "查询异常",
          });
        });
    },
  },
};
</script>

3、方式二,复杂查询需要用到sql,涉及mapper文件和xml文件

controller

package com.stu.service.edu.controller.admin;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.service.base.result.R;
import com.stu.service.base.result.ResultCodeEnum;
import com.stu.service.edu.entity.Course;
import com.stu.service.edu.entity.CourseDescription;
import com.stu.service.edu.entity.form.CourseInfoForm;
import com.stu.service.edu.entity.vo.CoursePublishVo;
import com.stu.service.edu.entity.vo.CourseQueryVo;
import com.stu.service.edu.entity.vo.CourseVo;
import com.stu.service.edu.service.CourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author stu
 * @since 2022-05-05
 */
@RestController
@RequestMapping("/admin/edu/course")
//@CrossOrigin
public class CourseController {

    @Autowired
    private CourseService courseService;

    /***********************************
     * 用途说明:更新课程基本信息和课程简介
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @PostMapping("updateCourseForm")
    private R updateCourseForm(@RequestBody CourseInfoForm courseInfoForm) {

        //非空判断
        if (null == courseInfoForm || StringUtils.isEmpty(courseInfoForm.getId())) {
            return R.error().message(ResultCodeEnum.PARAM_ERROR.getMessage());
        }
        //更新课程进步信息和课程简介
        boolean updateCourseForm = courseService.updateCourseForm(courseInfoForm);
        if (updateCourseForm) {
            return R.ok();
        } else {
            return R.error().message(ResultCodeEnum.UPDATE_ERROR.getMessage());
        }

    }

    /***********************************
     * 用途说明:保存课程基本信息和课程简介
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @PostMapping("saveCourseInfo")
    private R saveCourseInfo(@RequestBody CourseInfoForm courseInfoForm) {
        return R.ok().data("data", courseService.saveCourseInfo(courseInfoForm));
    }

    /***********************************
     * 用途说明:取得课程的基本信息和课程简介
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @GetMapping("getCourseForm/{courseId}")
    private R getCourseForm(@PathVariable(required = true) String courseId) {

        if (StringUtils.isEmpty(courseId)) {
            return R.error().message(ResultCodeEnum.PARAM_ERROR.getMessage());
        }
        CourseInfoForm courseInfoForm = courseService.getCourseForm(courseId);
        if (null == courseInfoForm) {
            return R.error().message(ResultCodeEnum.DATA_NULL.getMessage());
        } else {
            return R.ok().data("data", courseService.getCourseForm(courseId));
        }

    }

    /***********************************
     * 用途说明:去看发布课程的详情
     * @param courseId
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @GetMapping("getPublishCourseByid/{courseId}")
    public R getPublishCourseByid(@PathVariable String courseId) {
        CoursePublishVo coursePublish = courseService.getCoursePublishById(courseId);
        if(null != coursePublish){
            return R.ok().data("data",coursePublish);
        }
        return R.error().message(ResultCodeEnum.DATA_NULL.getMessage());
    }

    /***********************************
     * 用途说明:发布课程
     * @param courseId
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @GetMapping("publishCourse/{courseId}")
    public R publishCourse(@PathVariable String courseId) {
        boolean result = courseService.publishCourse(courseId);
        if (result) {
            return R.ok();
        }
        return R.error().message(ResultCodeEnum.UPDATE_ERROR.getMessage());
    }

    /***********************************
     * 用途说明:分页
     * @param page
     * @param limit
     * @param courseQueryVo
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @GetMapping("pageCourses/{page}/{limit}")
    public R pageCourses(@PathVariable Long page, @PathVariable Long limit, CourseQueryVo courseQueryVo) {
        IPage<CourseVo> coursePublishVoIPage = courseService.pageCourses(page, limit, courseQueryVo);

        return R.ok().data("data",coursePublishVoIPage);

    }

    /***********************************
     * 用途说明:根據id刪除課程(包括课时,小节,详情等)
     * @param id
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @DeleteMapping("deleteById/{id}")
    public R deleteById(@PathVariable String id) {
        boolean result = courseService.deleteById(id);
        if (result) {
            return R.ok();
        }
        return R.error().message(ResultCodeEnum.UPDATE_ERROR.getMessage());
    }



}

service接口

package com.stu.service.edu.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.service.base.dto.CourseDto;
import com.stu.service.edu.entity.Course;
import com.baomidou.mybatisplus.extension.service.IService;
import com.stu.service.edu.entity.form.CourseInfoForm;
import com.stu.service.edu.entity.vo.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务类
 * </p>
 *
 * @author stu
 * @since 2022-05-05
 */
public interface CourseService extends IService<Course> {

    /***********************************
     * 用途说明:保存课程基本信息和课程简介
     * 返回值说明: com.stu.service.edu.entity.Course
     ***********************************/
    Course saveCourseInfo(CourseInfoForm courseInfoForm);

    /***********************************
     * 用途说明:取得课程的基本信息和课程简介
     * 返回值说明: com.stu.service.edu.entity.form.CourseInfoForm
     ***********************************/
    CourseInfoForm getCourseForm(String id);

    /***********************************
     * 用途说明:更新课程基本信息和课程简介
     * 返回值说明: boolean
     ***********************************/
    boolean updateCourseForm(CourseInfoForm courseInfoForm);

    /***********************************
     * 用途说明:查询课程发布信息
     * @param courseId
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.CoursePublishVo
     ***********************************/
    CoursePublishVo getCoursePublishById(String courseId);

    /***********************************
     * 用途说明:发布课程
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
    boolean publishCourse(String id);

    /***********************************
     * 用途说明:分页
     * @param page
     * @param limit
     * @param courseQueryVo
     * 返回值说明:
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.stu.service.edu.entity.vo.CoursePublishVo>
     ***********************************/
    IPage<CourseVo> pageCourses(Long page, Long limit, CourseQueryVo courseQueryVo);


    /***********************************
     * 用途说明:根据课程id删除课程(章节,详情,视频都需要删除)
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
   boolean deleteById(String id);

   /***********************************
    * 用途说明:取得热门课程
    * 返回值说明:
    * @return java.util.List<com.stu.service.edu.entity.Course>
    ***********************************/
   List<Course> listHotCourses();

   /***********************************
    * 用途说明:根据讲师id查询所有课程
    * @param id
    * 返回值说明:
    * @return java.util.List<com.stu.service.edu.entity.Course>
    ***********************************/
   List<Course> listCourseByTeacherId(String id);

    /***********************************
     * 用途说明:前端课程分页nuxt
     * @param pageParam
     * @param courseQueryVo
     * 返回值说明:
     * @return java.util.Map<java.lang.String, java.lang.Object>
     ***********************************/
    Map<String,Object> listPageCourses(Page<Course> pageParam, CourseQueryVo courseQueryVo);

    /***********************************
     * 用途说明:根据课程id查询详情nuxt
     * @param id
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.ApiCourseVo
     ***********************************/
    ApiCourseVo getApiCourseById(String id);

    /***********************************
     * 用途说明:更新游览数
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
    boolean updateViewCount(String id);

    /***********************************
     * 用途说明:根据课程id查询订单相关的课程信息
     * @param id
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.CourseApiVo
     ***********************************/
    CourseDto getCourseById(String id);

    /***********************************
     * 用途说明:更新課程銷售量
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
    boolean  updateBuyCountById(String id);
}

service实现类

package com.stu.service.edu.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stu.service.base.dto.CourseDto;
import com.stu.service.base.exception.CustomException;
import com.stu.service.base.result.ResultCodeEnum;
import com.stu.service.edu.entity.Chapter;
import com.stu.service.edu.entity.Course;
import com.stu.service.edu.entity.CourseDescription;
import com.stu.service.edu.entity.constant.CourseConstant;
import com.stu.service.edu.entity.form.CourseInfoForm;
import com.stu.service.edu.entity.vo.ApiCourseVo;
import com.stu.service.edu.entity.vo.CoursePublishVo;
import com.stu.service.edu.entity.vo.CourseQueryVo;
import com.stu.service.edu.entity.vo.CourseVo;
import com.stu.service.edu.mapper.CourseMapper;
import com.stu.service.edu.service.ChapterService;
import com.stu.service.edu.service.CourseDescriptionService;
import com.stu.service.edu.service.CourseService;
import com.stu.service.edu.service.VideoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author stu
 * @since 2022-05-05
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionService courseDescriptionService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private ChapterService chapterService;

    /***********************************
     * 用途说明:保存课程基本信息和课程简介
     * 返回值说明: com.stu.service.edu.entity.Course
     ***********************************/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Course saveCourseInfo(CourseInfoForm courseInfoForm) {

        //保存课程基本信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        course.setStatus(CourseConstant.STATUS_DRAFT);//未发布
        baseMapper.insert(course);

        //保存课程简介
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        //设置课程和描述是一对一的关系,即课程id和描述id相等。
        //EduCourseDescription实体类主键生成策略改为input。
        courseDescription.setId(course.getId());
        courseDescriptionService.save(courseDescription);

        return course;
    }

    /***********************************
     * 用途说明:取得课程的基本信息和课程简介
     * 返回值说明: com.stu.service.edu.entity.form.CourseInfoForm
     ***********************************/
    @Override
    public CourseInfoForm getCourseForm(String id) {
        return baseMapper.getCourseForm(id);
    }

    /***********************************
     * 用途说明:更新课程基本信息和课程简介
     * 返回值说明: boolean
     ***********************************/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCourseForm(CourseInfoForm courseInfoForm) {
        //课程基本信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        int countUpdate = baseMapper.updateById(course);

        //课程简介
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(course.getId());
        courseDescription.setDescription(courseInfoForm.getDescription());

        boolean countUpdateDescriptiong = courseDescriptionService.updateById(courseDescription);

        return (countUpdate > 0 && countUpdateDescriptiong);
    }

    /***********************************
     * 用途说明:
     * @param courseId
     * 返回值说明:查询课程发布信息
     * @return com.stu.service.edu.entity.vo.CoursePublishVo
     ***********************************/
    @Override
    public CoursePublishVo getCoursePublishById(String courseId) {
        return baseMapper.getCoursePublishById(courseId);
    }

    @Override
    public boolean publishCourse(String id) {
        Course course = new Course();
        course.setId(id);
        course.setStatus(CourseConstant.STATUS_NORMAL);
        return baseMapper.updateById(course) > 0;
    }

    /***********************************
     * 用途说明:课程分页
     * @param page
     * @param limit
     * @param courseQueryVo
     * 返回值说明:
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.stu.service.edu.entity.vo.CoursePublishVo>
     ***********************************/
    @Override
    public IPage<CourseVo> pageCourses(Long page, Long limit, CourseQueryVo courseQueryVo) {

        QueryWrapper<CourseVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("t1.gmt_modified").orderByDesc("t1.id");

        String title = courseQueryVo.getTitle();

        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("t1.title", title);
        }
        Page<CourseVo> pageParam = new Page<>(page, limit);
        List<CourseVo> coursePublishVos = baseMapper.pageCourses(pageParam, queryWrapper);
        pageParam.setRecords(coursePublishVos);
        return pageParam;
    }

    /***********************************
     * 用途说明:根據id刪除課程(包括课时,小节,详情等)
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(String id) {
        boolean result = false;
        //删除video课时
        boolean videoResult = videoService.removeVideoByCourseId(id);
        //删除description课程详情
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<Chapter>();
        chapterQueryWrapper.eq("course_id", id);
        boolean chapterResult = chapterService.remove(chapterQueryWrapper);

        boolean desResult = courseDescriptionService.removeById(id);

        //删除course课程
        int courseResult = baseMapper.deleteById(id);
        if (videoResult && chapterResult && courseResult > 0) {
            return true;
        } else {
            result = false;
            throw new CustomException(ResultCodeEnum.UPDATE_ERROR);


        }

    }

    /***********************************
     * 用途说明:根据游览数量取得热门课程
     * 返回值说明:
     * @return java.util.List<com.stu.service.edu.entity.Course>
     ***********************************/
    @Cacheable(value = "index", key = "'listHotCourses'")
    @Override
    public List<Course> listHotCourses() {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("view_count");
        queryWrapper.last("limit 8");
        return baseMapper.selectList(queryWrapper);
    }

    /***********************************
     * 用途说明:根据讲师id查询所有课程
     * @param id
     * 返回值说明:
     * @return java.util.List<com.stu.service.edu.entity.Course>
     ***********************************/
    @Override
    public List<Course> listCourseByTeacherId(String id) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_modified");
        queryWrapper.eq("teacher_id", id);
        return baseMapper.selectList(queryWrapper);
    }

    /***********************************
     * 用途说明:前端课程分页nuxt
     * @param pageParam
     * @param courseQueryVo
     * 返回值说明:
     * @return java.util.Map<java.lang.String, java.lang.Object>
     ***********************************/
    @Override
    public Map<String, Object> listPageCourses(Page<Course> pageParam, CourseQueryVo courseQueryVo) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        if (null != courseQueryVo) {
            String subjectParentId = courseQueryVo.getSubjectParentId();
            String subjectId = courseQueryVo.getSubjectId();
            //"销量排序"
            String buyCountSort = courseQueryVo.getBuyCountSort();
            //"最新时间排序"
            String gmtCreateSort = courseQueryVo.getGmtCreateSort();
            //"价格排序"
            String priceSort = courseQueryVo.getPriceSort();

            if (StringUtils.isNotEmpty(subjectParentId)) {
                queryWrapper.eq("subject_parent_id", subjectParentId);
            }
            if (StringUtils.isNotEmpty(subjectId)) {
                queryWrapper.eq("subject_id", subjectId);
            }
            if (StringUtils.isNotEmpty(buyCountSort)) {
                queryWrapper.orderByDesc("buy_count");
            }
            if (StringUtils.isNotEmpty(gmtCreateSort)) {
                queryWrapper.orderByDesc("gmt_create");
            }
            if (StringUtils.isNotEmpty(priceSort)) {
                queryWrapper.orderByDesc("price");
            }
        }
        baseMapper.selectPage(pageParam, queryWrapper);
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("items", pageParam.getRecords());//当前页记录
        mapParam.put("current", pageParam.getCurrent());//当前页
        mapParam.put("pages", pageParam.getPages());//共有多少页
        mapParam.put("size", pageParam.getSize());//每页的记录数
        mapParam.put("total", pageParam.getTotal());//总记录数
        mapParam.put("hasNext", pageParam.hasNext());//是否有上一页
        mapParam.put("hasPrevious", pageParam.hasPrevious());//是否有下一页
        return mapParam;
    }

    /***********************************
     * 用途说明:根据课程id查询详情nuxt
     * @param id
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.ApiCourseVo
     ***********************************/
    @Override
    public ApiCourseVo getApiCourseById(String id) {
        this.updateViewCount(id);
        return baseMapper.getApiCourseById(id);
    }

    /***********************************
     * 用途说明:更新游览数
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
    @Override
    public boolean updateViewCount(String id) {
        Course course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        return baseMapper.updateById(course) > 0;
    }

    /***********************************
     * 用途说明:根据课程id查询订单相关的课程信息
     * @param id
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.CourseApiVo
     ***********************************/
    @Override
    public CourseDto getCourseById(String id) {
        return baseMapper.getCourseById(id);
    }

    /***********************************
     * 用途说明:更新課程銷售量
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
    @Override
    public boolean updateBuyCountById(String id) {
        Course course = baseMapper.selectById(id);
        course.setBuyCount(course.getBuyCount() + 1);
        return baseMapper.updateById(course) > 0;


    }
}

mapper文件

注意@Param(Constants.WRAPPER)这里

package com.stu.service.edu.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.service.edu.entity.Course;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.stu.service.edu.entity.form.CourseInfoForm;
import com.stu.service.edu.entity.vo.ApiCourseVo;
import com.stu.service.base.dto.CourseDto;
import com.stu.service.edu.entity.vo.CoursePublishVo;
import com.stu.service.edu.entity.vo.CourseVo;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * <p>
 * 课程 Mapper 接口
 * </p>
 *
 * @author stu
 * @since 2022-05-05
 */
public interface CourseMapper extends BaseMapper<Course> {

    /***********************************
     * 用途说明:取得课程的基本信息和课程简介
     * @param id
     * 返回值说明:
     * @return com.stu.service.edu.entity.form.CourseInfoForm
     ***********************************/
    CourseInfoForm getCourseForm(String id);

    /***********************************
     * 用途说明:查询发布课程信息
     * @param courseId
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.CoursePublishVo
     ***********************************/
    CoursePublishVo getCoursePublishById(String courseId);

    /***********************************
     * 用途说明:课程列表
     * @param pageParam
     * @param queryWrapper
     * 返回值说明:
     * @return java.util.List<com.stu.service.edu.entity.vo.CoursePublishVo>
     ***********************************/
    List<CourseVo> pageCourses(Page<CourseVo> pageParam, @Param(Constants.WRAPPER)QueryWrapper<CourseVo> queryWrapper);


    /***********************************
     * 用途说明:根据课程id查询详情nuxt
     * @param id
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.ApiCourseVo
     ***********************************/
    ApiCourseVo getApiCourseById(String id);

    /***********************************
     * 用途说明:根据课程id查询订单相关的课程信息
     * @param id
     * 返回值说明:
     * @return com.stu.service.edu.entity.vo.CourseApiVo
     ***********************************/
    CourseDto getCourseById(String id);

}

xml文件

注意${ew.customSqlSegment}这里

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.stu.service.edu.mapper.CourseMapper">
    <resultMap id="baseBesultMap" type="com.stu.service.edu.entity.form.CourseInfoForm">
        <id column="id" property="id"/>
        <result column="teacher_id" property="teacherId"/>
        <result column="subject_id" property="subjectId"/>
        <result column="subject_parent_id" property="subjectParentId"/>
        <result column="title" property="title"/>
        <result column="price" property="price"/>
        <result column="lesson_num" property="lessonNum"/>
        <result column="cover" property="cover"/>
        <result column="description" property="description"/>
    </resultMap>

    <select id="getCourseForm" resultMap="baseBesultMap">
        SELECT t1.id,
               t1.teacher_id,
               t1.subject_id,
               t1.subject_parent_id,
               t1.title,
               t1.price,
               t1.lesson_num,
               t1.cover,
               t2.description
        FROM edu_course t1
                 LEFT JOIN edu_course_description t2 ON t1.id = t2.id
        WHERE t1.id = #{id}
    </select>
    <select id="getCoursePublishById" parameterType="java.lang.String"
            resultType="com.stu.service.edu.entity.vo.CoursePublishVo">
        SELECT t1.id,
               t1.title,
               t1.price,
               t1.cover,
               t1.lesson_num,
               td.description,
               t3.title AS subjectLevelOne,
               t4.title AS subjectLevelTwo,
               t2.NAME  AS teacherName,
               t3.id,
               t1.subject_id,
               t4.parent_id
        FROM edu_course t1
                 LEFT JOIN edu_course_description td ON td.id = t1.id
                 LEFT JOIN edu_teacher t2 ON t2.id = t1.teacher_id
                 LEFT JOIN edu_subject t3 ON t3.id = t1.subject_parent_id
                 LEFT JOIN edu_subject t4 ON t4.id = t1.subject_id
        WHERE t1.id = #{courseId}
    </select>

    <!--课程分页-->
    <select id="pageCourses" resultType="com.stu.service.edu.entity.vo.CourseVo">
        SELECT t1.id,
               t1.title,
               t1.cover,
               t1.lesson_num   AS lessonNum,
               t1.price,
               t1.buy_count    AS buyCount,
               t1.view_count   AS viewCount,
               t1.`status`,
               t1.gmt_create   AS gmtCreate,
               t1.gmt_modified AS gmtModified,
               t3.title        AS subjectParentTitle,
               t4.title        AS subjectTitle,
               t2.NAME         AS teacherName,
               td.description
        FROM edu_course t1
                 LEFT JOIN edu_course_description td ON td.id = t1.id
                 LEFT JOIN edu_teacher t2 ON t2.id = t1.teacher_id
                 LEFT JOIN edu_subject t3 ON t3.id = t1.subject_parent_id
                 LEFT JOIN edu_subject t4 ON t4.id = t1.subject_id
            ${ew.customSqlSegment}
    </select>
    <!--课程详情-->
    <select id="getApiCourseById" parameterType="java.lang.String"
            resultType="com.stu.service.edu.entity.vo.ApiCourseVo">
        SELECT
            t1.id,
            t1.title,
            t1.price,
            t1.cover,
            t1.lesson_num,
            t1.buy_count,
            t1.view_count,
            t1.STATUS,
            t1.subject_parent_id AS subjectParentId,
            t1.subject_id AS subjectId,
            td.description,
            t2.intro,
            t2.avatar,
            t2.id AS teacherId,
            t3.title AS subjectParentTitle,
            t4.title AS subjectTitle,
            t2.NAME AS teacherName
        FROM
            edu_course t1
        LEFT JOIN edu_course_description td ON td.id = t1.id
        LEFT JOIN edu_teacher t2 ON t2.id = t1.teacher_id
        LEFT JOIN edu_subject t3 ON t3.id = t1.subject_parent_id
        LEFT JOIN edu_subject t4 ON t4.id = t1.subject_id
        WHERE
            t1.id = #{id}
    </select>

    <select id="getCourseById" resultType="com.stu.service.base.dto.CourseDto">
        SELECT
            t1.id,
            t1.title,
            t1.price,
            t1.cover,
            t2.NAME AS teacherName
        FROM
            edu_course t1
        LEFT JOIN edu_teacher t2
        ON t2.id = t1.teacher_id
        WHERE
            t1.id = #{id}
    </select>

</mapper>

vue

vue.js

import request from '@/utils/request'

export default {
    //保存课程基本信息和课程简介
    saveCourseInfo(course) {
        return request({
            url: '/admin/edu/course/saveCourseInfo',
            method: 'post',
            data: course
        })
    },
    //取得课程基本信息和课程简介
    getCourseForm(courseId) {
        return request({
            url: `/admin/edu/course/getCourseForm/${courseId}`,
            method: 'get'
        })

    },
    //更新课程基本信息和课程简介
    updateCourseForm(courseForm) {
        return request({
            url: '/admin/edu/course/updateCourseForm',
            method: 'post',
            data: courseForm
        })
    },
    //课程列表分页
    pageCourses(page, limit, searchData) {
        return request({
            url: `/admin/edu/course/pageCourses/${page}/${limit}`,
            method: 'get',
            params: searchData
        })
    },
    //取得课程基本信息和课程简介
    deleteById(courseId) {
        return request({
            url: `/admin/edu/course/deleteById/${courseId}`,
            method: 'delete'
        })

    },
}

vue页面

<template>
  <div class="app-container">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="课程标题">
        <el-input
          v-model="searchData.title"
          placeholder="示例:Java基础课"
        ></el-input>
      </el-form-item>
      <el-form-item label="课程类别">
        <el-select
          v-model="searchData.subjectLevelOne"
          placeholder="一级分类"
          @change="getTwoSubjectList"
        >
          <el-option
            v-for="info in subjectLevelOneList"
            :key="info.id"
            :label="info.title"
            :value="info.id"
          >
          </el-option>
        </el-select>
        <el-select v-model="searchData.subjectLevelTwo" placeholder="二级分类">
          <el-option
            v-for="info in subjectLevelTwoList"
            :key="info.id"
            :label="info.title"
            :value="info.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!--课程讲师ID-->
      <el-form-item label="课程讲师">
        <el-select v-model="searchData.teacherId">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="getList()"
        >查询</el-button
      >
      <el-button type="default" @click="resetData()">清空</el-button>
    </el-form>

    <el-table :data="pageList" border>
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="封面" width="200" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.cover" alt="scope.row.title" width="100%" />
        </template>
      </el-table-column>
      <el-table-column label="课程信息" align="center">
        <template slot-scope="scope">
          <p>
            标题:<a href="">{{ scope.row.title }}</a>
          </p>
          <p>一级分类:{{ scope.row.subjectParentTitle }}</p>
          <p>二级分类: {{ scope.row.subjectTitle }}</p>

          <p>
            课时:{{ scope.row.lessonNum }} 游览:{{
              scope.row.viewCount
            }}
            付费学员:{{ scope.row.buyCount }}
          </p>
        </template>
      </el-table-column>

      <el-table-column label="讲师" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.teacherName }}
        </template>
      </el-table-column>
      <el-table-column label="价格" width="100" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="Number(scope.row.price) === 0"
            >免费</el-tag
          >
          <el-tag v-else>{{ scope.row.price }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="课程状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 'Draft' ? 'warning' : 'success'">
            {{ scope.row.status === "Draft" ? "未发布" : "已发布" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.gmtCreate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <router-link :to="'/course/editCourse/' + scope.row.id">
            <el-button type="primary" size="mini" icon="el-icon-edit" v-if="hasPerm('course.update')"
              >修改</el-button
            >
          </router-link>
          <router-link :to="'/course/editChapter/' + scope.row.id">
            <el-button type="primary" size="mini" icon="el-icon-edit" v-if="hasPerm('chapter.update')"
              >编辑大纲</el-button
            >
          </router-link>

          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="deleteById(scope.row.id)" 
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      :page-sizes="[5, 10, 15, 20]"
      style="padding: 12px 8px; text-align: center"
      layout="sizes, prev, pager, next, jumper, ->, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script>
import courseApi from "@/api/course";
import teacherApi from "@/api/teacher";
import subjectApi from "@/api/subject";

export default {
  data() {
    return {
      pageList: [],
      total: 0,
      limit: 5,
      page: 1,
      searchData: {
        title: "",
        teacherId: "",
        subjectLevelOne: "",
        subjectLevelTwo: "",
      },
      teacherList: [],
      subjectLevelOneList: [],
      subjectLevelTwoList: [],
    };
  },
  created() {
    this.init();
  },
  methods: {
    //删除
    deleteById(courseId) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除api
          courseApi.deleteById(courseId).then((res) => {
            if (res.code === 20000) {
              this.$message({
                type: "info",
                message: "刪除成功: ",
              });
            } else {
              this.$message({
                type: "info",
                message: "刪除失败: ",
              });
            }
            this.pageCourses();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    init() {
      this.getAllSubject();
      this.getTeacher();
      this.pageCourses();
    },
    //分页
    pageCourses() {
      courseApi
        .pageCourses(this.page, this.limit, this.searchData)
        .then((res) => {
          
          if (res.code === 20000) {
            if (res.data.data.records) {
              this.pageList = res.data.data.records;
            }
            if (res.data.data.total) {
              this.total = res.data.data.total;
            }
          }
        });
    },
    //改变数量
    handleSizeChange(size) {
      this.limit = size;
      this.pageCourses();
    },
    //改变页码
    handleCurrentChange(page) {
      this.page = page;
      this.pageCourses();
    },
    getTeacher() {
      teacherApi.listAllTeachers().then((res) => {
        if (res.code === 20000 && res.data.list) {
          this.teacherList = res.data.list;
        }
      });
    },
    getAllSubject() {
      subjectApi.treeList().then((res) => {
        if (res.code === 20000 && res.data.treeList) {
          this.subjectLevelOneList = res.data.treeList;
        }
      });
    },
    //点击一级分类,显示二级分类
    getTwoSubjectList(value) {
      //选中一级分类,在改变一级分类,二级分类显示的数据没有清空的问题
      // this.searchData.subjectLevelTwo = ''

      let tempOneSbujectList = this.subjectLevelOneList.filter(
        (item) => item.id === value && item.id
      );
      this.subjectLevelTwoList = tempOneSbujectList[0].childList;

      if (
        !this.subjectLevelTwoList.includes(this.searchData.subjectLevelTwo) &&
        this.searchData.subjectLevelTwo
      ) {
        this.searchData.subjectLevelTwo = "";
      }
    },
    //清空查询条件
    resetData() {
      this.searchData = {};
    },
  },
};
</script>
>

4、方式3

contrller直接通过调用封装的page接口,不涉及serv,mapper,sql

controller

package com.stu.service.acl.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.service.acl.entity.Role;
import com.stu.service.acl.service.RoleService;
import com.stu.service.base.result.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author stu
 * @since 2022-08-16
 */
@RestController
@RequestMapping("/admin/acl/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /***********************************
     * 用途说明:删除角色
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @DeleteMapping("deleteRole/{id}")
    public R deleteRole(@PathVariable String id) {

        /*        if (true) {
            throw new CustomException(ResultCodeEnum.DIVIDE_ZERO);
        }*/

        boolean result = roleService.removeById(id);
        if (result) {
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    /***********************************
     * 用途说明:修改角色
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @PostMapping("updateRole")
    public R updateRole(@RequestBody Role role) {
        boolean result = roleService.updateById(role);
        if (result) {
            return R.ok().message("更新成功");
        }
        return R.error().message("更新失败");
    }

    /***********************************
     * 用途说明:添加角色
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @ApiOperation("添加角色")
    @PostMapping("addRole")
    public R addRole(@ApiParam("角色对象") @RequestBody Role role) {
        boolean result = roleService.save(role);
        if (result) {
            return R.ok().message("保存成功");
        }
        return R.error().message("保存失败");
    }

    /***********************************
     * 用途说明:查询角色表所有数据
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @GetMapping("findAll")
    public R findAllRole() {
        List<Role> list = roleService.list();
        return R.ok().data("list", list);
    }

    /***********************************
     * 用途说明:查询
     * 返回值说明: com.stu.service.edu.entity.Role
     ***********************************/
    @GetMapping("get/{id}")
    public R getRole(@PathVariable String id) {

        return R.ok().data("dataInfo", roleService.getById(id));

    }

    /***********************************
     * 用途说明:查询角色表所有数据
     * 返回值说明: com.stu.service.base.result.R
     ***********************************/
    @GetMapping("pageList/{page}/{limit}")
    public R pageList(@PathVariable long page, @PathVariable long limit, Role role) {
        Page<Role> pageParam = new Page<>(page, limit);

        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(role.getRoleName())) {
            queryWrapper.like("role_name", role.getRoleName());
        }
        roleService.page(pageParam, queryWrapper);
        Map<String, Object> map = new HashMap<String, Object>();
        long total = pageParam.getTotal();
        List<Role> list = pageParam.getRecords();
        map.put("total", total);
        map.put("list", list);
        return R.ok().data(map);

    }

}

vue

vue.js

import request from '@/utils/request'
const apiName = '/admin/acl/role';

export default {
    pageList(page, limit, Role) {
        return request({
            url: `${apiName}/pageList/${page}/${limit}`,
            method: 'get',
            params: Role
        })
    },
    removeById(id) {
        return request({
            url: `${apiName}/deleteRole/${id}`,
            method: 'delete'
        })
    },
    save(role) {
        return request({
            url: `${apiName}/addRole`,
            method: 'post',
            data: role
        })
    },
    //角色详情
    getDetail(id) {
        return request({
            url: `${apiName}/get/${id}`,
            method: 'get'
        })
    },
    update(role) {
        return request({
            url: `${apiName}/updateRole`,
            method: 'post',
            data: role
        })
    },

    //取得角色的集合
    listAllRoles() {
        return request({
            url: '${apiName}/findAll',
            method: 'get'
        })
    },
}

vue页面

<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchData.name" placeholder="讲师" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="pageList()"
          >查询</el-button
        >
        <el-button type="default" @click="resetData()">清空</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-button type="danger" size="mini" @click="add()">添加</el-button>
      <el-button type="danger" size="mini" @click="batchRemove()"
        >批量删除</el-button
      >
    </div>
    <!-- 表格 -->
    <el-table
      :data="list"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column label="ID" width="50">
        <!-- 使用连续的序号 -->
        <template slot-scope="scope">
          {{ (currentPage - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="名称" width="150" />

      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <router-link :to="'/acl/role/distribution/' + scope.row.id">
            <el-button type="info" size="mini" icon="el-icon-info"></el-button
          ></router-link>
          <router-link :to="'/acl/role/update/' + scope.row.id">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
            ></el-button
          ></router-link>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeById(scope.row)"></el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :current-page="currentPage"
      :page-size="limit"
      :total="total"
      :page-sizes="[5, 10, 15, 20]"
      style="padding: 12px 8px; text-align: center"
      layout="sizes, prev, pager, next, jumper, ->, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
 

<script>
import roleApi from "@/api/acl/role";
export default {
  data() {
    return {
      list: [], //列表数据
      total: 0,
      currentPage: 1, //当前页
      limit: 10, //每页记录数
      searchData: {},
      idList: null,
    };
  },
  created() {
    this.pageList();
  },
  methods: {
    //跳转到修改页面
    add() {
      this.$router.push({ path: `/acl/role/form/` });
    },
    //批量删除
    batchRemove() {
     
      if (!this.idList || this.idList.length <= 0) {
        this.$message({
          type: "info",
          message: "请先选择要删除的数据!",
        });
        return false;
      }
      let arrayIds = [];
      this.idList.forEach((element) => {
        arrayIds.push(element.id);
      });

      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除api
          roleApi.batchRemove(arrayIds).then((res) => {
            if (res.code === 20000 && res.data) {
              this.$message({
                type: "info",
                message: "刪除成功: ",
              });
              this.pageList();
            } else {
              this.$message({
                type: "info",
                message: "刪除失败: ",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //多选
    handleSelectionChange(idList) {
      this.idList = idList;
    },
    //删除
    removeById(data) {
      this.$confirm("此操作将永久删除" + data.name + ", 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除api
          roleApi.removeById(data.id).then((res) => {
            if (res.code === 20000 && res.data) {
              this.$message({
                type: "info",
                message: "刪除成功: ",
              });
              this.pageList();
            } else {
              this.$message({
                type: "info",
                message: "刪除失败: ",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    resetData() {
      this.searchData = {};
      this.pageList();
    },
    //改变数量
    handleSizeChange(size) {
      this.limit = size;
      this.pageList();
    },
    //改变页码
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.pageList();
    },

    //分页查询
    pageList() {
      roleApi
        .pageList(this.currentPage, this.limit, this.searchData)
        .then((res) => {
          
          if (res.code === 20000 && res.data) {
            this.$message({
              type: "info",
              message: "查询成功: ",
            });
            this.list = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message({
              type: "info",
              message: "查询失败: ",
            });
          }
        })
        .catch((e) => {
          this.$message({
            type: "info",
            message: "查询异常",
          });
        });
    },
  },
};
</script>
作者:
出处:https://www.cnblogs.com/konglxblog//
版权:本文版权归作者和博客园共有
转载:欢迎转载,文章中请给出原文连接,此文章仅为个人知识学习分享,否则必究法律责任