day2
0.第二天任务:
1.完成后端的项目环境搭建
2.完成讲师模块的接口并完成测试
3..完成全局异常处理
1.环境搭建
1.项目名为guli_parent4
2.项目有两个子模块 common 和 service(暂时)
3.common的作用是对公共的代码或者依赖进行复用,有两个字模块,一个是common_utils和service_base
4.service是完成接口,今天需要完成讲师模块的接口所有创建service-edu模块
2.在guli_parent的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>
<groupId>com.guli</groupId>
<artifactId>guli_parent</artifactId>
<packaging>pom</packaging>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>service</module>
<module>common</module>
</modules>
<name>guli_parent</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<guli.version>0.0.1-SNAPSHOT</guli.version>
<mybatis-plus.version>3.0.5</mybatis-plus.version>
<velocity.version>2.0</velocity.version>
<swagger.version>2.7.0</swagger.version>
<aliyun.oss.version>2.8.3</aliyun.oss.version>
<jodatime.version>2.10.1</jodatime.version>
<poi.version>3.17</poi.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-io.version>2.6</commons-io.version>
<httpclient.version>4.5.1</httpclient.version>
<jwt.version>0.7.0</jwt.version>
<aliyun-java-sdk-core.version>4.3.3</aliyun-java-sdk-core.version>
<aliyun-sdk-oss.version>3.1.0</aliyun-sdk-oss.version>
<aliyun-java-sdk-vod.version>2.15.2</aliyun-java-sdk-vod.version>
<aliyun-java-vod-upload.version>1.4.14</aliyun-java-vod-upload.version>
<aliyun-sdk-vod-upload.version>1.4.11</aliyun-sdk-vod-upload.version>
<fastjson.version>1.2.28</fastjson.version>
<gson.version>2.8.2</gson.version>
<json.version>20170516</json.version>
<commons-dbutils.version>1.7</commons-dbutils.version>
<canal.client.version>1.1.0</canal.client.version>
<docker.image.prefix>zx</docker.image.prefix>
<cloud-alibaba.version>0.2.2.RELEASE</cloud-alibaba.version>
<spring-boot.version>2.2.1.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--Spring Cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--mybatis-plus 持久层-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency>
<!--日期时间工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime.version}</version>
</dependency>
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<!--xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<!--commons-io-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!--aliyun-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${aliyun-java-sdk-core.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun-sdk-oss.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
<version>${aliyun-java-sdk-vod.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.aliyun</groupId>-->
<!-- <artifactId>aliyun-java-vod-upload</artifactId>-->
<!-- <version>1.4.11</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-sdk-vod-upload</artifactId>
<version>${aliyun-sdk-vod-upload.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>${commons-dbutils.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.client</artifactId>
<version>${canal.client.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.guli.guli_parent.GuliParentApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.讲师模块接口的创建
1.讲师模块的接口在service-edu实现
2.在service的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>guli_parent</artifactId>
<groupId>com.guli</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.guli</groupId>
<artifactId>service</artifactId>
<packaging>pom</packaging>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>service-edu</module>
</modules>
<dependencies>
<!--<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId></dependency>-->
<!--hystrix依赖,主要是用 @HystrixCommand -->
<!--<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>-->
<!--服务注册-->
<!-- <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>-->
<!--服务调用-->
<!-- <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>-->
<!--导入公共的依赖-->
<dependency>
<artifactId>common</artifactId>
<groupId>com.guli</groupId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--导入公共的工具模块-->
<dependency>
<groupId>com.guli</groupId>
<artifactId>common_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--lombok用来简化实体类:需要安装lombok插件-->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!--commons-io-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!--gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
3.使用mybatis_plus自带的代码生成,生成mapper,service和controller简化开发
在测试环境中创建一个类,复制官网中代码,然后运行
package Code;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;
/**
* @author
* @since 2018/12/13
*/
public class CodeGenerator {
@Test
public void run() {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("mxs");
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ID_WORKER); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(true);//开启Swagger2模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com");
pc.setModuleName("edu"); //模块名
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("edu_teacher");
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
点击运行,生成如下代码(除了vo)
4.为了同一处理结果,在common_utils的com.edu.util包下创建一个R类
package com.edu.utils;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
* @author mxs
* 统一相应结果
*/
@Data
public class R {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "响应码")
private Integer code;
@ApiModelProperty(value = "返回信息")
private String message;
@ApiModelProperty(value = "返回数据")
private HashMap<String,Object> data = new HashMap<>();//注意一定要先初始化这个map,否则报错
//私有空构造方法,防止外部new
private R(){}
/**
* 返回成功
* @return
*/
public static R success(){
R r = new R();
r.setCode(ResultCode.SUCCESS_CODE);
r.setMessage("成功");
r.setSuccess(true);
return r;
}
public static R error(){
R r = new R();
r.setCode(ResultCode.FAIL_CODE);
r.setSuccess(false);
r.setMessage("失败");
return r;
}
/**
* set方法全部的返回值都为this,为了便于链式编程
* 类似于 R.success().message().....
*/
public R success(Boolean success) {
this.success = success;
return this;
}
public R code(Integer code) {
this.code = code;
return this;
}
public R message(String message) {
this.message = message;
return this;
}
public R data(HashMap<String, Object> data) {
this.data = data;
return this;
}
public R data(String key,Object data){
this.data.put(key,data);
return this;
}
}
响应码的接口(为了存放数据,可以使用枚举,但这里暂时使用接口存放数据)
package com.edu.utils;
/**
* @author mxs
* 响应码定义接口
*/
public interface ResultCode {
/**
* 成功响应码
*/
public static final Integer SUCCESS_CODE = 20000;
/**
* 失败响应码
*/
public static final Integer FAIL_CODE = 20001;
}
5.处理更新和插入操作时候gmtCreate和gmtModified字段的自动更新
在common_base中创建一个统一处理的类(在com.edu.config包下)
package com.edu.config.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
*元信息处理
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入操作时候对信息的处理
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
//更新 插入时间和更新时间
this.setFieldValByName("gmtCreate",new Date(),metaObject);
this.setFieldValByName("gmtModified",new Date(),metaObject);
}
/**
* 更新的时候对元信息的处理
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
//更新 更新时间
this.setFieldValByName("gmtModified",new Date(),metaObject);
}
}
6.为了便于测试接口,使用swagger,并在common-base的com.edu.config中配置其相关配置
package com.edu.config;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* swagger测试文档配置类
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 文档测试的配置
*
* @return
*/
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
/**
* 文档信息描述的配置
*
* @return
*/
private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
.title("网站-课程中心API文档")
.description("本文档描述了课程中心微服务接口定义")
.version("1.0")
.contact(new Contact("java", "http://mxs.com", "2426@qq.com"))
.build();
}
}
7.使用了mybatis_plus,需要在servce-edu中配置(主要是为了配置分页模型和删除配置)
package com.edu.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mybatis_plus配置类
*/
@Configuration
@MapperScan("com.edu.mapper")
public class MyBatisConfig {
/**
* 逻辑删除配置
*
* @return
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
/**
* 分页插件配置
*
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
8.service-edu中application.yml的配置
spring:
application:
name: servie-edu
profiles:
active: dev
# 配置数据库
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8
username: root
password: 123456
jackson:
# 配置日期格式
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
#配置mybatisplus的日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#逻辑删除配置
global-config:
db-config:
logic-delete-value: 1
logic-not-delete-value: 0
9.接口开发
package com.edu.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.entity.Teacher;
import com.edu.entity.vo.TeacherQuery;
import com.edu.service.TeacherService;
import com.edu.utils.R;
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.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.websocket.server.PathParam;
import java.util.Date;
import java.util.List;
/**
* <p>
* 讲师 前端控制器
* </p>
* 统一采用restful风格
*
* @author mxs
* @since 2021-10-13
*/
@RestController
@RequestMapping("/edu/teacher")
@Api(tags = "教师管理模块")//描述这个接口
public class TeacherController {
@Autowired
private TeacherService teacherService;
/**
* 找到所有的教师Teacher
*
* @return
*/
@ApiOperation(value = "查找所有教师")//描述这个方法
@GetMapping("findAll")
public R findAll() {
List<Teacher> list = teacherService.list(null);
return R.success().data("items", list);
}
/**
* 根据id删除教师(逻辑删除,将deleted项设为1)
*
* @param id 教师id
* @return 是否删除成功
*/
@ApiOperation(value = "逻辑删除老师")
@DeleteMapping("{id}")
public R removeTeacher(@ApiParam(name = "id", value = "老师id", required = true) //参数的描述
@PathVariable String id) {
boolean b = teacherService.removeById(id);
if (b) {
return R.success().data("isdelete", true).message("删除成功");
}
return R.error().data("isdeleted", false).message("删除失败");
}
/**
* 分页查询教师
*
* @param pageNo 查询页码
* @param limit 每页限制数量
* @return 返回记录数 和 当期页的数据
*/
@GetMapping("/pageListTeacher/{pageNo}/{limit}")
public R pageListTeacher(@PathVariable("pageNo") long pageNo,
@PathVariable("limit") long limit) {
Page<Teacher> page = new Page<>(pageNo, limit);
teacherService.page(page, null);
long total = page.getTotal();
List<Teacher> records = page.getRecords();
return R.success().data("total", total).data("records", records);
}
/**
* 动态查询教师
*
* @param pageNo 查询页码
* @param limit 限制每页数量条数
* @param teacherQuery 条件查询对象
* @return 需要注意,如果参数TeacherQuery没有加@RequestBody,那么请求方式可以是get
* 如果加了注解就必须要用post请求的方式
*/
@PostMapping("/pageListTeacherCondition/{pageNo}/{limit}")
public R pageTeacherCondition(@PathVariable("pageNo") long pageNo,
@PathVariable("limit") long limit,
@RequestBody(required = false) TeacherQuery teacherQuery) {
Page<Teacher> teacherPage = new Page<>(pageNo, limit);
//创建条件查询wrapper对象
QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
//下面是为了动态查询,后面会封装到service中
String id = teacherQuery.getId();
String name = teacherQuery.getName();
Date gmtCreate = teacherQuery.getGmtCreate();
Date gmtModified = teacherQuery.getGmtModified();
if (!StringUtils.isEmpty(id)) {
queryWrapper.eq("id", id);
}
if (!StringUtils.isEmpty(name)) {
queryWrapper.like("name", name);
}
if (!StringUtils.isEmpty(gmtCreate)) {
queryWrapper.gt("gmt_create", gmtCreate);
}
if (!StringUtils.isEmpty(gmtModified)) {
queryWrapper.lt("gmt_modified", gmtModified);
}
//条件查询
teacherService.page(teacherPage, queryWrapper);
//获取数据
List<Teacher> records = teacherPage.getRecords();
long total = teacherPage.getTotal();
return R.success().data("records", records).data("total", total);
}
/**
* 插入新的教师新数据
*
* @param teacher
* @return
*/
@PostMapping("/save")
public R save(@RequestBody Teacher teacher) {
boolean save = teacherService.save(teacher);
if (save) {
return R.success().data("save", save);
} else {
return R.error().data("sace", save);
}
}
/**
* 根据id获取教师
*
* @param id 教师id
* @return
*/
@GetMapping("{id}")
public R getTeacher(@PathVariable("id") long id) {
int i = 1 / 0;
Teacher teacher = teacherService.getById(id);
return R.success().data("teacher", teacher);
}
/**
* 根据教师id更新教师数据
*
* @param teacher 更新的教师
* @return
*/
@PostMapping("/updateTeacher")
public R updateTeacherById(@RequestBody Teacher teacher) {
boolean b = teacherService.updateById(teacher);
if (b) {
return R.success().data("change:", b);
} else {
return R.error().data("change:", b);
}
}
}
3.全局异常处理,应该在common_base中的,但是无法扫描到其他模块(正在排查原因)
package com.edu.config.exceptionHandler;
import com.edu.utils.R;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 全局异常处理
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public R error(Exception e){
e.getStackTrace();
return R.error().message("使用了全局异处理...");
}
}
4.测试
启动类
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
//为了扫描其他模块的包
@ComponentScan("com.edu")
@EnableSwagger2
public class EduApplication {
public static void main(String[] args) {
SpringApplication.run(EduApplication.class,args);
}
}
swagger测试