SpringBoot2+Vue2实战(十二)springboot一对一,一对多查询

新建数据库表

Course

@Data
@TableName("t_course")
public class Course implements Serializable {private static final long serialVersionUID = 1L;/*** id*/@TableId(value = "id", type = IdType.AUTO)private Integer id;/*** 课程名称*/private String name;/*** 学分*/private Integer score;/*** 上课时间*/private String times;/*** 是否开课*/private Boolean state;/*** 授课老师id*/private Integer teacherId;}

CourseController 

@RestController
@RequestMapping("/course")
public class CourseController {@Resourceprivate CourseService courseService;//修改或增加@PostMapping("/saveCourse")public Result saveCourse(@RequestBody Course course) {//新增或修改return Result.success(courseService.saveOrUpdate(course));}@GetMapping("/findAll")public Result findAll() {return Result.success(courseService.list());}@DeleteMapping("/{id}")public Result delete(@PathVariable("id") Integer id) {return Result.success(courseService.removeById(id));}//批量删除@PostMapping("/del/batch")public Result deleteBatch(@RequestBody List<Integer> ids) {return Result.success(courseService.removeBatchByIds(ids));}//分页查询 mybatis-plus方式@GetMapping("/selectPage")public Result selectPage(@RequestParam(defaultValue = "") String name,@RequestParam Integer pageSize,@RequestParam Integer pageNum) {IPage<Course> page = new Page<>(pageNum, pageSize);QueryWrapper<Course> queryWrapper = new QueryWrapper<>();if (!"".equals(name)) {queryWrapper.like("name", name);}return Result.success(courseService.page(page, queryWrapper));}}

Course.vue

<template><div><div><div style="margin: 10px 0"><el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search"v-model="name"></el-input><el-button class="ml-5" type="primary" @click="load">搜索</el-button><el-button type="warning" @click="reset">重置</el-button></div><div style="margin: 10px 0"><el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button><el-popconfirmclass="ml-5"confirm-button-text='确定'cancel-button-text='我再想想'icon="el-icon-info"icon-color="red"title="您确定批量删除这些数据吗?"@confirm="delBatch"><el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button></el-popconfirm></div><el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"@selection-change="handleSelectionChange"><el-table-column type="selection" width="55"></el-table-column><el-table-column prop="id" label="ID" width="80"></el-table-column><el-table-column prop="name" label="课程名"></el-table-column><el-table-column prop="score" label="学分"></el-table-column><el-table-column prop="times" label="课时"></el-table-column><el-table-column prop="teacher" label="授课老师"></el-table-column><el-table-column label="启用"><template slot-scope="scope"><el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ccc"@change="changeEnable(scope.row)"></el-switch></template></el-table-column><el-table-column label="操作" width="200" align="center"><template slot-scope="scope"><el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button><el-popconfirmclass="ml-5"confirm-button-text='确定'cancel-button-text='我再想想'icon="el-icon-info"icon-color="red"title="您确定删除吗?"@confirm="del(scope.row.id)"><el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button></el-popconfirm></template></el-table-column></el-table><div style="padding: 10px 0"><el-pagination@size-change="handleSizeChange"@current-change="handleCurrentChange":current-page="pageNum":page-sizes="[2, 5, 10, 20]":page-size="pageSize"layout="total, sizes, prev, pager, next, jumper":total="total"></el-pagination></div><el-dialog title="课程信息" :visible.sync="dialogFormVisible" width="30%"><el-form label-width="80px" size="small"><el-form-item label="课程名"><el-input v-model="form.name" autocomplete="off"></el-input></el-form-item><el-form-item label="学分"><el-input v-model="form.score" autocomplete="off"></el-input></el-form-item><el-form-item label="课时"><el-input v-model="form.times" autocomplete="off"></el-input></el-form-item><el-form-item label="授课老师"><el-select clearable v-model="form.teacherId" placeholder="请选择" style="width: 100%"><el-option v-for="item in teachers" :key="item.id" :label="item.nickname" :value="item.id"></el-option></el-select></el-form-item></el-form><div slot="footer" class="dialog-footer"><el-button @click="dialogFormVisible = false">取 消</el-button><el-button type="primary" @click="save">确 定</el-button></div></el-dialog></div></div>
</template><script>
export default {name: "Course",data() {return {form: {},tableData: [],name: "",multipleSelection: [],pageNum: 1,pageSize: 5,total: 0,dialogFormVisible: false,teachers: [],user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}}}, created() {this.load()},methods: {//图片回显formatImg(value) {if (value) {return "<img src='" + value.substring(21) + "' style='hight:50px'>"} else {return null;}},load() {this.request.get("/course/selectPage", {params: {pageNum: this.pageNum,pageSize: this.pageSize,name: this.name}}).then(res => {//注意datathis.tableData = res.data.recordsthis.total = res.data.total})},changeEnable(row) {this.request.post("/course/update", row).then(res => {if (res.code === '200') {this.$message.success("更新成功")}})},del(id) {this.request.delete("/course/" + id).then(res => {if (res.code === '200') {this.$message.success("删除成功")this.load()} else {this.$message.error("删除失败")}})},save() {this.request.post("/course/saveCourse", this.form).then(res => {if (res.code === '200') {this.$message.success("保存成功")this.dialogFormVisible = falsethis.load()} else {this.$message.error("保存失败")}})},handleAdd() {this.dialogFormVisible = truethis.form = {}},handleEdit(row) {this.form = JSON.parse(JSON.stringify(row))this.dialogFormVisible = true},handleSelectionChange(val) {console.log(val)this.multipleSelection = val},delBatch() {let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]this.request.post("/course/del/batch", ids).then(res => {if (res.data) {this.$message.success("批量删除成功")this.load()} else {this.$message.error("批量删除失败")}})},reset() {this.name = ""this.load()},handleSizeChange(pageSize) {console.log(pageSize)this.pageSize = pageSizethis.load()},handleCurrentChange(pageNum) {console.log(pageNum)this.pageNum = pageNumthis.load()},handleFileUploadSuccess(res) {console.log(res)this.load()},download(url) {window.open(url)}}
}
</script><style></style>

插入数据

一、实现授课老师查询

(关联查询)

一对一

UserController

@GetMapping("/role/{role}")public Result findAllUserByRoleId(@PathVariable String role) {QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.eq("role", role);List<User> list = userService.list(queryWrapper);return success(list);}

Course.vue

load() {this.request.get("/course/selectPage", {params: {pageNum: this.pageNum,pageSize: this.pageSize,name: this.name}}).then(res => {//注意datathis.tableData = res.data.recordsthis.total = res.data.total})this.request.get("/user/role/ROLE_TEACHER").then(res => {//注意datathis.teachers = res.data})},

 Course

 @TableField(exist = false)private String teacher;
//睡一会
TimeUnit.SECONDS.sleep(20);

CourseController

第一种方法

//分页查询 mybatis-plus方式@GetMapping("/selectPage")public Result selectPage(@RequestParam(defaultValue = "") String name,@RequestParam Integer pageSize,@RequestParam Integer pageNum) {QueryWrapper<Course> queryWrapper = new QueryWrapper<>();queryWrapper.orderByDesc("id");Page<Course> page = courseService.page(new Page<>(pageNum, pageSize), queryWrapper);List<Course> records = page.getRecords();for (Course record : records) {User user = userService.getById(record.getTeacherId());if (user != null) {record.setTeacher(user.getNickname());}}return Result.success(page);}

第二种方法

CourseController

@GetMapping("/selectPage")public Result selectPage(@RequestParam String name,@RequestParam Integer pageSize,@RequestParam Integer pageNum) {Page<Course> page = courseService.findPage(new Page<>(pageNum, pageSize), name);return Result.success(page);}

CourseService

Page<Course> findPage(Page<Course> page, String name);

CourseServiceImpl

@Resourceprivate CourseMapper courseMapper;@Overridepublic Page<Course> findPage(Page<Course> page, String name) {return courseMapper.findPage(page,name);}

CourseMapper

Page<Course> findPage(Page<Course> page, @Param("name") String name);

CourseMapper.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.example.springboot.mapper.CourseMapper"><select id="findPage" resultType="com.example.springboot.entity.Course">select t_course.*,sys_user.nickname as teacherfrom t_courseleft join sys_useron t_course.teacher_id = sys_user.id<where><if test="name!=null and name !=''">and name like concat('%',#{name},'%')</if></where></select>
</mapper>

 多对一: 

查看老师教授课程

User.vue

//让页面好看<el-table-column prop="role" label="角色" width="140"><template slot-scope="scope"><el-tag type="primary" v-if="scope.row.role==='ROLE_ADMIN'">管理员</el-tag><el-tag type="warning" v-if="scope.row.role==='ROLE_TEACHER'">老师</el-tag><el-tag type="success" v-if="scope.row.role==='ROLE_STUDENT'">学生</el-tag></template></el-table-column>//添加按钮<el-button type="primary" @click="lookCourse(scope.row.courses)" v-if="scope.row.role === 'ROLE_TEACHER'">查看教授课程<i class="el-icon-document"></i></el-button>//添加弹窗
<el-dialog title="课程信息" :visible.sync="vis" width="30%"><el-table :data="courses" border stripe><el-table-column prop="name" label="课程名称"></el-table-column><el-table-column prop="score" label="学分"></el-table-column></el-table></el-dialog>//添加变量courses: [],vis: false//添加方法lookCourse(courses) {this.courses = coursesthis.vis = true},

User

@TableField(exist = false)private List<Course> courses;

UserController

@GetMapping("/selectPage")public Result selectPage(@RequestParam(defaultValue = "") String username,@RequestParam Integer pageSize,@RequestParam Integer pageNum,@RequestParam(defaultValue = "") String email,@RequestParam(defaultValue = "") String address) {return Result.success(userService.findPage(new Page<>(pageNum,pageSize),username,email,address));}

UserService

Page<User> findPage(Page<User> page, String username, String email, String address);

UserServiceImpl

 @Overridepublic Page<User> findPage(Page<User> page, String username, String email, String address) {return userMapper.findPage(page,username,email,address);}

UserMapper

    Page<User> findPage(Page<User> page, @Param("username") String username,@Param("email") String email,@Param("address") String address);

UserMapper.xml

<resultMap id="pageUser" type="com.example.springboot.entity.User"><result column="id" property="id"/><result column="username" property="username"/><result column="nickname" property="nickname"/><result column="email" property="email"/><result column="phone" property="phone"/><result column="address" property="address"/><result column="create_time" property="createTime"/><result column="avatar_url" property="avatarUrl"/><result column="role" property="role"/><collection property="courses" javaType="java.util.ArrayList" ofType="com.example.springboot.entity.Course"><result column="name" property="name"/><result column="score" property="score"/></collection></resultMap><select id="findPage" resultMap="pageUser">select sys_user.*,t_course.*from sys_user left join t_courseon sys_user.id = t_course.teacher_id<where><if test="username !=null and username!=''">and sys_user.username like concat('%',#{username},'%')</if><if test="email !=null and email!=''">and sys_user.email like concat('%',#{email},'%')</if><if test="address !=null and address!=''">and sys_user.address like concat('%',#{address},'%')</if></where></select>

 多对多

学生选课功能

新建数据库表

 

 CourseController

//修改或增加@PostMapping("/studentCourse/{courseId}/{studentId}")public Result StudentCourse(@PathVariable Integer courseId,@PathVariable Integer studentId ) {//新增或修改courseService.setStudentCourse(courseId,studentId);return Result.success();}

CourseService

void setStudentCourse(Integer courseId, Integer studentId);

CourseServiceImpl

@Override@Transactionalpublic void setStudentCourse(Integer courseId, Integer studentId) {courseMapper.deleteStudentCourse(courseId, studentId);courseMapper.setStudentCourse(courseId, studentId);}

CourseMapper

    void deleteStudentCourse(@Param("courseId") Integer courseId, @Param("studentId") Integer studentId);void setStudentCourse(@Param("courseId") Integer courseId, @Param("studentId") Integer studentId);

CourseMapper.xml

<delete id="deleteStudentCourse">deletefrom student_coursewhere student_id = #{studentId}and course_id = #{courseId}</delete><insert id="setStudentCourse">insertinto student_course(student_id, course_id)values (#{studentId}, #{courseId})</insert>

Course.vue

//添加按钮           <el-button type="primary" @click="selectCourse(scope.row.id)">选课</el-button>//添加方法
selectCourse(courseId) {this.request.post("/course/studentCourse/" + courseId + "/" + this.user.id).then(res => {if (res.code === '200') {this.$message.success("选课成功")} else {this.$message.error(res.msg)}})},

查询已选课程功能实现

User.vue

//添加按钮<el-button type="warning" @click="lookStuCourse(scope.row.stuCourses)" v-if="scope.row.role === 'ROLE_STUDENT'">查看已选课程<i class="el-icon-document"></i></el-button>//添加参数
stuVis:false,stuCourses:[],//添加功能lookStuCourse(stuCourses) {this.courses = stuCoursesthis.stuVis = true},<el-dialog title="课程信息" :visible.sync="stuVis" width="30%"><el-table :data="courses" border stripe><el-table-column prop="name" label="课程名称"></el-table-column><el-table-column prop="score" label="学分"></el-table-column></el-table></el-dialog>

UserMapper.xml

<resultMap id="pageUser" type="com.example.springboot.entity.User"><result column="id" property="id"/><result column="username" property="username"/><result column="nickname" property="nickname"/><result column="email" property="email"/><result column="phone" property="phone"/><result column="address" property="address"/><result column="create_time" property="createTime"/><result column="avatar_url" property="avatarUrl"/><result column="role" property="role"/><collection property="courses" javaType="java.util.ArrayList" ofType="com.example.springboot.entity.Course"><result column="teacherCourseName" property="name"/><result column="teacherScore" property="score"/></collection><collection property="stuCourses" javaType="java.util.ArrayList" ofType="com.example.springboot.entity.Course"><result column="stuCourseName" property="name"/><result column="stuScore" property="score"/></collection></resultMap><select id="findPage" resultMap="pageUser">select sys_user.*,sc.name as stuCourseName,tc.name as teacherCourseName,tc.score as teacherScore,sc.score as stuScore from sys_userleft join student_courseon sys_user.id = student_course.student_idleft join t_course scon student_course.course_id = sc.idleft join t_course tcon sys_user.id = tc.teacher_id<where><if test="username !=null and username!=''">and sys_user.username like concat('%',#{username},'%')</if><if test="email !=null and email!=''">and sys_user.email like concat('%',#{email},'%')</if><if test="address !=null and address!=''">and sys_user.address like concat('%',#{address},'%')</if></where></select>

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/13272.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

开源数字名片生成器EnBizCard

什么是 EnBizCard &#xff1f; EnBizCard 可帮助您创建美观、响应灵敏的基于 HTML 的数字名片&#xff0c;并将其托管在您的网站上。 无需注册100% 免费和开源没有用户跟踪和数据收集离线工作 如果不想自己搭建&#xff0c;可以去试用官方的在线体验站点&#xff0c;地址&…

排序算法解析

常见的排序算法包括以下几种&#xff1a; 冒泡排序&#xff08;Bubble Sort&#xff09;&#xff1a;重复比较相邻的两个元素&#xff0c;将较大的元素逐渐向后移动&#xff0c;直到整个序列有序。 选择排序&#xff08;Selection Sort&#xff09;&#xff1a;从未排序部分选…

java面试题(24)

1、重写equals&#xff08;&#xff09;方法的原则 1、对称性&#xff1a; 如果x.equals&#xff08;y&#xff09;返回是“true”&#xff0c;那么y.equals&#xff08;x&#xff09;也应该返回是 “true”。 2、自反性&#xff1a; x.equals&#xff08;x&#xff09;必须…

mysql 数据库备份和还原

数据库备份 第一步&#xff1a;先在环境变量Path里面加上mysql bin目录的路径 第二部&#xff1a;执行对应的命令 备份数据库中的表&#xff1a; 命令&#xff1a; mysqldump -u root -p fenku_lianxi customer > d:\temp.sql root是 账号 username fenku_lianxi是数据…

transforms机制与数据标准化

文章和代码已经归档至【Github仓库&#xff1a;https://github.com/timerring/dive-into-AI 】或者公众号【AIShareLab】回复 pytorch教程 也可获取。 文章目录 图像预处理 transformstransforms运行机制数据标准化transforms.normalizetransforms.Normalize 图像预处理 transf…

javassist 02 implement interface

创建 interface package com.wsd;public interface AccountDao {int delete(); }利用 javassist 生产一个 类A, Class A implements AccountDao package com.wsd;import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.Modifi…

4. PS切图

4.1常见的图片格式 jpg图像格式: JPEG ( .JPG )对色彩的信息保留较好,高清,颜色较多,我们产品类的图片经常用jpg格式的gif图像格式 : GIF格式最多只能储存256色,所以通常用来显示简单图形及字体,但是可以保存透明背景和动画效果,实际经常用于一些图片小动画效果png图像格式&am…

RabbitMQ五种工作模式的简单应用

发布订阅模式(三种方式) 发布订阅模式上一篇我们已经介绍了,这里就不做介绍了,想要看的可以点此链接 在SpringBoot中对RabbitMQ三种使用方式_流殇꧂的博客-CSDN博客 Routing(路由模式)(基于注解的方式) 1.创建交换机和消息队列,类型要为direct(不设置也是默认的配置) //路由模式…

企业低成本万能架构

企业软件应用架构层出不穷&#xff08;这里的应用架构是指偏后端服务的软件架构&#xff09;每个企业由各自业务形态&#xff0c;技术栈&#xff0c;技术路线&#xff0c;技术实力不同&#xff0c;各自架构方案&#xff0c;技术选型各有各的不同&#xff0c;千姿百态&#xff0…

English Learning - L3 作业打卡 Lesson8 Day58 2023.7.3 周一

English Learning - L3 作业打卡 Lesson8 Day58 2023.7.3 周一 引言&#x1f349;句1: And this is when I learned that our borders and our obstacles can only do two things: one, stop us in our tracks or two, force us to get creative.成分划分弱读连读爆破语调 &…

颜色渐变的数据密集适用的堆叠图

一般情况会用柱状图去堆叠&#xff0c;但是如果数据量太大了&#xff0c;就可考虑这种方式堆叠。可以呈现时间和数量上不同层次数据的变化。 效果图&#xff1a; 比较详细的注释一下源码&#xff1a; import matplotlib as mpl import matplotlib.pyplot as plt import numpy …

OpenAI的新语言模型升级是否会改变人工智能领域的格局?

近年来&#xff0c;人工智能领域取得了巨大的进展&#xff0c;其中语言模型的发展尤为引人注目。而在这个领域的重要参与者之一&#xff0c;OpenAI近期宣布了其大型语言模型API的重大升级&#xff0c;引发了业界的广泛关注。随着GPT-4和gpt-3.5-turbo等新版本的推出&#xff0c…