Spring+RestFul+Vue多表(学校,老师,类型)

 今天考了一个测试,在最后时刻才把所有功能都写完,还得继续努力了,接下来把这个测试案例分享给大家:

数据库SQL(有三个表:校区表,老师表,类型表):

 CREATE TABLE `t_school`  (
`id` int(11) NOT NULL AUTO_INCREMENT,
`school_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
);

INSERT INTO `t_school` VALUES (1, '沭阳校区');
INSERT INTO `t_school` VALUES (2, '南京校区');
INSERT INTO `t_school` VALUES (3, '上海校区');
INSERT INTO `t_school` VALUES (4, '北京校区');

CREATE TABLE `t_teacher`  (
`id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`salary` decimal(10, 2) NULL DEFAULT NULL,
`type_id` int(11) NULL DEFAULT NULL,
`school_id` int(11) NULL DEFAULT NULL,
`hire_date` date NULL DEFAULT NULL,
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ;
INSERT INTO `t_teacher` VALUES (1, 'tom', '123', '男', 5000.00, 1, 1, '2020-02-03', 'tom是优秀老师');
INSERT INTO `t_teacher` VALUES (2, 'lucy', '123', '女', 10000.00, 2, 2, '2020-06-09', 'lucy很优秀');


CREATE TABLE `t_type`  (
`id` int(11) NOT NULL AUTO_INCREMENT,
`city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
);

INSERT INTO `t_type` VALUES (1, '辅导员');
INSERT INTO `t_type` VALUES (2, '助理讲师');
INSERT INTO `t_type` VALUES (3, '主讲老师');
INSERT INTO `t_type` VALUES (4, '财务老师');
INSERT INTO `t_type` VALUES (5, '后勤老师');

前期准备:
application.yml:

#端口号
server:
  port: 8081
#服务名
spring:
  thymeleaf:
    prefix: classpath:/templates/
    mode: html5
    encoding: utf-8
    suffix: .html
    cache: false
  mvc:
    static-path-pattern: /**
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ssm_db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT&autoReconnect=true&useSSL=false
    username: root
    password: root
    druid: #druid 连接池配置
      initial-size: 1       #初始化连接池大小
      min-idle: 1           #最小连接数
      max-active: 20        #最大连接数
      test-on-borrow: true  #获取连接时候验证,会影响性能
  servlet:
    multipart:
      #设置总上传的数据大小
      max-request-size: 100MB
      #单个文件大小
      maxFileSize: 30MB
    #热部署模块
    devtools:
      restart:
        enabled: true
        additional-paths: src/main/java
        exclude: test/**
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss

#pagehelper分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
#开启log4j打印SQL语句
logging:
  level:
    com:
      omitkit:
        mapper: debug

返回值Java类型:BaseResult.java

package com.czxy.Vo;

import java.util.HashMap;
import java.util.Map;

public class BaseResult<T> {

    //成功状态码
    public static final int OK = 1;
    //失败状态码
    public static final int ERROR = 0;

    //返回码
    private Integer code;
    //返回消息
    private String message;

    //存放数据
    private T data;
    //其他数据
    private Map<String,Object> 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<String, Object> getOther() {
        return other;
    }
}

pom文件:pom.xml



    4.0.0

    org.example
    exam_project1919
    1.0-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.5
         
    
    
        UTF-8
        1.8
        1.3.2
        2.0.2
        1.2.5
        8.0.26
        1.1.10
        3.4.0
        2.7.0
        0.9.0
        2.9.7
        1.9.3
    
    
    
        
            
            
                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
        

        
            org.springframework.boot
            spring-boot-devtools
            true
        
        
            org.projectlombok
            lombok
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
    


mian.js:
Spring+RestFul+Vue多表(学校,老师,类型)_第1张图片

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from "axios"
axios.defaults.baseURL="http://localhost:8081"
Vue.prototype.$http= axios
Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

后端项目结构:
Spring+RestFul+Vue多表(学校,老师,类型)_第2张图片
学校增删改查:
JavaBean:

package com.czxy.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "t_school")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class School {
     @Id
    private Integer id;
     private String school_name;
}

dao层:

package com.czxy.dao;

import com.czxy.domain.School;
import tk.mybatis.mapper.common.Mapper;
@org.apache.ibatis.annotations.Mapper
public interface SchoolMapper extends Mapper<School> {
}

service层:

package com.czxy.service;

import com.czxy.domain.School;

import java.util.List;

public interface SchoolService {
    List<School> selectAll();

    School selectById(String id);

    Boolean edit(School school);

    Boolean Delete(String id);

    Boolean add(School school);
}

service实例类:

package com.czxy.service.impl;

import com.czxy.dao.SchoolMapper;
import com.czxy.domain.School;
import com.czxy.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SchoolServiceImpl implements SchoolService {
    @Autowired
    private SchoolMapper schoolMapper;

    @Override
    public List<School> selectAll() {
        return schoolMapper.selectAll();
    }

    @Override
    public School selectById(String id) {
        return schoolMapper.selectByPrimaryKey(id);
    }

    @Override
    public Boolean edit(School school) {
        return schoolMapper.updateByPrimaryKey(school)==1;
    }

    @Override
    public Boolean Delete(String id) {
        return schoolMapper.deleteByPrimaryKey(id)==1;
    }

    @Override
    public Boolean add(School school) {
        return schoolMapper.insert(school)==1;
    }
}

controller层:

package com.czxy.controller;

import com.czxy.domain.School;
import com.czxy.service.SchoolService;
import com.czxy.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/school")
public class SchoolController {
    @Autowired
    private SchoolService schoolService;

    @GetMapping
    public BaseResult selectAll() {
        List<School> list = schoolService.selectAll();
        if (list != null) {
            return BaseResult.ok("查询成功", list);
        }
        return BaseResult.error("查询失败");
    }

    @GetMapping("/selectById/{id}")
    public BaseResult selectById(@PathVariable("id") String id) {
        System.out.println(id);
        School school = schoolService.selectById(id);
        if (school != null) {
            return BaseResult.ok("查询成功", school);
        }
        return BaseResult.error("查询失败");
    }

    @PutMapping
    public BaseResult edit(@RequestBody School school) {
        Boolean f = schoolService.edit(school);
        if (f) {
            return BaseResult.ok("修改成功");
        }
        return BaseResult.error("修改失败");
    }

    @DeleteMapping("/del/{id}")
    public BaseResult Delete(@PathVariable("id") String id) {
        Boolean f = schoolService.Delete(id);
        if (f) {
            return BaseResult.ok("删除成功");
        }
        return BaseResult.error("删除失败");
    }
    @PostMapping
    public BaseResult add(@RequestBody School school) {
        Boolean f = schoolService.add(school);
        if (f) {
            return BaseResult.ok("添加成功");
        }
        return BaseResult.error("添加失败");
    }
}

前端结构:
Spring+RestFul+Vue多表(学校,老师,类型)_第3张图片
App.vue:




router->index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import( /* webpackChunkName: "about" */ '../views/About.vue')
  }, {
    path: '/school',
    name: 'School',
    component: () => import( /* webpackChunkName: "about" */ '../views/SchoolList.vue')
  }, {
    path: '/TeacherEdit/:id',
    name: 'TeacherEdit',
    component: () => import( /* webpackChunkName: "about" */ '../views/TeacherEdit.vue')
  }, {
    path: '/TeacherAdd',
    name: 'TeacherAdd',
    component: () => import( /* webpackChunkName: "about" */ '../views/TeacherAdd.vue')
  }, {
    path: '/teacher',
    name: 'Teacher',
    component: () => import( /* webpackChunkName: "about" */ '../views/TeacherList.vue')
  }, {
    path: '/schoolAdd',
    name: 'schoolAdd',
    component: () => import( /* webpackChunkName: "about" */ '../views/schoolAdd.vue')
  }, {
    path: '/schoolEdit/:id',
    name: 'schoolEdit',
    component: () => import( /* webpackChunkName: "about" */ '../views/schoolEdit.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

SchoolList.vue:






schoolEdit.vue:






schoolAdd.vue:






学校的增删改查就到这了

接下来是老师的多条件分页查询,修改,增加,批量删除:

controller:

package com.czxy.controller;

import com.czxy.domain.Teacher;
import com.czxy.service.TeacherService;
import com.czxy.vo.BaseResult;
import com.czxy.vo.TeacherVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @PostMapping("/condition/{pageNum}/{pageSize}")
    public BaseResult condition(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize,
            @RequestBody TeacherVo teacherVo) {
        System.out.println(teacherVo);
        PageInfo<Teacher> pageInfo = teacherService.condition(pageSize, pageNum, teacherVo);
        return BaseResult.ok("查询成功", pageInfo);
    }

    @GetMapping("/selectById/{id}")
    public BaseResult selectById(@PathVariable("id") String id) {
        Teacher teacher = teacherService.selectById(id);
        if (teacher != null) {
            return BaseResult.ok("查询成功", teacher);
        }
        return BaseResult.error("查询失败");
    }

    @PutMapping
    public BaseResult edit(@RequestBody Teacher teacher) {
        Boolean f = teacherService.edit(teacher);
        if (f) {
            return BaseResult.ok("修改成功");
        }
        return BaseResult.error("修改失败");
    }

    @DeleteMapping("/del/{id}")
    public BaseResult Delete(@PathVariable("id") String id) {
        Boolean f = teacherService.Delete(id);
        if (f) {
            return BaseResult.ok("删除成功");
        }
        return BaseResult.error("删除失败");
    }

    @DeleteMapping("/dels/{delids}")
    public BaseResult Deletes(@PathVariable("delids") String delids) {
        String[] split = delids.split(",");
        Boolean f = true;
        for (String s : split) {
            f = teacherService.Delete(s);
        }
        if (f) {
            return BaseResult.ok("删除成功");
        }
        return BaseResult.error("删除失败");

    }

    @PostMapping
    public BaseResult add(@RequestBody Teacher teacher) {
        Boolean f = teacherService.add(teacher);
        if (f) {
            return BaseResult.ok("添加成功");
        }
        return BaseResult.error("添加失败");
    }
}



-----------------------------------------------------------------



package com.czxy.controller;

import com.czxy.domain.T_Type;
import com.czxy.service.T_typeService;
import com.czxy.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/t_type")
public class T_typeController {
    @Autowired
    private T_typeService t_typeService;
    @GetMapping
    public BaseResult selectAll(){
        List<T_Type> list = t_typeService.selectAll();
        if (list != null) {
            return BaseResult.ok("查询成功", list);
        }
        return BaseResult.error("查询失败");
    }
}

dao层:

package com.czxy.dao;

import com.czxy.domain.Teacher;
import tk.mybatis.mapper.common.Mapper;
@org.apache.ibatis.annotations.Mapper
public interface TeacherMapper extends Mapper<Teacher> {
}
------------------------------------------------------------------------------------
package com.czxy.dao;

import com.czxy.domain.T_Type;
import tk.mybatis.mapper.common.Mapper;
@org.apache.ibatis.annotations.Mapper
public interface T_typeMapper extends Mapper<T_Type> {
}

domain(JavaBean):

package com.czxy.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Table(name = "t_teacher")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    //   CREATE TABLE `t_teacher`  (
//            `id` int(11) NOT NULL AUTO_INCREMENT,
//  `teacher_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
//  `pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
//  `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
//  `salary` decimal(10, 2) NULL DEFAULT NULL,
//  `type_id` int(11) NULL DEFAULT NULL,
//  `school_id` int(11) NULL DEFAULT NULL,
//  `hire_date` date NULL DEFAULT NULL,
//  `remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
//    PRIMARY KEY (`id`) USING BTREE
//) ;
    @Id
    private Integer id;
    private String teacher_name;
    private String pwd;
    private String sex;
    private Double salary;
    private Integer type_id;
    private Integer school_id;
    @JsonFormat(pattern = "yyyy-MM-dd" ,timezone = "GMT+8")
    private Date hire_date;
    private String remark;
    private School school;
    private T_Type t_type;
}
==========================================================================
package com.czxy.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "t_type")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class T_Type {
    //    CREATE TABLE `t_type`  (
//            `id` int(11) NOT NULL AUTO_INCREMENT,
//  `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
//    PRIMARY KEY (`id`) USING BTREE
//);
    @Id
    private Integer id;
    private String city;
}

teacherVo(条件查询):

package com.czxy.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TeacherVo {
    private String t_Name;
    private String school;
    private String minSalary;
    private String maxSalary;
    private String startTime;
    private String endTime;
}

service:

package com.czxy.service;

import com.czxy.domain.Teacher;
import com.czxy.vo.TeacherVo;
import com.github.pagehelper.PageInfo;

public interface TeacherService {
    PageInfo<Teacher> condition(Integer pageSize, Integer pageNum, TeacherVo teacherVo);

    Teacher selectById(String id);

    Boolean edit(Teacher teacher);

    Boolean Delete(String id);

    Boolean add(Teacher teacher);
}


==============================================================================================


package com.czxy.service;

import com.czxy.domain.T_Type;

import java.util.List;

public interface T_typeService {
    List<T_Type> selectAll();
}

serviceImpl实现类

package com.czxy.service.impl;

import com.czxy.dao.SchoolMapper;
import com.czxy.dao.T_typeMapper;
import com.czxy.dao.TeacherMapper;
import com.czxy.domain.Teacher;
import com.czxy.service.TeacherService;
import com.czxy.vo.TeacherVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private T_typeMapper t_typeMapper;
    @Autowired
    private SchoolMapper schoolMapper;

    @Override
    public PageInfo<Teacher> condition(Integer pageSize, Integer pageNum, TeacherVo teacherVo) {
        Example example = new Example(Teacher.class);
        Example.Criteria criteria = example.createCriteria();
        if (teacherVo.getT_Name() != null && !"".equals(teacherVo.getT_Name())) {
            criteria.andLike("teacher_name", "%"+teacherVo.getT_Name()+"%");
        }
        if (teacherVo.getSchool() != null && !"".equals(teacherVo.getSchool())) {
            criteria.andEqualTo("school_id", teacherVo.getSchool());
        }
        if (teacherVo.getMinSalary() != null && !"".equals(teacherVo.getMinSalary())) {
            criteria.andGreaterThanOrEqualTo("salary", teacherVo.getMinSalary());
        }
        if (teacherVo.getMaxSalary() != null && !"".equals(teacherVo.getMaxSalary())) {
            criteria.andLessThanOrEqualTo("salary", teacherVo.getMaxSalary());
        }
        if (teacherVo.getStartTime() != null && !"".equals(teacherVo.getStartTime())) {
            criteria.andGreaterThanOrEqualTo("hire_date", teacherVo.getStartTime());
        }
        if (teacherVo.getEndTime() != null && !"".equals(teacherVo.getEndTime())) {
            criteria.andLessThanOrEqualTo("hire_date", teacherVo.getEndTime());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Teacher> teachers = teacherMapper.selectByExample(example);
        for (Teacher teacher : teachers) {
            teacher.setSchool(schoolMapper.selectByPrimaryKey(teacher.getSchool_id()));
            teacher.setT_type(t_typeMapper.selectByPrimaryKey(teacher.getType_id()));
        }

        return new PageInfo<>(teachers);
    }

    @Override
    public Teacher selectById(String id) {
        return teacherMapper.selectByPrimaryKey(id);
    }

    @Override
    public Boolean edit(Teacher teacher) {
        return teacherMapper.updateByPrimaryKey(teacher)==1;
    }

    @Override
    public Boolean Delete(String id) {
        return teacherMapper.deleteByPrimaryKey(id)==1;
    }

    @Override
    public Boolean add(Teacher teacher) {
        return teacherMapper.insert(teacher)==1;
    }
}
======================================================================
package com.czxy.service.impl;

import com.czxy.dao.T_typeMapper;
import com.czxy.domain.T_Type;
import com.czxy.service.T_typeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class T_typeServiceImpl implements T_typeService {
    @Autowired
    private T_typeMapper t_typeMapper;

    @Override
    public List<T_Type> selectAll() {
        return t_typeMapper.selectAll();
    }
}

前端:

teacherList.vue






teacherEidt.vue:






teacherAdd.vue:






到这里就已经结束了,希望对大家有帮助

你可能感兴趣的:(spring,restful,vue.js)