create database ssm_db3;
use ssm_db3;
-- 班级表
create table tb_class(
`c_id` varchar(32) primary key comment '班级ID',
`c_name` varchar(50) comment '班级名称',
`desc` varchar(200) comment '班级描述'
);
insert into tb_class(`c_id`,`c_name`,`desc`) values('c001','Java12班','。。。。');
insert into tb_class(`c_id`,`c_name`,`desc`) values('c002','Java34班','。。。。');
# 学生表
create table tb_student(
s_id varchar(32) primary key comment '学生ID',
sname varchar(50) comment '姓名',
age int comment '年龄',
birthday datetime comment '生日',
gender char(1) comment '性别',
c_id varchar(32)
);
alter table tb_student add constraint foreign key (c_id) references tb_class (c_id);
insert into tb_student(`s_id`,`sname`,`age`,`birthday`,`gender`,`c_id`) values('s001','赵三',19,'2001-01-17','1','c001');
insert into tb_student(`s_id`,`sname`,`age`,`birthday`,`gender`,`c_id`) values('s002','钱四',19,'2001-05-16','1','c001');
insert into tb_student(`s_id`,`sname`,`age`,`birthday`,`gender`,`c_id`) values('s003','孙五',18,'2002-03-15','1','c001');
insert into tb_student(`s_id`,`sname`,`age`,`birthday`,`gender`,`c_id`) values('s004','李三',19,'2001-04-14','0','c002');
insert into tb_student(`s_id`,`sname`,`age`,`birthday`,`gender`,`c_id`) values('s005','周四',19,'2001-02-13','0','c002');
insert into tb_student(`s_id`,`sname`,`age`,`birthday`,`gender`,`c_id`) values('s006','王五',18,'2002-06-12','1','c002');
4.0.0
com.czxy.ssm
day21_student
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.2.5.RELEASE
UTF-8
1.8
Hoxton.SR3
1.1.0
2.2.1.RELEASE
1.3.2
2.0.2
1.2.5
5.1.32
1.1.10
3.4.0
2.7.0
0.9.0
2.9.7
1.9.3
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud-release.version}
pom
import
com.alibaba.nacos
nacos-client
${nacos.version}
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
${alibaba.cloud.version}
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-config
${alibaba.cloud.version}
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
${alibaba.cloud.version}
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis.starter.version}
tk.mybatis
mapper-spring-boot-starter
${mapper.starter.version}
com.github.pagehelper
pagehelper-spring-boot-starter
${pageHelper.starter.version}
com.baomidou
mybatis-plus-boot-starter
${mybatis.plus.version}
com.baomidou
mybatis-plus-annotation
${mybatis.plus.version}
mysql
mysql-connector-java
${mysql.version}
com.alibaba
druid-spring-boot-starter
${durid.starter.version}
io.springfox
springfox-swagger2
${swagger.version}
io.springfox
springfox-swagger-ui
${swagger.version}
commons-beanutils
commons-beanutils
${beanutils.version}
io.jsonwebtoken
jjwt
${jwt.jjwt.version}
joda-time
joda-time
${jwt.joda.version}
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
tk.mybatis
mapper-spring-boot-starter
com.github.pagehelper
pagehelper-spring-boot-starter
mysql
mysql-connector-java
com.alibaba
druid-spring-boot-starter
io.springfox
springfox-swagger2
io.springfox
springfox-swagger-ui
#端口号
server.port=8080
#数据库基本配置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ssm_db3?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=1234
#druid 连接池配置
#驱动
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#初始化连接池大小
spring.datasource.druid.initial-size=1
#最小连接数
spring.datasource.druid.min-idle=1
#最大连接数
spring.datasource.druid.max-active=20
#获取连接时候验证,会影响性能
spring.datasource.druid.test-on-borrow=true
# mybatis
# mybatis.type-aliases-package=com.czxy.domain.base
# mybatis.mapper-locations=classpath:mappers/*.xml
#mapper
mapper.not-empty=false
mapper.identity=MYSQL
#开启驼峰映射
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath*:mapper/*.xml
#开启log4j打印SQL语句
logging.level.com.czxy.dao=debug
package com.czxy.ssm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StudentApplication {
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}
package com.czxy.ssm.vo;
import java.util.HashMap;
import java.util.Map;
public class BaseResult {
//成功状态码
public static final int OK = 1;
//失败状态码
public static final int ERROR = 0;
//返回码
private Integer code;
//返回消息
private String message;
//存放数据
private T data;
//其他数据
private Map other = new HashMap<>();
public BaseResult() {
}
public BaseResult(Integer code, String message) {
this.code = code;
this.message = message;
}
public BaseResult(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 快捷成功BaseResult对象
* @param message
* @return
*/
public static BaseResult ok(String message){
return new BaseResult(BaseResult.OK , message);
}
public static BaseResult ok(String message, Object data){
return new BaseResult(BaseResult.OK , message, data );
}
/**
* 快捷失败BaseResult对象
* @param message
* @return
*/
public static BaseResult error(String message){
return new BaseResult(BaseResult.ERROR , message);
}
/**
* 自定义数据区域
* @param key
* @param msg
* @return
*/
public BaseResult append(String key , Object msg){
other.put(key , msg);
return this;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
public T getData() {
return data;
}
public Map getOther() {
return other;
}
}
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 + '\'' +
'}';
}
}
编写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 {
}
编写service
接口
package com.czxy.ssm.service;
import com.czxy.ssm.domain.Classes;
import java.util.List;
public interface ClassesService {
/**
* 查询所有
* @return
*/
public List 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 selectAll() {
List 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() {
// 查询所有
List list = classesService.selectAll();
// 返回
/*
BaseResult baseResult = new BaseResult();
baseResult.setCode(1); // 0 错误, 1 成功
baseResult.setMessage("提示信息");
baseResult.setData(list);
return baseResult;
*/
return BaseResult.ok("查询成功", list);
}
}
查询结果
Document
编号
名称
描述
{{classes.cid}}
{{classes.cname}}
{{classes.desc}}
编写JavaBean:表对应 Student、条件封装 StudentVo
编写Mapper:StudentMapper
编写service
编写controller
编写JavaBean:表对应 Student、条件封装 StudentVo
表对应 Student
package com.czxy.ssm.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Table(name = "tb_student")
public class Student {
@Id
@Column(name = "s_id")
private String sid;
@Column(name = "sname")
private String sname;
@Column(name = "age")
private Integer age;
@Column(name = "birthday")
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
private Date birthday;
@Column(name = "gender")
private String gender;
@Column(name = "c_id")
private String cid; //班级id
private Classes classes; //班级对象
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public Classes getClasses() {
return classes;
}
public void setClasses(Classes classes) {
this.classes = classes;
}
}
/*
CREATE TABLE tb_student(
s_id VARCHAR(32) PRIMARY KEY COMMENT '学生ID',
sname VARCHAR(50) COMMENT '姓名',
age INT COMMENT '年龄',
birthday DATETIME COMMENT '生日',
gender CHAR(1) COMMENT '性别',
c_id VARCHAR(32)
);
*/
条件封装 StudentVo
package com.czxy.ssm.vo;
/** 学生条件查询封装对象
*/
public class StudentVo {
private String cid;
private String studentName;
private String startAge;
private String endAge;
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStartAge() {
return startAge;
}
public void setStartAge(String startAge) {
this.startAge = startAge;
}
public String getEndAge() {
return endAge;
}
public void setEndAge(String endAge) {
this.endAge = endAge;
}
}
编写Mapper:StudentMapper
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Student;
import tk.mybatis.mapper.common.Mapper;
@org.apache.ibatis.annotations.Mapper
public interface StudentMapper extends Mapper {
}
编写service
接口
package com.czxy.ssm.service;
import com.czxy.ssm.domain.Student;
import com.czxy.ssm.vo.StudentVo;
import com.github.pagehelper.PageInfo;
public interface StudentService {
/**
* 条件查询
* @param pageSize
* @param pageNum
* @param studentVo
* @return
*/
PageInfo condition(Integer pageSize, Integer pageNum, StudentVo studentVo);
}
实现类
package com.czxy.ssm.service.impl;
import com.czxy.ssm.domain.Classes;
import com.czxy.ssm.domain.Student;
import com.czxy.ssm.mapper.ClassesMapper;
import com.czxy.ssm.mapper.StudentMapper;
import com.czxy.ssm.service.StudentService;
import com.czxy.ssm.vo.StudentVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.List;
@Service
@Transactional
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
@Resource
private ClassesMapper classesMapper;
@Override
public PageInfo condition(Integer pageSize, Integer pageNum, StudentVo studentVo) {
//1 拼凑条件
Example example = new Example(Student.class);
Example.Criteria criteria = example.createCriteria();
if(studentVo.getCid() != null && !"".equals(studentVo.getCid())) {
criteria.andEqualTo("cid", studentVo.getCid());
}
if(studentVo.getStudentName() != null && !"".equals(studentVo.getStudentName())) {
criteria.andLike("sname", "%" +studentVo.getStudentName() + "%");
}
if(studentVo.getStartAge() != null && !"".equals(studentVo.getStartAge())) {
criteria.andGreaterThanOrEqualTo("age",studentVo.getStartAge());
}
if(studentVo.getEndAge() != null && !"".equals(studentVo.getEndAge())) {
criteria.andLessThanOrEqualTo("age",studentVo.getEndAge());
}
//2 分页数据
PageHelper.startPage(pageNum,pageSize);
//3 查询
List list = studentMapper.selectByExample(example);
//4 处理关联数据
for (Student student : list) {
Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
student.setClasses(classes);
}
//5 返回
return new PageInfo<>(list);
}
}
编写controller
package com.czxy.ssm.controller;
import com.czxy.ssm.domain.Student;
import com.czxy.ssm.service.StudentService;
import com.czxy.ssm.vo.BaseResult;
import com.czxy.ssm.vo.StudentVo;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/student")
@CrossOrigin
public class StudentController {
@Resource
private StudentService studentService;
/** http://localhost:8080/student/condition/3/1
* 条件查询,接收条件post + 分页
*/
@PostMapping("/condition/{pageSize}/{pageNum}")
public BaseResult condition(
@PathVariable("pageSize") Integer pageSize,
@PathVariable("pageNum") Integer pageNum,
@RequestBody StudentVo studentVo) {
// 查询
PageInfo pageInfo = studentService.condition(pageSize,pageNum,studentVo);
// 返回结果
return BaseResult.ok("查询成功", pageInfo);
}
}
环境:导入2个js、new Vue()
编写条件查询函数,发送ajax查询
展示查询结果:data区域存放数据,使用table展示数据
条件查询表单,封装数据
分页条
环境:导入2个js、new Vue()
new Vue({
el: '#app',
data:{}
})
编写条件查询函数,发送ajax查询
methods: {
condition(pageNum) {
if(pageNum) {
this.pageInfo.pageNum = pageNum
}
var url = `http://localhost:8080/student/condition/${this.pageInfo.pageSize}/${this.pageInfo.pageNum}`
axios.post(url,this.studentVo)
.then(res => {
// 处理数据
var baseResult = res.data
// 判断
if(baseResult.code == 1) {
// 成功
this.pageInfo = baseResult.data
} else {
// 失败
alert(baseResult.message)
}
})
.catch(err => {
console.error(err);
})
}
},
created() {
// 条件所有
this.condition()
},
展示查询结果:data区域存放数据,使用table展示数据
ID
班级
姓名
年龄
生日
性别
操作
{{student.sid}}
{{student.classes !=null ? student.classes.cname : ''}}
{{student.sname}}
{{student.age}}
{{student.birthday}}
{{student.gender == 1? "男": "女"}}
修改
删除
条件查询表单,封装数据
班级:
姓名:
年龄: -
分页条
当前第{{pageInfo.pageNum}}页,共{{pageInfo.pages}}页
{{num}}
Document
ID
班级
姓名
年龄
生日
性别
操作
{{student.sid}}
{{student.classes !=null ? student.classes.cname : ''}}
{{student.sname}}
{{student.age}}
{{student.birthday}}
{{student.gender == 1? "男": "女"}}
修改
删除
当前第{{pageInfo.pageNum}}页,共{{pageInfo.pages}}页
{{num}}
步骤1:ajax查询,将结果存放到data区域
selectAllClasses() {
var url = 'http://localhost:8080/classes'
axios.get(url)
.then(response => {
// 将查询结果保存data区域
var baseResult = response.data
if(baseResult.code == 1) {
this.classesList = baseResult.data
}
})
.catch(error => {})
}
步骤2:从data获得数据,并使用select展示
{{classes.cname}}
完整代码
Document
ID
班级
姓名
年龄
生日
性别
操作
{{student.sid}}
{{student.classes !=null ? student.classes.cname : ''}}
{{student.sname}}
{{student.age}}
{{student.birthday}}
{{student.gender == 1? "男": "女"}}
修改
删除
当前第{{pageInfo.pageNum}}页,共{{pageInfo.pages}}页
{{num}}
编写service
接口
/**
* 通过id查询详情
* @param sid
* @return
*/
public Student selectById(String sid );
实现类
@Override
public Student selectById(String sid) {
return studentMapper.selectByPrimaryKey(sid);
}
编写controller
/**
* 通过id 查询详情
* @param sid
* @return
*/
@GetMapping("/{sid}")
public BaseResult selectById(@PathVariable("sid") String sid) {
// 查询详情
Student student = studentService.selectById(sid);
// 返回结果
return BaseResult.ok("查询成功", student);
}
编写service
接口
/**
* 更新学生信息
* @param student
* @return
*/
public boolean update(Student student);
实现类
@Override
public boolean update(Student student) {
int result = studentMapper.updateByPrimaryKey(student);
return result == 1;
}
编写controller
/**
* 更新
* @param student
* @return
*/
@PutMapping
public BaseResult update(@RequestBody Student student) {
// 更新操作
boolean result = studentService.update(student);
// 处理结果
if(result) {
// 成功 code==1
return BaseResult.ok("更新成功");
} else {
// 失败 code==0
return BaseResult.error("更新失败");
}
}
修改
Title
学生
班级
姓名
年龄
生日
性别
男
女
{{student}}
Title
学生
班级
姓名
年龄
生日
性别
男
女
细节1:给更新按钮绑定事件
细节2:编写函数完成更新,如果成功重定向到列表页面,如果失败提示
updateStudent() {
var url = 'http://localhost:8080/student'
axios.put(url,this.student)
.then(res => {
var baseResult = res.data
if(baseResult.code == 1) {
// 成功
location.href = 'student_list.html'
} else {
// 失败
alert(baseResult.message)
}
})
.catch(err => {
console.error(err);
})
}
Title
学生
班级
姓名
年龄
生日
性别
男
女
编写service
接口
/**
* 通过id删除
* @param sid
* @return
*/
public boolean delete(String sid);
实现类
@Override
public boolean delete(String sid) {
int result = studentMapper.deleteByPrimaryKey(sid);
return result == 1;
}
编写controller
/**
* 删除
* @param sid
* @return
*/
@DeleteMapping("/{sid}")
public BaseResult deleteById(@PathVariable("sid") String sid) {
// 删除
boolean result = studentService.delete(sid);
// 处理
if(result) {
// 成功 code==1
return BaseResult.ok("删除成功");
} else {
// 失败 code==0
return BaseResult.error("删除失败");
}
}
步骤1:给超链接绑定点击事件
删除
步骤2:发送ajax删除,成功刷新,失败提示
deleteUser(sid) {
// 询问
if(!confirm("您确定要删除么?")) {
return;
}
var url = `http://localhost:8080/student/${sid}`
axios.delete(url)
.then(res => {
var baseResult = res.data
if(baseResult.code == 1) {
//成功
location.href = 'student_list.html'
} else {
// 失败
alert(baseResult.message)
}
})
.catch(err => {
console.error(err);
})
}
编写service:调用mapper完成添加
接口
/**
* 添加
* @param student
* @return
*/
public boolean add(Student student);
实现类
@Override
public boolean add(Student student) {
int result = studentMapper.insert(student);
return result == 1;
}
编程controller:
/**
* 添加
* @param student
* @return
*/
@PostMapping
public BaseResult add(@RequestBody Student student) {
// 添加
boolean result = studentService.add(student);
// 处理
if(result) {
// 成功 code==1
return BaseResult.ok("添加成功");
} else {
// 失败 code==0
return BaseResult.error("添加失败");
}
}
Title
学生ID
班级
姓名
年龄
生日
性别
男
女