# SpringBoot-MybatisPlus **Repository Path**: xiaoxiunique/SpringBoot-MybatisPlus ## Basic Information - **Project Name**: SpringBoot-MybatisPlus - **Description**: No description available - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2018-08-04 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SpringBoot-MybatisPlus **项目介绍** 使用 个人博客后端: SpringBoot + MybatisPlus + MySql [小西博客](http://www.atom.kim) #### 1.MySql数据源配置 ```yaml # MYSQL DATABASE CONFIG datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://www.atom.kim:3306/xiaoxi?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=GMT username: root password: Welcome_1 type: com.alibaba.druid.pool.DruidDataSource ``` #### 2.MybatisPlus 配置(官方推荐配置) ```yaml #mybatis mybatis-plus: mapper-locations: classpath:/mapper/*Mapper.xml #实体扫描,多个package用逗号或者分号分隔 typeAliasesPackage: com.xx.springboot.entity; com.xx.springboot.Vo # typeEnumsPackage: com.xx.springboot.entity.enums global-config: # 数据库相关配置 db-config: #主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID"; id-type: auto #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断" field-strategy: not_empty #驼峰下划线转换 column-underline: true #数据库大写下划线转换 #capital-mode: true #逻辑删除配置 logic-delete-value: 0 logic-not-delete-value: 1 db-type: mysql #刷新mapper 调试神器 refresh: true # 原生配置 configuration: map-underscore-to-camel-case: true cache-enabled: false ``` #### 3.Excel 导出 **http://localhost:8889/export** 程序入口: ExportController ##### excel 导出步骤 - 在com.xx.springboot.export.tpl 文件下, 创建要导出数据的对应的 xls模板文件, 与tpl文件 - 在ExportController 中 查询到将要导出的数据集合 - 定义好输出文件名字, 模板对应的名字, 然后调用工具类方法 ##### 导出Excel的几个关键类文件 - com.xx.springboot.utils.XlsUtils - 加载配置文件, 读取配置文件信息 - com.xx.springboot.controller.ExportController - 控制层方法, 对外提供调用接口 - com.xx.springboot.export.tpl - 要导出文件的配置文件 #### 4.Shiro + VUE + SpringBoot 前后端分离跨域问题 **解决办法** - 前端请求axios设置 ```js //浏览器请求 携带 cookie axios.defaults.withCredentials = true ``` - SpringBoot 配置跨域请求头 ```java /** *

* 配置跨域访问 *

*/ @Configuration public class WebCorsConfig { @Bean public WebMvcConfigurer corsConfigurer(){ return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders("*") .allowedMethods("*") .allowCredentials(true) .allowedOrigins("*"); } }; } } ``` #### 5.jenkins自动化部署 解决jenkins启动完毕后, 会自动删除掉所有的衍生进程, 导致spring boot应用通过 `nohup java -jar project.jar > log &` 命令jenkins自动化部署之后, 会被删除. **解决方案** 在Exec Shell上方添加如下代码 ``` BUILD_ID=DONTKILLME ``` #### 6.解决springboot上传文件的问题 > 描述: springboot每次部署的时候, 都会创建临时目录, 如果这时如果使用相对目录, 那么下一次重新部署之后, 那么文件会找不到 **解决办法** 上传文件的时候上传到固定的问题, 浏览文件的时候, 通过 nginx 代理访问 ```java /** * 上传文件接口 * @param file * @return */ @ResponseBody @RequestMapping(value = "/uploadImage") public ResponseBo uploadImage(@RequestParam("image") MultipartFile file) { if(!file.isEmpty()){ try { Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename())); return ResponseBo.ok(); } catch (IOException e) { e.printStackTrace(); return ResponseBo.error(e.getLocalizedMessage()); } }else { return ResponseBo.error(); } } ``` #### 7.使用@Vaild 进行实体验证 注意事项 > `@NotNull` 和 `@NotEmpty` 和`@NotBlank` 区别 - @NotEmpty 用在集合类上面 - @NotBlank 用在String上面 - @NotNull 用在基本类型上 #### 8.shiro 做认证授权 > 表结构 ```sql -- create role table drop table if exists role; create table role ( id int primary key auto_increment not null, name varchar(11) not null, create_time TIMESTAMP not null ); insert into role(name, create_time) value('superAdmin', now()); insert into role(name, create_time) value('admin', now()); insert into role(name, create_time) value('user', now()); -- 创建用户关系表 drop table if exists user_role; create table user_role ( id int primary key auto_increment not null, user_id int not null, role_id int not null ); insert into user_role(user_id, role_id) value (3, 1); -- create permission table drop table if exists permission; create table permission ( id int primary key auto_increment not null, name varchar(11) not null, create_time TIMESTAMP ); insert into permission(name, create_time) values ('select', now()), ('update', now()), ('insert', now()), ('delete', now()); drop table if exists role_permission; create table role_permission ( id int primary key auto_increment not null, role_id int not null, permission_id int not null ); insert into role_permission(role_id, permission_id) values (1, 1), (1, 2), (1, 3), (1, 4); ``` > mybatis 一对多查询语句 ```xml ``` > mybatis-plus 排除对应的列 ```java q.excludeColumns(User.class, "roleList"); ``` #### 9.spring boot, 发送邮件 > 引入依赖 ```xml org.springframework.boot spring-boot-starter-mail ``` >YAML 配置 ```yaml # mail configuration mail: host: smtp.163.com username: xxxx@163.com password: xxxxx properties: mail: smtp: auth: true starttls: enable: true required: true ``` > 控制层代码 ```java /** * 发送简单邮件 * @return */ @ResponseBody @RequestMapping("sendSimpleMail") public ResponseBo sendSimpleEmail() { try { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo("929746602@qq.com"); message.setSubject("一封简单的邮件"); message.setText("使用spring boot发送简单邮件"); javaMailSender.send(message); return ResponseBo.ok("邮件发送成功"); } catch (MailException e) { return ResponseBo.error("邮件发送失败"); } } ``` #### 10. 自定义注解,实现方法运行时间记录 > 注解类 ```java /** * @author xiaoxi * @descrition 日志注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Log { String value() default ""; } ``` > @Target 这个注解就是表明该注解类能够作用的范围,也就是能够注解在哪,比如 类、方法、参数等 下面是他的一些参数: - `@Target(ElementType.TYPE)` //接口、类、枚举、注解 - `@Target(ElementType.FIELD)` //字段、枚举的常量 - `@Target(ElementType.METHOD)` //方法 - `@Target(ElementType.PARAMETER)` //方法参数 - `@Target(ElementType.CONSTRUCTOR)` //构造函数 - `@Target(ElementType.LOCAL_VARIABLE)`//局部变量 - `@Target(ElementType.ANNOTATION_TYPE)`//注解 - `@Target(ElementType.PACKAGE)` ///包 里面的参数是可以多选的,使用方法比如@Target({ElementType.METHOD,ElementType.TYPE})。 > @Retention 这个注解是保留说明,也就是表明这个注解所注解的类能在哪里保留,他有三个属性值: `RetentionPolicy.SOURCE` —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略 `RetentionPolicy.CLASS` —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略 `RetentionPolicy.RUNTIME` —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用。 从上面可以看出一般使用的事第三个属性,其余两个属性,说实话 我也不清楚什么情况下使用这两种。 #### 11.Servlet 生命周期 - 容器加载类, 调用servlet的无参数构造函数, 并调用servlet的init() 方法, 从而初始化servlet - init() 方法(开发人员可以覆盖) 在servlet一生中只调用一次, 往往在servlet为客户请求提供服务之前调用 - init() 方法使servlet可以访问ServletConfig 和 ServletContext对象, servlet需要从这些对象得到有关servlet配置和web应用的信息 - 容器通过调用servlet的destroy方法来结束servlet的生命 - servlet一生的大多数时间都是在为某个客户请求运行service方法. - 对servlet的每个请求都在独立的线程中运行!任何特定的servlet类都只是一个实例. - 你的servlet一般都会扩展javax.servlet.http.HttpServlet, 并由此集成service()方法的一个实现, 它去一个HttpServletRequest和一个HttpServletResponse作为参数 - HttpServlet扩展了javax.servlet.GenericServlet, 这是一个抽象类, 实现了大多数基本的servlet方法. - GenericServlet 实现了servlet 接口. - Servlet相关的类(除了与JSP有关的类) 都在以下面的两个包中: javax.servlet 或javax.servlet.http. - 可以覆盖init()方法, 而且必须覆盖一个服务方法(doGet(), doPost() 等) #### 12.spring boot 中的@RestController 注解 > 源码 ```java @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) * @since 4.0.1 */ @AliasFor(annotation = Controller.class) String value() default ""; } ``` 实际上@RestController 注解是结合了 spring mvc 中的@controller + @responseBody 注解, 所以在控制层上加上@RestController 注解之后, 方法上就不需要再单独的添加@responseBody 注解了 #### 13.idea 插件 **Free Mybatis plugin** 可以直接进入mapper.xml文件中