1、所使用的环境配置:
编译器:IDEA
后台框架:SpringBoot
Mybatis-Plus
数据库:Mysql8.0
数据库工具:Navicat premium
前端框架:Vue Element UI
2、项目简介
这是一个基于SpringBoot和Vue的简单增删改查。
页面展示
增加
修改
3、代码和配置
项目结构
3.1 配置文件:
(1) Mybatis-Plus配置文件,实现分页查询:MybatisPlusConfig
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置
* MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
(2) 跨域配置文件:CorsConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration // 一定不要忽略此注解
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有接口
.allowCredentials(true) // 是否发送 Cookie
.allowedOrigins("*")// 支持域
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) // 支持方法
.allowedHeaders("*")
.exposedHeaders("*");
}
}
(3) swagger配置文件
@Configuration
@EnableSwagger2 //开启seagger注解驱动
public class SwaggerConfig {
@Bean
public Docket docket(){
Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("QY163")
.apiInfo(getInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.hm.controller"))
.build();
return docket;
}
private ApiInfo getInfo(){
Contact DEFAULT_CONTACT = new Contact("hm", "http://www.baidu.com", "[email protected]");
ApiInfo apiInfo=new ApiInfo("QY163心里测试系统API", "QY163心里测试系统API", "1.1.0", "http://www.jd.com",
DEFAULT_CONTACT, "志远科技", "http://www.aaa.com", new ArrayList<VendorExtension>());
return apiInfo;
}
}
(4) mysql 配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql:///work
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
(5) Result请求返回类
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "公共json对象")
public class Result {
@ApiModelProperty(value = "状态码 200正常 500错误")
private Integer code;
@ApiModelProperty(value = "消息内容")
private String msg;
@ApiModelProperty(value = "数据")
private Object data;
}
(6)pom.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hm</groupId>
<artifactId>qy163-springboot03</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>qy163-springboot03</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--swagger2依赖-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.7.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.2 代码
1. 实体类
学生实体类
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @program: qy163-springboot04
* @description:
* @author: 胡萌
* @create: 2023-04-12 20:20
**/
@Data
@ApiModel(value = "学生实体类")
public class Student implements Serializable {
/**
*
*/
@TableId(type = IdType.AUTO)
@ApiModelProperty(value = "学生编号")
private Integer sid;
/**
*
*/
@ApiModelProperty(value = "学生姓名")
private String sname;
/**
*
*/
@ApiModelProperty(value = "学生年龄")
private Integer age;
/**
*
*/
@ApiModelProperty(value = "班级编号")
private Integer cid;
@TableField(exist = false)
private Class aaa;
public Student() {
}
public Student(Integer sid, String sname, Integer age, Integer cid) {
this.sid = sid;
this.sname = sname;
this.age = age;
this.cid = cid;
}
public Student(String sname, Integer age, Integer cid) {
this.sname = sname;
this.age = age;
this.cid = cid;
}
private static final long serialVersionUID = 1L;
}
班级实体类
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(value = "班级实体类")
public class Class implements Serializable {
/**
*
*/
@TableId(type = IdType.AUTO)
@ApiModelProperty(value = "班级编号")
private Integer cid;
/**
*
*/
@ApiModelProperty(value = "班级名称")
private String cname;
private static final long serialVersionUID = 1L;
}
2. 定义一个StudentVo来作为条件查询
@ApiModel(value = "接收学生的请求参数")
public class StudentVo {
@ApiModelProperty(value = "学生编号")
private String sid;
@ApiModelProperty(value = "学生的名称")
private String sname;
@ApiModelProperty(value = "学生的年龄")
private String age;
private String cid;
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 String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public StudentVo(String sid, String sname, String age, String cid) {
this.sid = sid;
this.sname = sname;
this.age = age;
this.cid = cid;
}
}
3.mapper层
StudentMapper
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hm.pojo.entity.Student;
import org.apache.ibatis.annotations.Param;
/**
* @program: qy163-springboot04
* @description:
* @author:
* @create: 2023-04-12 19:27
**/
public interface StudentMapper extends BaseMapper<Student> {
IPage<Student> findByPage(IPage<Student> iPage,@Param("ew") Wrapper<Student> wrapper);
}
ClassMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
/**
* @program: qy163-springboot04
* @description:
* @author:
* @create: 2023-04-15 14:30
**/
public interface ClassMapper extends BaseMapper<Class> {
List<Class> findAll();
}
4. Mapper.xml
StudentMapper.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.hm.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.hm.pojo.entity.Student" autoMapping="true">
<id property="sid" column="sid" jdbcType="INTEGER"/>
<association property="aaa" javaType="com.hm.pojo.entity.Class" autoMapping="true">
<id property="cid" column="cid"/>
</association>
</resultMap>
<select id="findByPage" resultMap="BaseResultMap">
select * from student t join class c on t.cid=c.cid
<if test="ew!=null and ew.sqlSegment!=''">
<where> and ${ew.sqlSegment} </where>
</if>
</select>
</mapper>
ClassMapper.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.hm.mapper.ClassMapper">
<resultMap id="BaseResultMap" type="com.hm.pojo.Class">
<id property="cid" column="cid" jdbcType="INTEGER"/>
<result property="cname" column="cname" jdbcType="VARCHAR"/>
</resultMap>
<select id="findAll" resultMap="BaseResultMap">
select * from class
</select>
</mapper>
5. Service层
StudentService
import com.hm.pojo.entity.Student;
import com.hm.pojo.vo.StudentVo;
import com.hm.util.Result;
import io.swagger.models.auth.In;
import java.util.List;
/**
* @program: qy163-springboot04
* @description:
* @author:
* @create: 2023-04-12 19:27
**/
public interface StudentService{
//vo:view Object 接受前端请求的数据对象
Result findByPage(Integer current, Integer pageSize, StudentVo studentVo);
Result updateById(Student student);
Result deleteById(Integer sid);
Result deleteBatchIds(List<Integer> ids);
Result insert(Student student);
}
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.hm.mapper.StudentMapper;
import com.hm.pojo.entity.Student;
import com.hm.pojo.vo.StudentVo;
import com.hm.service.StudentService;
import com.hm.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class StudentServiceImpl implements StudentService{
@Resource
private StudentMapper studentMapper;
@Override
public Result findByPage(Integer current, Integer pageSize, StudentVo studentVo) {
//分页对象
Page<Student> page=new Page<>(current,pageSize);
//条件对象-- xml
QueryWrapper<Student> wrapper=new QueryWrapper<>();
//判断是否为空
if (StringUtils.hasText(studentVo.getSid())){
wrapper.eq("sid",studentVo.getSid());
}
if (StringUtils.hasText(studentVo.getSname())){
wrapper.like("sname",studentVo.getSname());
}
if (StringUtils.hasText(studentVo.getAge())){
wrapper.ge("age",studentVo.getAge());
}
IPage<Student> byPage = studentMapper.findByPage(page, wrapper);
return new Result(200,"分页查询学生成功",byPage);
}
@Override
public Result updateById(Student student) {
return new Result(200,"修改学生成功",studentMapper.updateById(student));
}
@Override
public Result deleteById(Integer sid) {
return new Result(200,"删除成功",studentMapper.deleteById(sid));
}
@Override
public Result deleteBatchIds(List<Integer> ids) {
int i = studentMapper.deleteBatchIds(ids);
if (i>0){
return new Result(200,"删除成功",i);
}else{
return new Result(500,"删除失败",i);
}
}
@Override
public Result insert(Student student) {
int insert = studentMapper.insert(student);
if (insert>0){
return new Result(200,"添加成功",insert);
}else{
return new Result(500,"添加失败",insert);
}
}
}
Classservie
import com.hm.util.Result;
/**
* @program: qy163-springboot04
* @description:
* @author:
* @create: 2023-04-15 14:28
**/
public interface ClassService {
Result findAll();
}
impl
import javax.annotation.Resource;
import java.util.List;
/**
* @program: qy163-springboot04
* @description:
* @author:
* @create: 2023-04-15 14:28
**/
@Service
public class ClassServiceImpl implements ClassService {
@Resource
private ClassMapper classMapper;
@Override
public Result findAll() {
List<Class> classes = classMapper.findAll();
return new Result(200,"查询成功",classes);
}
}
6. Controller层
StudentController
import com.hm.mapper.StudentMapper;
import com.hm.pojo.entity.Student;
import com.hm.pojo.vo.StudentVo;
import com.hm.service.StudentService;
import com.hm.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* @program: qy163-springboot04
* @description:
* @author:
* @create: 2023-04-12 19:30
**/
@RestController
@RequestMapping("student")
@Api(tags = "学生操作API")
public class StudentController {
@Autowired
private StudentService studentService;
@Resource
private StudentMapper studentMapper;
@PostMapping("list/{current}/{pageSize}")
@ApiOperation(value = "根据条件分页查询学生信息")
public Result list(
@ApiParam(value = "当前页面", name = "current", required = true, defaultValue = "1")
@PathVariable Integer current,
@ApiParam(value = "当前页数", name = "pageSize", required = true, defaultValue = "5")
@PathVariable Integer pageSize,
@RequestBody StudentVo studentVo) {
return studentService.findByPage(current, pageSize, studentVo);
}
//@PutMapping 查询 get提交 删除 delete 修改 PUT提交 添加 post提交
/*查 根据id查询*/
@GetMapping("findById/{sid}")
@ApiOperation(value = "根据id查询学生信息")
public Student findAById(
@ApiParam(value = "学生id", name = "sid", required = true)
@PathVariable Integer sid
){
Student student = studentMapper.selectById(sid);
return student;
}
/*增*/
@PostMapping("insert")
@ApiOperation(value = "新增学生信息")
public Result insert(@RequestBody Student student){
return studentService.insert(student);
}
/*改*/
@PutMapping("update")
@ApiOperation(value = "根据id修改学生信息")
public Result update(@RequestBody Student student){
System.out.println(student);
return studentService.updateById(student);
}
/*删*/
@DeleteMapping("delete/{sid}")
@ApiOperation(value = "根据删除学生信息")
public Result delete(
@ApiParam(value = "学生id", name = "sid", required = true)
@PathVariable Integer sid
){
Result result = studentService.deleteById(sid);
return result;
}
/*批量删除*/
@PostMapping("deleteList")
public Result deleteList(@RequestBody List<Integer> ids){
System.out.println(ids);
return studentService.deleteBatchIds(ids);
}
}
ClassController
import com.hm.service.ClassService;
import com.hm.util.Result;
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;
/**
* @program: qy163-springboot04
* @description:
* @author:
* @create: 2023-04-15 14:26
**/
@RestController
@RequestMapping("class")
public class ClassController {
@Resource
private ClassService classService;
@GetMapping("list")
public Result list(){
Result all = classService.findAll();
return all;
}
}
4. Vue工程
4.1在App.vue中添加Student路径
4.2 main.js中引入axios
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './plugins/element.js'
import axios from "axios";
Vue.config.productionTip = false
Vue.prototype.axios=axios
new Vue({
router,
render: h => h(App)
}).$mount('#app')
4.3 index.js
4.4 Student.vue
<template>
<div>
<el-form :inline="true" :model="stuSearchForm" class="demo-form-inline">
<el-form-item label="学生编号">
<el-input v-model="stuSearchForm.sid" placeholder="学生编号"></el-input>
</el-form-item>
<el-form-item label="学生编号">
<el-input v-model="stuSearchForm.sname" placeholder="学生姓名"></el-input>
</el-form-item>
<el-form-item label="学生编号">
<el-input v-model="stuSearchForm.age" placeholder="学生年龄"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="initTable">查询</el-button>
<el-button type="danger" @click="batchDelete">批量删除</el-button>
<el-button type="primary" @click="Add">添加</el-button>
</el-form-item>
</el-form>
<el-table
:data="tableData"
border
@selection-change="handleSelectionChange"
style="width: 100%">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
prop="sid"
label="学生编号">
</el-table-column>
<el-table-column
prop="sname"
label="姓名">
</el-table-column>
<el-table-column
prop="age"
label="年龄">
</el-table-column>
<el-table-column
prop="aaa.cname"
label="班级名称">
</el-table-column>
<el-table-column
fixed="right"
label="操作">
<template slot-scope="scope">
<el-button type="success" icon="el-icon-edit" @click="Student(scope.row)">修改</el-button>
<el-button type="danger" icon="el-icon-delete" @click="del(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!--
@size-change:
@current-change:
page-sizes:[]
:current-page=当前页码
:page-size默认每页显示的条数
:total 总条数
-->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[5, 10, 15, 20]"
:page-size="5"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
<!--编辑对话框-->
<el-dialog
title="修改员工"
:visible.sync="dialogVisible"
width="30%">
<el-form ref="form" :model="studentForm" label-width="80px" >
<el-form-item label="学生编号">
<el-input v-model="studentForm.sid"></el-input>
</el-form-item>
<el-form-item label="学生名字">
<el-input v-model="studentForm.sname"></el-input>
</el-form-item>
<el-form-item label="学生年龄">
<el-input v-model="studentForm.age"></el-input>
</el-form-item>
<el-form-item label="班级编号">
<el-input v-model="studentForm.cid"></el-input>
</el-form-item>
<el-form-item label="班级名称">
<el-select v-model="studentForm.cid" placeholder="请选择">
<el-option
v-for="item in classes"
:key="item.cid"
:label="item.cname"
:value="item.cid">
</el-option>
</el-select>
</el-form-item>
<el-form-item size="large">
<el-button type="primary" @click="updateStudent">确认修改</el-button>
<el-button @click="dialogVisible=false">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
<el-dialog
title="添加学生"
:visible.sync="dialogVisibles"
width="30%">
<el-form ref="form" :model="studentForm" label-width="80px" >
<el-form-item label="学生名字">
<el-input v-model="studentForm.sname"></el-input>
</el-form-item>
<el-form-item label="学生年龄">
<el-input v-model="studentForm.age"></el-input>
</el-form-item>
<el-form-item label="班级编号">
<el-input v-model="studentForm.cid"></el-input>
</el-form-item>
<el-form-item size="large">
<el-button type="primary" @click="addStudent">确认添加</el-button>
<el-button @click="dialogVisibles=false">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
</div>
</template>
<script>
export default {
data(){
return{
dialogVisibles:false,
//编辑对话框的显示和隐藏
dialogVisible:false,
/*搜索*/
stuSearchForm:{},
//编辑表单对象
studentForm:{},
tableData: [],
currentPage:1,
pageSize:5,
total:0,
//所有班级
classes:[],
//表格的选中项
multipleSelection:[],
//声明被选中的id
/*ids:[],*/
//增加
//students:{}
}
},
created() {
this.initTable(),
//查询所有部门
this.loadAllClass()
},
methods:{
addStudent(){
this.axios.post("http://localhost:8080/student/insert",this.studentForm).then(result=>{
if (result.data.code===200){
this.$message.success("添加成功") //弹出成功的消息框
this.dialogVisibles=false;
this.initTable() //重新加载表格
}
})
},
//批量删除
batchDelete(){
this.ids=this.multipleSelection.map(item=>item.sid)
console.log(this.ids)
this.axios.post("http://localhost:8080/student/deleteList",this.ids).then(result=>{
if(result.data.code===200){
this.$message.success(result.data.msg);
//刷新页面
this.initTable();
}
})
},
//获取表格被选中的项
handleSelectionChange(val){
this.multipleSelection=val;
},
//确认修改员工信息
updateStudent(){
this.axios.put("http://localhost:8080/student/update",this.studentForm).then(result=>{
if (result.data.code===200){
this.$message.success("修改成功") //弹出成功的消息框
this.dialogVisible=false;
this.initTable() //重新加载表格
}
})
},
loadAllClass(){
this.axios.get("http://localhost:8080/class/list").then(result=>{
this.classes=result.data.data
console.log(this.classes)
})
},
initTable(){
this.axios.post("http://localhost:8080/student/list/"+this.currentPage+"/"+this.pageSize,this.stuSearchForm).then(result=>{
this.tableData=result.data.data.records;
this.total=result.data.data.total
})
},
//改变每页的条数时触发该方法
handleSizeChange(val) {
this.pageSize=val;
this.initTable();
},
//改变当前页码时触发的方法
handleCurrentChange(val) {
this.currentPage=val;
this.initTable();
},
//删除学生
del(row){
let sid = row.sid;
this.axios.delete("http://localhost:8080/student/delete/"+sid).then(result=>{
if (result.data.code===200){
this.$message.success("删除成功") //弹出成功的消息框
this.initTable() //重新加载表格
}
})
},
//修改
Student(row){
this.dialogVisible=true;
this.studentForm=row;
},
Add(){
this.dialogVisibles=true;
}
}
}
</script>
<style scoped>
</style>