4.班级管理
4.1JavaBean:Classes
package com.czxy.ssm.domain; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; @Table(name = "tb_class") public class Classes { /* CREATE TABLE tb_class( `c_id` VARCHAR(32) PRIMARY KEY COMMENT '班级ID', `c_name` VARCHAR(50) COMMENT '班级名称', `desc` VARCHAR(200) COMMENT '班级描述' ); */ @Id @Column(name = "c_id") private String cid; @Column(name = "c_name") private String cname; @Column(name = "`desc`") private String desc; public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Classes() { } public Classes(String cid, String cname, String desc) { this.cid = cid; this.cname = cname; this.desc = desc; } @Override public String toString() { return "Classes{" + "cid='" + cid + '\'' + ", cname='" + cname + '\'' + ", desc='" + desc + '\'' + '}'; } }
4.2查询所有
4.2.1后端
- 编写Mapper
package com.czxy.ssm.mapper; import com.czxy.ssm.domain.Classes; import tk.mybatis.mapper.common.Mapper; @org.apache.ibatis.annotations.Mapper public interface ClassesMapper extends Mapper<Classes> { }
- 编写service
- 接口
package com.czxy.ssm.service; import com.czxy.ssm.domain.Classes; import java.util.List; public interface ClassesService { /** * 查询所有 * @return */ public List<Classes> selectAll() ; }
-实现类
package com.czxy.ssm.service.impl; import com.czxy.ssm.domain.Classes; import com.czxy.ssm.mapper.ClassesMapper; import com.czxy.ssm.service.ClassesService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; @Service @Transactional public class ClassesServiceImpl implements ClassesService { @Resource private ClassesMapper classesMapper; @Override public List<Classes> selectAll() { List<Classes> list = classesMapper.selectAll(); return list; } }
- 编写Controller
package com.czxy.ssm.controller; import com.czxy.ssm.domain.Classes; import com.czxy.ssm.service.ClassesService; import com.czxy.ssm.vo.BaseResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; @RestController @RequestMapping("/classes") public class ClassesController { @Resource private ClassesService classesService; @GetMapping public BaseResult<List<Classes>> list() { // 查询所有 List<Classes> list = classesService.selectAll(); // 返回 /* BaseResult baseResult = new BaseResult(); baseResult.setCode(1); // 0 错误, 20000 成功 baseResult.setMessage("提示信息"); baseResult.setData(list); return baseResult; */ return BaseResult.ok("查询成功", list); } }
- 查询结果
4.2.2前端:axios+then
- 编写页面、发送ajax、显示数据
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="js/vue.js"></script> <script src="js/axios.js"></script> </head> <body> <div id="app"> <table border="1"> <tr> <td>编号</td> <td>名称</td> <td>描述</td> </tr> <tr v-for="(classes,index) in classesList"> <td>{{classes.cid}}</td> <td>{{classes.cname}} </td> <td>{{classes.desc}}</td> </tr> </table> </div> </body> </html> <script> new Vue({ el: '#app', data: { classesList: [] }, methods: { selectAllClasses() { // ajax 查询 var url = 'http://localhost:8080/classes' axios.get(url) .then(res => { // 获得查询结果 BaseResult var baseResult = res.data // 判断 if(baseResult.code == 1) { // 成功 -- 将结果存放到数据区域 this.classesList = baseResult.data } else { // 失败 alert(baseResult.message) } }) .catch(err => { console.error(err); }) } }, created() { //mounted() // 查询所有 this.selectAllClasses() }, }) </script>
4.2.3前端:async+await
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>班级列表</title> <script src="../js/axios.js"></script> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <table border="1"> <tr> <td>编号</td> <td>班级名称</td> <td>描述</td> <td>操作</td> </tr> <tr v-for="(classes,index) in classesList"> <td>{{classes.cid}}</td> <td>{{classes.cname}}</td> <td>{{classes.desc}}</td> <td> 修改 删除 </td> </tr> </table> </div> </body> </html> <script> new Vue({ el: '#app', data: { classesList: [], //所有班级 }, methods: { async findAllClasses() { // response.data let { data: baseResult } = await axios.get(`http://localhost:8080/classes`) // 判断 if(baseResult.code == 20000) { this.classesList = baseResult.data } } }, mounted() { // 查询所有班级 this.findAllClasses() } }) </script>
4.3添加班级
4.3.1需求:
- 完成班级的添加
- 后端
- 获得提交的班级数据(json数据)
- 保存班级数据(controller-service)
- 根据操作结果提示:成功true-->添加成功,失败false-->添加失败
- 前端
- 绘制表单,数据绑定
- 点击添加,发送ajax完成添加
- 成功,跳转到列表页面。失败,给出提示
4.3.2后端
- 步骤1:编写service,完成添加
- 接口
/** * 添加班级 * @param classes * @return */ public boolean add(Classes classes);
- 实现类
@Override public boolean add(Classes classes) { int result = classesMapper.insert(classes); return result == 1; }
步骤2:编写controller,处理结果BaseResult
/** * 添加班级 * @param classes * @return */ @PostMapping public BaseResult add(@RequestBody Classes classes) { // 添加 boolean result =classesService.add(classes); // 提示 if(result) { // 成功 return BaseResult.ok("添加成功"); } // 失败 return BaseResult.error("添加失败"); }
4.3.3前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>班级列表</title> <script src="../js/axios.js"></script> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <table> <tr> <td>编号</td> <td> <input type="text" v-model="classes.cid" /> </td> </tr> <tr> <td>班级名称</td> <td> <input type="text" v-model="classes.cname" /> </td> </tr> <tr> <td>班级描述</td> <td> <textarea cols="30" rows="10" v-model="classes.desc"></textarea> </td> </tr> <tr> <td> <input type="button" value="添加" @click="addClasses" /> </td> <td></td> </tr> </table> </div> </body> </html> <script> new Vue({ el: '#app', data: { classes: { } }, methods: { async addClasses() { let { data: baseResult } = await axios.post(`http://localhost:8080/classes`, this.classes) // 提示 if(baseResult.code == 20000) { //成功 location.href = '/classes/list.html' } else { //失败 alert(baseResult.message) } } }, mounted() { } }) </script>
4.4修改班级
4.4.1需求:
完成班级的修改
表单的回显:通过id查询详情
修改功能:通过id更新
4.4.2后端
- 步骤
- 编写service:selectById、update
- 接口
- 实现类
- 编写controller:selectById、update
- 编写service:selectById、update
- 接口
/** * 通过id查询详情 * @param cid * @return */ public Classes selectById(String cid); /** * 更新班级 * @param classes * @return */ public boolean update(Classes classes);
- 实现类
@Override public Classes selectById(String cid) { return classesMapper.selectByPrimaryKey(cid); } @Override public boolean update(Classes classes) { int result = classesMapper.updateByPrimaryKeySelective(classes); return result == 1; }
- 编写controller:selectById、update
/** * 查询详情 * @param cid * @return */ @GetMapping("/{cid}") public BaseResult<Classes> selectById(@PathVariable("cid") String cid) { //查询 Classes classes = classesService.selectById(cid); //返回 return BaseResult.ok("查询详情成功", classes); } /** * 更新 * @param classes * @return */ @PutMapping public BaseResult update(@RequestBody Classes classes) { try { // 更新 boolean result = classesService.update(classes); // 提示 if(result) { return BaseResult.ok("更新成功"); } return BaseResult.error("更新失败"); } catch (Exception e) { e.printStackTrace(); return BaseResult.error(e.getMessage()); } }
4.4.3前端
- 步骤:
- 列表页面点击“修改”,添加到修改页面 edit.html?cid=c001
- 页面加载成功时,通过id查询详情
- 回显:将查询结果绑定表单(添加已经完成,采用复制)
- 点击确定进行更新
- 修改list.html页面
<a :href="'/cls/edit.html?cid=' + classes.cid">修改</a>
编写edit.html页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>班级列表</title> <script src="../js/axios.js"></script> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <!--3 表单回显 --> <table> <tr> <td>编号</td> <td> {{classes.cid}} </td> </tr> <tr> <td>班级名称</td> <td> <input type="text" v-model="classes.cname" /> </td> </tr> <tr> <td>班级描述</td> <td> <textarea cols="30" rows="10" v-model="classes.desc"></textarea> </td> </tr> <tr> <td> <!--4 更新 --> <input type="button" value="修改" @click="updateClasses" /> </td> <td></td> </tr> </table> </div> </body> </html> <script> new Vue({ el: '#app', data: { classes: { }, classesId: '' }, methods: { async selectClassesById() { //2 查询详情 let { data: baseResult } = await axios.get(`http://localhost:8080/classes/${this.classesId}`) // 将查询结果存放classes对象,将自动回显 if( baseResult.code == 20000) { this.classes = baseResult.data } }, async updateClasses() { // 4 更新函数 let { data: baseResult } = await axios.put(`http://localhost:8080/classes`, this.classes) // 提示 if(baseResult.code == 20000) { //成功 location.href = '/cls/list.html' } else { //失败 alert(baseResult.message) } } }, mounted() { // 2.1 获得id let arr = location.href.split("?cid=") this.classesId = arr[1] // 2.2 查询详情 this.selectClassesById() } }) </script>
4.5删除班级
4.5.1分析
- 需求:通过id删除班级
- 思路:
- 确定访问路径:delete /classes/c001
- 点击发送ajax进行删除(成功:刷新页面;失败:提示)
- 编写controller获得id
- 编写service通过id删除
4.5.2后端
- 步骤:
- 编写controller获得id
- 编写service通过id删除
- 编写controller获得id
@DeleteMapping("/{classesId}") public BaseResult delete(@PathVariable("classesId") String classesId) { // 删除 boolean result = classesService.deleteById(classesId); // 处理 // 提示 if(result) { return BaseResult.ok("删除成功"); } return BaseResult.error("删除失败"); }
编写service通过id删除
- 接口
/** * 通过id删除 * @param classesId * @return */ boolean deleteById(String classesId); –实现类 @Override public boolean deleteById(String classesId) { int result = classesMapper.deleteByPrimaryKey(classesId); return result == 1 ; }
4.5.3前端
- 需求:点击发送删除ajax
<a href="" @click.prevent="deleteClasses(classes.cid)">删除</a> async deleteClasses( cid ) { // 询问 if(!confirm("您确定要删除么?")) { return } let { data: baseResult } = await axios.delete(`http://localhost:8080/classes/${cid}`) if(baseResult.code == 20000) { // 成功 this.findAllClasses() } else { // 失败 alert(baseResult.message) } }
4.5.4完善后端:级联删除
- 级联删除:删除班级前,先删除所关联的学生。
- 需求:完善班级删除的service,先删除指定班级的所有学生。
- 步骤:
- 编写JavaBen:Student
- 编写Mapper:StudentMapper
- 修改班级的service
- 编写JavaBen:Student
package com.czxy.student.domain; import lombok.Data; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; @Table(name = "tb_student") @Data public class Student { @Id @Column(name = "s_id") private String sid; private String sname; private Integer age; private Date birthday; @Column(name = "c_id") private String cid; } /* Create Table CREATE TABLE `tb_student` ( `s_id` varchar(32) NOT NULL COMMENT '学生ID', `sname` varchar(50) DEFAULT NULL COMMENT '姓名', `age` int(11) DEFAULT NULL COMMENT '年龄', `birthday` datetime DEFAULT NULL COMMENT '生日', `gender` char(1) DEFAULT NULL COMMENT '性别', `c_id` varchar(32) DEFAULT NULL, PRIMARY KEY (`s_id`), KEY `c_id` (`c_id`), CONSTRAINT `tb_student_ibfk_1` FOREIGN KEY (`c_id`) REFERENCES `tb_class` (`c_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 */
编写Mapper:StudentMapper
package com.czxy.student.mapper; import com.czxy.student.domain.Student; import tk.mybatis.mapper.common.Mapper; @org.apache.ibatis.annotations.Mapper public interface StudentMapper extends Mapper<Student> { } •修改班级的service @Resource private StudentMapper studentMapper; @Override public boolean deleteById(String classesId) { // 先删除班级中的学生 Example example = new Example(Student.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("cid", classesId); studentMapper.deleteByExample(example); // 删除班级 int result = classesMapper.deleteByPrimaryKey(classesId); return result == 1 ; }