学习尚硅谷的谷粒学院的一些笔记,主要是谷粒学院的笔记不好翻我这里重新整理一下
这里跳过了建表分析的,感觉应该是很重要的一步,一个项目要花很多时间在建库建表
数据库设计规约
以下规约只针对本模块,更全面的文档参考《阿里巴巴Java开发手册》: 五、MySQL数据库
1、库名与应用名称尽量一致
2、表名、字段名必须使用小写字母或数字,禁止出现数字开头,
3、表名不使用复数名词
4、表的命名最好是加上“业务名称_表的作用”。如,edu_teacher
5、表必备三字段:id, gmt_create, gmt_modified
说明:
其中 id 必为主键,类型为 bigint unsigned、单表时自增、步长为 1。
(如果使用分库分表集群部署,则id类型为verchar,非自增,业务中使用分布式id生成器)
gmt_create, gmt_modified 的类型均为 datetime 类型,前者现在时表示主动创建,后者过去分词表示被 动更新。
6、单表行数超过 500 万行或者单表容量超过 2GB,才推荐进行分库分表。 说明:如果预计三年后的数据量根本达不到这个级别,请不要在创建表时就分库分表。
7、表达是与否概念的字段,必须使用 is_xxx 的方式命名,数据类型是 unsigned tinyint (1 表示是,0 表示否)。
说明:任何字段如果为非负数,必须是 unsigned。
注意:POJO 类中的任何布尔类型的变量,都不要加 is 前缀。数据库表示是与否的值,使用 tinyint 类型,坚持 is_xxx 的 命名方式是为了明确其取值含义与取值范围。
正例:表达逻辑删除的字段名 is_deleted,1 表示删除,0 表示未删除。
8、小数类型为 decimal,禁止使用 float 和 double。 说明:float 和 double 在存储的时候,存在精度损失的问题,很可能在值的比较时,得到不 正确的结果。如果存储的数据范围超过 decimal 的范围,建议将数据拆成整数和小数分开存储。
9、如果存储的字符串长度几乎相等,使用 char 定长字符串类型。
10、varchar 是可变长字符串,不预先分配存储空间,长度不要超过 5000,如果存储长度大于此值,定义字段类型为 text,独立出来一张表,用主键来对应,避免影响其它字段索 引效率。
11、唯一索引名为 uk_字段名;普通索引名则为 idx_字段名。
说明:uk_ 即 unique key;idx_ 即 index 的简称
12、不得使用外键与级联,一切外键概念必须在应用层解决。外键与级联更新适用于单机低并发,不适合分布式、高并发集群;级联更新是强阻塞,存在数据库更新风暴的风险;外键影响数据库的插入速度。
模块说明
环境搭建
创建一个Spring Boot 的父工程,版本使用:2.2.1.RELEASE
父工程pom.xml里面添加
<packaging>pom</packaging>
在pom.xml中添加依赖的版本
删除pom.xml中的内容
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
添加 确定依赖的版本
这里我换了swagger和mybatisplus的版本
<properties>
<java.version>1.8</java.version>
<guli.version>0.0.1-SNAPSHOT</guli.version>
<mybatis-plus.version>3.4.2</mybatis-plus.version>
<velocity.version>2.0</velocity.version>
<swagger.version>2.9.2</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.11</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>
</properties>
配置 锁定依赖的版本
<dependencyManagement>
<dependencies>
<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>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<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>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<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>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<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>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<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>${aliyun-java-vod-upload.version}</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>
删除src目录
搭建service模块
在父工程guli-parent下面创建模块service
添加模块类型是pom
因为service下面还要再建子模块的
<artifactId>service</artifactId>
<packaging>pom</packaging>
添加项目需要的依赖
注意把springcloud的一些依赖给注释掉
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
删掉service的src
搭建service-edu模块
在父工程service模块下面创建子模块service-edu,也是普通的maven项目
resources目录下创建文件 application.yml
#服务端口
server:
port: 8080
spring:
application:
name: service-edu
profiles:
active: dev
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/gulischool?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
创建MP代码生成器
在test/java目录下创建包com.atguigu.eduservice,创建代码生成器:CodeGenerator.java
package com.atguigu.demo;
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;
public class CodeGenerator {
@Test
public void run() {
AutoGenerator mpg = new AutoGenerator();
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir("D:\\ideacode\\guli_parent\\service\\service_edu" + "/src/main/java");
gc.setAuthor("dyk");
gc.setOpen(false);
gc.setFileOverride(false);
gc.setServiceName("%sService");
gc.setIdType(IdType.ASSIGN_ID);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/gulischool?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
PackageConfig pc = new PackageConfig();
pc.setModuleName("eduservice");
pc.setParent("com.atguigu");
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
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);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
mpg.execute();
}
}
创建SpringBoot配置类
注意启动类的位置
@SpringBootApplication
public class EduApplication {
public static void main(String[] args) {
SpringApplication.run(EduApplication.class,args);
}
}
创建SpringBoot配置类
@Configuration
@MapperScan("com.atguigu.eduservice.mapper")
public class EduConfig {
}
统一返回的json时间格式
#返回json的全局时间格式
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
编写eduteacher后台管理api接口
查询所有
@RestController
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
@Autowired
private EduTeacherService eduTeacherService;
@GetMapping("findAll")
public List<EduTeacher>findAllTeacher(){
List<EduTeacher> list = eduTeacherService.list(null);
return list;
}
}
逻辑删除讲师
@DeleteMapping("{id}")
public boolean removeTeacher(@PathVariable("id") String id){
boolean flag = eduTeacherService.removeById(id);
return flag;
}
跨域
浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域 。前后端分离开发中,需要考虑ajax跨域的问题。 这里我们可以从服务端解决这个问题
配置
在Controller类上添加注解
@CrossOrigin
或者跨域添加配置类
整合swagger2
创建common模块
在guli-parent下创建模块common
在common中引入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
在模块service-base中,创建swagger的配置类
创建包com.atguigu.servicebase.config,创建类SwaggerConfig
package com.atguigu.servicebase;
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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@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();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("网站-课程中心API文档")
.description("本文档描述了课程中心微服务接口定义")
.version("1.0")
.contact(new Contact("dyk", "https://blog.csdn.net/qq_44866153", "1106649325@qq.com"))
.build();
}
}
在模块service模块中引入service-base
因为要使用swagger
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>service_base</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
在service-edu启动类上添加注解
因为swaggerconfig使用了@Configuration,要使启动类扫描到,要加注解,不然只扫描当前包下的内容
@SpringBootApplication
@ComponentScan(basePackages = {"com.atguigu"})
public class EduApplication {
public static void main(String[] args) {
SpringApplication.run(EduApplication.class,args);
}
}
swagger访问地址
http://localhost:8001/swagger-ui.html
统一返回数据格式
项目中我们会将响应封装成json返回,一般我们会将所有接口的数据格式统一, 使前端(iOS Android, Web)对数据的操作更一致、轻松。 一般情况下,统一返回数据格式没有固定的格式,只要能描述清楚返回的数据状态以及要返回的具体数据就可以。但是一般会包含状态码、返回消息、数据这几部分内容
{
"success": 布尔,
"code": 数字,
"message": 字符串,
"data": HashMap
}
在common模块下创建子模块common-utils
创建接口定义返回码
package com.atguigu.commonutils;
public interface ResultCode {
public static Integer SUCCESS = 20000;
public static Integer ERROR = 20001;
}
创建统一结果返回类
构造方法私有,是为了让别人无法new对象 方法返回this,返回的是当前类对象,以后返回结果可以链式调用
package com.atguigu.commonutils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class ResultVo {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
private ResultVo(){}
public static ResultVo ok(){
ResultVo resultVo=new ResultVo();
resultVo.setSuccess(true);
resultVo.setCode(ResultCode.SUCCESS);
resultVo.setMessage("成功");
return resultVo;
}
public static ResultVo error(){
ResultVo resultVo=new ResultVo();
resultVo.setSuccess(false);
resultVo.setCode(ResultCode.ERROR);
resultVo.setMessage("失败");
return resultVo;
}
public ResultVo success(Boolean success){
this.setSuccess(success);
return this;
}
public ResultVo message(String message){
this.setMessage(message);
return this;
}
public ResultVo code(Integer code){
this.setCode(code);
return this;
}
public ResultVo data(String key,Object value){
this.data.put(key,value);
return this;
}
public ResultVo data(Map<String,Object> map){
this.setData(map);
return this;
}
}
统一返回结果使用
在service模块中添加common_utils依赖
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>common_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
修改Controller中的返回结果
@ApiOperation(value = "所有讲师列表")
@GetMapping("/findAll")
public ResultVo findAllTeacher(){
List<EduTeacher> list = eduTeacherService.list(null);
return ResultVo.ok().data("items",list);
}
@ApiOperation(value = "根据ID删除讲师")
@DeleteMapping("{id}")
public ResultVo removeTeacher(@PathVariable("id") String id){
boolean flag = eduTeacherService.removeById(id);
if(flag){
return ResultVo.ok();
}
else{
return ResultVo.error();
}
}
讲师分页功能
分页插件
在配置类 EduConfig添加
新版
@Configuration
@MapperScan("com.atguigu.eduservice.mapper")
public class EduConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
旧版
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
讲师分页Controller
@ApiOperation(value = "分页查询讲师")
@ApiImplicitParams({
@ApiImplicitParam(name="current",value = "当前页"),
@ApiImplicitParam(name="limit",value = "每页记录")
})
@GetMapping("/pageTeacher/{current}/{limit}")
public ResultVo pageListTeacher(@PathVariable Long current,@PathVariable Long limit){
Page<EduTeacher> teacherPage =new Page<>(current,limit);
eduTeacherService.page(teacherPage,null);
long total = teacherPage.getTotal();
List<EduTeacher> records = teacherPage.getRecords();
Map map=new HashMap();
map.put("total",total);
map.put("rows",records);
return ResultVo.ok().data(map);
}
条件查询带分页方法
根据讲师名称name,讲师头衔level、讲师入驻时间gmt_create(时间段)查询 在entity下面新建一个vo包,创建TeacherQueryVo
package com.atguigu.eduservice.entity.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "Teacher查询对象", description = "讲师查询对象封装")
public class TeacherQueryVo {
@ApiModelProperty(value = "教师名称,模糊查询")
private String name;
@ApiModelProperty(value = "头衔 1高级讲师 2首席讲师")
private Integer level;
@ApiModelProperty(value = "查询开始时间", example = "2019-01-01 10:10:10")
private String begin;
@ApiModelProperty(value = "查询结束时间", example = "2019-12-01 10:10:10")
private String end;
}
带条件分页查询讲师
注意这里条件可以为空,那么就和不带条件一样了,但是要加上 @RequestBody(required = false)否则会报错
@ApiOperation(value = "带条件分页查询讲师")
@ApiImplicitParams({
@ApiImplicitParam(name="current",value = "当前页"),
@ApiImplicitParam(name="limit",value = "每页记录")
})
@PostMapping("pageTeacherCondition/{current}/{limit}")
public ResultVo pageTeacherCondition(@PathVariable Long current, @PathVariable Long limit, @RequestBody(required = false) TeacherQueryVo teacherQueryVo){
Page<EduTeacher> teacherPage =new Page<>(current,limit);
QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
String name = teacherQueryVo.getName();
Integer level = teacherQueryVo.getLevel();
String begin = teacherQueryVo.getBegin();
String end = teacherQueryVo.getEnd();
if(!StringUtils.isEmpty(name)){
wrapper.like("name",name);
}
if(!StringUtils.isEmpty(level)){
wrapper.eq("level",level);
}
if(!StringUtils.isEmpty(begin)){
wrapper.ge("gmt_create", begin);
}
if(!StringUtils.isEmpty(end)){
wrapper.le("gmt_create", end);
}
eduTeacherService.page(teacherPage,wrapper);
long total = teacherPage.getTotal();
List<EduTeacher> records = teacherPage.getRecords();
Map map=new HashMap();
map.put("total",total);
map.put("rows",records);
return ResultVo.ok().data(map);
}
添加讲师
在service-base模块中添加 创建包handler,创建自动填充类 MyMetaObjectHandler
注意这里的是实体类的属性名字而不是数据库的字段名字
package com.atguigu.servicebase.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 {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("gmtCreate",new Date(),metaObject);
this.setFieldValByName("gmtModified",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("gmtModified",new Date(),metaObject);
}
}
在实体类添加自动填充注解
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
添加讲师controller
@PostMapping("addTeacher")
public ResultVo addTeacher(@RequestBody EduTeacher eduTeacher){
boolean save = eduTeacherService.save(eduTeacher);
if(save){
return ResultVo.ok();
}else {
return ResultVo.error();
}
}
根据id查询 controller
@ApiOperation(value = "根据讲师id进行查询")
@ApiImplicitParam(name="id",value = "讲师id",dataType = "string")
@GetMapping("/{id}")
public ResultVo getTeacher(@PathVariable String id){
EduTeacher eduTeacher = eduTeacherService.getById(id);
return ResultVo.ok().data("teacher",eduTeacher);
}
根据id修改 controller
@ApiOperation(value = "讲师修改功能")
@PutMapping("/updateTeacher")
public ResultVo updateTeacher(@RequestBody EduTeacher eduTeacher){
boolean flag=eduTeacherService.updateById(eduTeacher);
if(flag){
return ResultVo.ok();
}
else{
return ResultVo.error();
}
}
统一异常处理
什么是统一异常处理
我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理
创建统一异常处理器
在service-base中创建包ExceptionHandler再创建统一异常处理类GlobalExceptionHandler.java
@ControllerAdvice
public class GloablExceptonHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResultVo error(Exception e){
e.printStackTrace();
return ResultVo.error().message(e.getMessage());
}
}
删除service模块中common_utils的gav坐标
注意这里使用了ResultVo,所有需要service-base引入common_utils的gav坐标,但是在service模块中当时同时引入了两个service-base,common_utils的gav坐标,就会有冲突,所有要删除service模块中common_utils的gav坐标
自定义异常
创建自定义异常类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Api(tags = "自定义异常类")
public class GuliException extends RuntimeException{
@ApiModelProperty(value = "状态码")
private Integer code;
private String msg;
}
添加异常处理方法
@ExceptionHandler(GuliException.class)
@ResponseBody
public ResultVo error(GuliException e){
e.printStackTrace();
return ResultVo.error().code(e.getCode()).message(e.getMsg());
}
业务中需要的位置抛出GuliException
try {
int i=1/0;
}catch (Exception e){
throw new GuliException(20001,"执行了自定义异常");
}
日志
配置日志级别
日志记录器(Logger)的行为是分等级的。如下表所示: 分为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL 默认情况下,spring boot从控制台打印出来的日志级别只有INFO及以上级别,可以配置日志级别
# 设置日志级别
logging.level.root=WARN
这种方式只能将日志打印在控制台上
配置logback日志
删除application.yml中原有的mybatisplus日志配置,不然有冲突会报错 resources 中创建 logback-spring.xml
日后根据自己情况修改日志打印的位置,和包名
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="10 seconds">
<contextName>logback</contextName>
<property name="log.path" value="D:/java项目/gulischool/edu" />
<property name="CONSOLE_LOG_PATTERN"
value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/log_info.log</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>15</maxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/log_warn.log</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>15</maxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/log_error.log</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>15</maxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<springProfile name="dev">
<logger name="com.guli" level="INFO" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</springProfile>
<springProfile name="pro">
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
</configuration>
将错误日志输出到文件
GlobalExceptionHandler.java 中 类上添加注解 @Slf4j 这个是lombok的注解,用来打印日志用的
异常输出语句 : log.error(e.getMessage());
package com.atguigu.servicebase.exceptionhandler;
import com.atguigu.commonutils.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@Slf4j
public class GloablExceptonHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResultVo error(Exception e){
e.printStackTrace();
return ResultVo.error().message(e.getMessage());
}
@ExceptionHandler(GuliException.class)
@ResponseBody
public ResultVo error(GuliException e){
log.error(e.getMessage());
e.printStackTrace();
return ResultVo.error().code(e.getCode()).message(e.getMsg());
}
}
更详细的记录错误信息
common_utils模块commonutils 创建ExceptionUtil.java工具类
package com.atguigu.commonutils.utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionUtil {
public static String getMessage(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
}
log.error(ExceptionUtil.getMessage(e));
GuliException中创建toString方法,或者直接lombok@tostring
@Override
public String toString() {
return "GuliException{" +
"code=" + code +
", msg='" + msg + '\'' +
'}';
}
es6和vue基础知识点
es6语法新特性博客链接 vue基础知识点博客链接
|