vue springboot mybatis plus 分页
方式一,自定义sql语句分页
1、pom依赖版本
<mybatis-plus.version>3.4.0</mybatis-plus.version>
2、MyBatisPlusConfig
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; } }
3、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()); } }
4、service接口
package com.stu.service.edu.service; import com.baomidou.mybatisplus.core.metadata.IPage; 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.CoursePublishVo; import com.stu.service.edu.entity.vo.CourseQueryVo; import com.stu.service.edu.entity.vo.CourseVo; /** * <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); }
5、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.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.Video; import com.stu.service.edu.entity.constant.CourseConstant; 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.mapper.ChapterMapper; import com.stu.service.edu.mapper.CourseDescriptionMapper; import com.stu.service.edu.mapper.CourseMapper; import com.stu.service.edu.mapper.VideoMapper; import com.stu.service.edu.service.ChapterService; import com.stu.service.edu.service.CourseDescriptionService; import com.stu.service.edu.service.CourseService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 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.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * <p> * 课程 服务实现类 * </p> * * @author stu * @since 2022-05-05 */ @Service public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService { @Autowired private CourseDescriptionService courseDescriptionService; @Autowired private VideoMapper videoMapper; @Autowired private ChapterMapper chapterMapper; @Autowired private CourseDescriptionMapper descriptionMapper; @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.orderByAsc("t1.gmt_modified"); 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课时 QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>(); videoQueryWrapper.eq("course_id", id); boolean videoResult = videoService.remove(videoQueryWrapper); //删除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){ result = true; } return result; } }
6、mapper接口
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.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); }
7、mapper的xml文件
<?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> </mapper>
8、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 }) }, }
9、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" >修改</el-button > </router-link> <router-link :to="'/course/editChapter/' + scope.row.id"> <el-button type="primary" size="mini" icon="el-icon-edit" >编辑大纲</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: 3, page: 1, searchData: { title: "", teacherId: "", subjectLevelOne: "", subjectLevelTwo: "", }, teacherList: [], subjectLevelOneList: [], subjectLevelTwoList: [], }; }, created() { this.init(); }, methods: { //删除 deleteById(){ }, init() { this.getAllSubject(); this.getTeacher(); this.pageCourses(); }, //分页 pageCourses() { courseApi .pageCourses(this.page, this.limit, this.searchData) .then((res) => { debugger 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> >
方式二、不是自定义的
1、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.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, ChapterVo.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); } }
2、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; /** * <p> * 讲师 服务类 * </p> * * @author stu * @since 2022-04-11 */ public interface TeacherService extends IService<Teacher> { /** * 分页 * @param pageParam * @param teacherQueryVo */ IPage<Teacher> listPage(Page<Teacher> pageParam, ChapterVo.TeacherQueryVo teacherQueryVo); }
3、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.stu.service.edu.entity.Teacher; import com.stu.service.edu.entity.vo.ChapterVo; import com.stu.service.edu.mapper.TeacherMapper; import com.stu.service.edu.service.TeacherService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * <p> * 讲师 服务实现类 * </p> * * @author stu * @since 2022-04-11 */ @Service public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService { @Autowired private TeacherService teacherService; @Override public IPage<Teacher> listPage(Page<Teacher> pageParam, ChapterVo.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); } }
4、mappper自带的接口(框架自带的,不用在TeacherMapper接口和xml里写自定义的接口和sql语句)
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package com.baomidou.mybatisplus.core.mapper; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; public interface BaseMapper<T> extends Mapper<T> { int insert(T entity); int deleteById(Serializable id); int deleteByMap(@Param("cm") Map<String, Object> columnMap); int delete(@Param("ew") Wrapper<T> wrapper); int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList); int updateById(@Param("et") T entity); int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper); T selectById(Serializable id); List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList); List<T> selectByMap(@Param("cm") Map<String, Object> columnMap); T selectOne(@Param("ew") Wrapper<T> queryWrapper); Integer selectCount(@Param("ew") Wrapper<T> queryWrapper); List<T> selectList(@Param("ew") Wrapper<T> queryWrapper); List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper); List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper); <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper); <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper); }
5、mapper接口
package com.stu.service.edu.mapper; import com.stu.service.edu.entity.Teacher; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * 讲师 Mapper 接口 * </p> * * @author stu * @since 2022-04-11 */ public interface TeacherMapper extends BaseMapper<Teacher> { }
6、vue和上边方式1一样处理
方式三、通过map封装
1、service接口(没有xml的sql,没有mapper的接口)
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); }
2、实现类
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; } }
3、controller
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; } }
4、vue页面
<template> <div id="aCoursesList" class="bg-fa of"> <!-- 讲师列表 开始 --> <section class="container"> <header class="comm-title all-teacher-title"> <h2 class="fl tac"> <span class="c-333">全部讲师</span> </h2> <section class="c-tab-title"> <a id="subjectAll" title="全部" href="#">全部</a> <!-- <c:forEach var="subject" items="${subjectList }"> <a id="${subject.subjectId}" title="${subject.subjectName }" href="javascript:void(0)" onclick="submitForm(${subject.subjectId})">${subject.subjectName }</a> </c:forEach>--> </section> </header> <section class="c-sort-box unBr"> <div> <!-- /无数据提示 开始--> <section class="no-data-wrap" v-if="data.total === 0"> <em class="icon30 no-data-ico"> </em> <span class="c-666 fsize14 ml10 vam" >没有相关数据,小编正在努力整理中...</span > </section> <!-- /无数据提示 结束--> <article class="i-teacher-list" v-if="data.total > 0"> <ul class="of"> <li v-for="item in data.items" :key="item.id"> <section class="i-teach-wrap"> <div class="i-teach-pic"> <a :href="'/teacher/' + item.id" :title="item.name" target="_blank" > <img :src="item.avatar" :alt="item.name" height="142" width="142" /> </a> </div> <div class="mt10 hLh30 txtOf tac"> <a :href="'/teacher/' + item.id" :title="item.name" target="_blank" class="fsize18 c-666" >姚晨</a > </div> <div class="hLh30 txtOf tac"> <span class="fsize14 c-999">{{ item.career }}</span> </div> <div class="mt15 i-q-txt"> <p class="c-999 f-fA">{{ item.intro }}</p> </div> </section> </li> </ul> <div class="clear"></div> </article> </div> <!-- 公共分页 开始 --> <div> <div class="paging"> <!-- undisable这个class是否存在,取决于数据属性hasPrevious --> <a :class="{ undisable: !data.hasPrevious }" href="#" title="首页" @click.prevent.prevent="listPage(1)" >首页</a > <a v-if="data.hasPrevious" href="#" title="前一页" @click.prevent="listPage(data.current - 1)" ><</a > <a v-else title="前一页"><</a> <a :class="{ current: data.current == page, undisable: data.current == page, }" v-for="page in data.pages" :key="page" :title="'第' + page + '页'" @click.prevent="listPage(page)" >{{ page }}</a > <a href="#" title="后一页" v-if="data.hasNext" @click="listPage(data.current + 1)" >></a > <a title="后一页" v-else>></a> <a href="#" title="末页" v-if="data.hasNext" @click="listPage(data.pages)" >末</a > <a v-else title="末页">末</a> <div class="clear"></div> </div> </div> <!-- 公共分页 结束 --> </section> </section> <!-- /讲师列表 结束 --> </div> </template> <script> import teacherApi from "@/api/teacher"; export default { data() { return { data: [] }; }, asyncData({ params, error }) { return teacherApi.listPageTeachers(1, 8).then((res) => { return { data: res.data.teacherList }; }); }, cretead() {}, methods: { listPage(page) { teacherApi.listPageTeachers(page, 8).then((res) => { if (res.code === 20000 && res.data.teacherList) { this.data = res.data.teacherList; } }); }, }, }; </script>
效果