SpringBoot
- 掌握基于SpringBoot框架的开发步骤
- 熟练使用SpringBoot配置文件修改服务器配置
- 掌握基于SpringBoot完成SSM整合,进行项目功能开发
# SpringBoot简介
SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程。
基于SpringMVC框架开发过程:
# 入门案例
# 基于Idea创建SpringBoot项目
- 创建空项目
- 创建模块
注意
模块创建完成后,需要等待几分钟,此时Maven需要从远程仓库下载SpringBoot框架所需依赖包。
- 初始化模块目录结构
安装下图删除暂时无用文件,修改相关类名
- 开发控制器类
package com.itheima.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable("id") Integer id) {
System.out.println("id ==> " + id);
return "hello, spring boot!";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- 运行
Application
类
最简SpringBoot程序所包含的基础文件:pom.xml和Application
<?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.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.itheima</groupId>
<artifactId>springboot-01-quickstart</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
</plugin>
</plugins>
</build>
</project>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.itheima;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
注意事项
基于Idea开发SpringBoot程序需要确保联网且能够加载到程序框架结构
Spring程序与SpringBoot程序对比
# 基于SpringBoot官网创建项目
# SpringBoot项目快速启动
- 对SpringBoot项目打包(执行Maven构建指令
package
)
- 将target目录下的jar包拷贝到某一目录下
- 打开命令提示符,输入
java -jar springboot-01-quickstart-0.0.1-SNAPSHOT.jar
启动
注意事项
jar包支持命令行java -jar *.jar
启动,需要依赖Maven插件支持,请确认打包时pom.xml文件中是否有SpringBoot对应的Maven插件。
# SpringBoot概述
SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程
- Spring程序缺点
- 配置繁琐
- 依赖设置繁琐
- SpringBoot程序优点
- 自动配置
- 起步依赖(简化依赖配置)
- 辅助功能(内置服务器,...)
# 起步依赖
- starter: SpringBoot中常见项目名称,定义了当前项目使用的所有项目坐标,以达到减少依赖配置的目的
- parent:
- 所有SpringBoot项目要继承的项目,定义了若干个坐标版本号(依赖管理、而非依赖),以达到减少依赖冲突的目的
- *spring-boot-starter-parent(2.5.0)与spring-boot-starter-parent(2.4.6)*的坐标版本有57处不同
- 实际开发:
- 使用任意坐标时,仅书写GAV中的G和A,V由SpringBoot提供
- 如发生坐标错误,再行指定
version
,需要注意版本冲突问题
# 辅助功能
- SpringBoot程序启动
package com.itheima;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
- SpringBoot在创建项目时,采用jar的打包方式
- SpringBoot的引导类是项目的入口,运行
main
方法就可以启动项目 - 使用Maven依赖管理来变更起步依赖项,如将Tomcat更换为Jetty
- Jetty比Tomcat更轻量级,可扩展性更强(相较于Tomcat),谷歌应用引擎(GAE)已经全面切换为Jetty
<?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.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.itheima</groupId>
<artifactId>springboot-01-quickstart</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</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>
</plugin>
</plugins>
</build>
</project>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 基础配置
# 配置文件格式
# 修改服务器端口
假设8080端口被占用了,怎么办?
http://localhost:8080/books/1
----> http://localhost/books/1
SpringBoot提供了多种属性配置方式:
application.properties
server.port=80
1application.yml
server: port: 81
1
2application.yaml
server: port: 82
1
2
# 配置文件自动提示功能消失解决方案
# SpringBoot配置文件的加载顺序
优先级从高至低排序:application.properties -> application.yml -> application.yaml
注意事项
- SpringBoot核心配置文件名为application
- SpringBoot内置属性很多,且所有属性集中在一个文件中,在使用时,通过提示键+关键字来修改属性
# yaml配置文件
YAML(YAML Ain't Markup Language),一种数据序列化格式
- 优点:
- 容器阅读
- 以数据为核心,重数据轻格式
- 容易与脚本语言交互
- 文件扩展名:
- .yml(主流)
- .yaml
# YAML语法规则
- 大小写敏感
- 属性层级关系使用多行描述,每行结尾使用冒号结束
- 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)
- 属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分割)
#
表示注释- 核心规则:数据前面要加空格与冒号隔开
# YAML数组数据
数组数据在数据书写位置的下方使用减号-
作为数据开始符号,每行书写一个数据,减号与数据之间用空格分割。
enterprise:
name: itcast
age: 16
tel: 4006184000
subject:
- Java
- 前端
- 大数据
2
3
4
5
6
7
8
# YAML数据读取
三种方式:
- 使用
@Value
注解读取单个数据,属性名引用方式:${一级属性名.二级属性名...}
- 封装全部数据到
Environment
对象
- 自定义对象封装数据(常用)
package com.itheima.domain;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private Integer age;
private String[] subject;
public Enterprise() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String[] getSubject() {
return subject;
}
public void setSubject(String[] subject) {
this.subject = subject;
}
@Override
public String toString() {
return "Enterprise{" +
"name='" + name + '\'' +
", age=" + age +
", subject=" + Arrays.toString(subject) +
'}';
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
自定义对象封装数据警告解决方案
在pom.xml文件中添加如下依赖坐标:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2
3
4
5
# 多环境开发配置
在实际开发中,项目的开发环境、测试环境、生产环境的配置信息肯定是不同的,就比如数据库,开发、测试、生产数据库肯定是不一样的,那么我们如何解决这样的问题,实现快速切换环境?
# YAML文件多环境配置
# properties文件多环境配置
# 主启动配置文件 application.properties
spring.profiles.active=pro
2
# 生产环境配置文件 application-pro.properties
server.port=83
2
# 测试环境配置文件 application-test.properties
server.port=82
2
# 开发环境配置文件 application-dev.properties
server.port=81
2
# 多环境启动命令格式
打jar包,在使用Maven打包之前需要执行三个操作
- 配置项目文件编码格式
- 备份
*.properties
文件,以免这些文件影响我们的测试效果
- 执行
package
命令前,先使用Maven的clean
命令
使用命令行参数启动SpringBoot应用
java -jar springboot-04-profile-0.0.1-SNAPSHOT.jar --spring.profiles.active=test java -jar springboot-04-profile-0.0.1-SNAPSHOT.jar --server.port=88 java -jar springboot-04-profile-0.0.1-SNAPSHOT.jar --server.port=88 --spring.profiles.active=test
1
2
3
4
5
# Maven与SpringBoot多环境兼容控制
- Maven的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.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.itheima</groupId>
<artifactId>springboot-04-profile</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<!--pom.xml中设置多环境属性-->
<profiles>
<profile>
<id>dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
<profile>
<id>pro</id>
<properties>
<profile.active>pro</profile.active>
</properties>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
</plugin>
</plugins>
</build>
</project>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
- SpringBoot中引用Maven属性
- 执行Maven打包指令:Maven指令执行完毕后,生成了jar包,其中类参与编译,但配置文件并没有参与编译,而是直接复制到包中
解决
对于源码中非java类的资源文件要求其加载Maven中配置的属性,解析${}
占位符
- 对资源文件开启Maven属性占位符的解析,需要引入插件
<?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.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.itheima</groupId>
<artifactId>springboot-04-profile</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<!--pom.xml文件中设置多环境属性-->
<profiles>
<profile>
<id>dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
<profile>
<id>pro</id>
<properties>
<profile.active>pro</profile.active>
</properties>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
</plugin>
<!--使用插件对resources目录下的资源文件开启占位符解析-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<encoding>UTF-8</encoding>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
</build>
</project>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
- Maven打包加载到属性,打包顺利通过
# 配置文件分类
问题:SpringBoot应用的配置文件可以放在项目的哪些地方?
java –jar springboot.jar --spring.profiles.active=test --server.port=85 --server.servlet.context-path=/heima ... ...
SpringBoot中存在4级配置文件
- 第1级:
file
: config/application.yml 最高 - 第2级:
file
: application.yml - 第3级:
classpath
: config/application.yml - 第4级:
classpath
: application.yml 最低
- 第1级:
作用
- 第1级与第2级留着系统打包后设置通用属性
- 第3级与第4级用于系统开发阶段设置通用属性
# 整合第三方技术
# 整合JUnit
# Spring整合JUnit
# SpringBoot整合JUnit
实际上在我们之前创建的SpringBoot项目中,已经给我们集成好了JUnit,即在pom.xml文件中引入的spring-boot-starter-test就已经帮我们整合了JUnit。因此我们只要学习如何在SpringBoot环境下使用它就可以了。
如果你的SpringBoot项目没有引入spring-boot-starter-test或者整合JUnit,你可以按照如下步骤进行:
- 添加整合了junit的起步依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2
3
4
5
- 编写测试类,默认创建完项目会自动生成一个
package com.itheima;
import com.itheima.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Application06Tests {
@Autowired
private BookService bookService;
@Test
public void save() {
bookService.save();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# SpringBoot整合MyBatis
# Spring整合MyBatis回顾
总的来说,需要在SpringConfig
配置类中将我们的数据源配置和MyBatis相关配置加载到容器当中。
SpringConfig
DruidConfig
MyBatisConfig
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@ComponentScan("com.itheima")
@Import({DruidConfig.class, MyBatisConfig.class})
public class SpringConfig {
}
2
3
4
5
6
7
8
9
10
11
12
DruidConfig
:定义数据源,加载properties属性配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/db1
jdbc.username=root
jdbc.password=1234
2
3
4
package com.itheima.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@PropertySource("druid.properties")
public class DruidConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(this.driver);
ds.setUrl(this.url);
ds.setUsername(this.username);
ds.setPassword(this.password);
return ds;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
MyBatisConfig
- 定义
SqlSessionFactoryBean
,将其交给Spring容器管理 - 定义Mapper代理接口扫描路径配置,将其交给Spring容器管理
- 定义
package com.itheima.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.itheima.domain");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.itheima.mapper");
return mapperScannerConfigurer;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# SpringBoot整合MyBatis
- SpringBoot整合Spring,因为SpringBoot底层核心还是Spring,其只不过是简化了Spring的开发和配置,因此不需要整合
- SpringBoot整合SpringMVC,SpringBoot提供了很多起步依赖,在创建SpringBoot项目时,选择spring-boot-starter-web起步依赖即可,也不需要做额外的工作
- SpringBoot整合MyBatis,这是我们本章节需要重点关注的内容,除了引入mybatis-spring-boot-starter起步依赖,还需要做一些配置。
本章节SpringBoot整合MyBatis我们完全采用注解开发,也即是使用MyBatis也基于注解,带着大家回顾下MyBatis注解应该怎么用,在下一章节讲解案例时,基于XML来使用MyBatis,两种方式都给大家讲解一下。
- 创建新模块,选择基于Spring Initializr创建springboot-07-mybatis模块
- 选择当前模块需要的技术集(MyBatis,MySQL)
- 在application.yml文件中配置数据源参数
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver # ?serverTimezone=UTC
url: jdbc:mysql://localhost:3306/db1
username: root
password: 1234
2
3
4
5
6
注意事项
SpringBoot版本低于2.4.3(不含),MySQL驱动版本大于8.0时,需要在url连接串中配置时区,或在MySQL*数据库端配置失去解决此问题
控制台提示
Loading class 'com.mysql.jdbc.Driver'. This is deprecated.
问题,需要将driver-class-name中配置的com.mysql.jdbc.Driver
修改为com.mysql.cj.jdbc.Driver
application.yml文件中
com.mysql.cj.jdbc.Driver
标红问题,修改MySQL依赖坐标的作用范围即可,这个不建议这样操作。
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<!--<scope>runtime</scope>-->
<scope>compile</scope>
</dependency>
2
3
4
5
6
- 定义数据层代理接口,通过注解定义SQL语句
package com.itheima.mapper;
import com.itheima.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from tb_user")
List<User> selectAll();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- 定义业务层Service接口与实现类
package com.itheima.service;
import com.itheima.domain.User;
import java.util.List;
public interface UserService {
List<User> findAll();
}
2
3
4
5
6
7
8
9
package com.itheima.service.impl;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.selectAll();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- 定义测试类,注入
UserService
接口,测试功能
package com.itheima.service;
import com.itheima.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testFindAll() {
List<User> all = userService.findAll();
System.out.println(all);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
扩展,如何使用*Druid*数据库连接池?
- 在pom.xml文件中引入druid依赖坐标
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
2
3
4
5
- 修改application.yml文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver # ?serverTimezone=UTC
url: jdbc:mysql://localhost:3306/db1
username: root
password: 1234
type: com.alibaba.druid.pool.DruidDataSource
2
3
4
5
6
7
至此,SpringBoot整合MyBatis就完成了,大家可以发现,SpringBoot整合MyBatis基于注解开发,还是很快捷方便的,但是基于注解写SQL语句也有一些缺点,后面我们讲完整合案例以后再进行介绍。
# SSM整合案例
# 工程准备
创建SpringBoot模块,选择我们所需要的Spring Web、MyBatis、MySQL等技术集,这个操作我们就不在此赘述了
创建好模块以后,删除无用文件和目录,在pom.xml文件中添加druid依赖坐标,上一小结我们也实际操作过了
<!-- TODO: 1. 添加druid数据库连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
2
3
4
5
6
- 将之前Spring、SpringMVC、MyBatis整合案例中的代码拷贝到我们创建的模块中,分析并删除无用的包和代码,项目目录结构如下:
复制springmvc-09-ssm工程中的静态资源pages、css、js、plugins目录
删除
config
包中的所有配置,在BookMapper
接口上加上@Mapper
注解
package com.itheima.mapper;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 图书持久层代理接口
* @author sunyy
* @version 1.0
* @since 2022.1.9
*/
// TODO: 3. 在BookMapper接口上加@Mapper注解,让Spring给接口创建代理对象
@Mapper
public interface BookMapper {
/**
* 添加图书
* @param book
* @return
*/
int save(Book book);
/**
* 修改图书
* @param book
* @return
*/
int update(Book book);
/**
* 根据id删除图书
* @param id
* @return
*/
int deleteById(@Param("id") Integer id);
/**
* 根据id查询图书
* @param id
* @return
*/
Book getById(@Param("id") Integer id);
/**
* 查询所有图书
* @return
*/
List<Book> getAll();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
- 将application.properties修改为application.yml,配置端口号和连接参数
server:
port: 80
# todo 4 配置数据库连接参数
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: 1234
type: com.alibaba.druid.pool.DruidDataSource
2
3
4
5
6
7
8
9
10
11
- 创建
BookServiceTest
类
package com.itheima.service;
import com.itheima.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
// TODO: 5. 创建BookService单元测试类,添加@SpringBootTest,@Test注解
@SpringBootTest
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById() {
// 传递参数1会抛出异常
Book book = bookService.getById(2);
System.out.println(book);
}
@Test
public void testGetAll() {
List<Book> all = bookService.getAll();
System.out.println(all);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
- 在static目录中提供index.html页面,并添加跳转到pages/books.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<script>
location.href = "pages/books.html";
</script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
最后启动引导类,查看页面效果。
# MyBatis基于注解还是XML
从JavaWeb阶段我们就开始学习MyBatis的使用,我们知道MyBatis有两种SQL语句映射模式,一种是基于注解,一种是基于XML。
- 基于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.itheima.mapper.BrandMapper">
<resultMap id="brandResultMap" type="Brand">
<result column="brand_name" property="brandName" />
<result column="company_name" property="companyName" />
</resultMap>
<insert id="add" parameterType="Brand" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand(
brand_name,
company_name,
ordered,
description,
status
)
values(
#{brandName},
#{companyName},
#{ordered},
#{description},
#{status}
)
</insert>
<update id="update" parameterType="Brand">
update tb_brand
<set>
<if test="brandName != null and brandName != ''">
brand_name = #{brandName},
</if>
<if test="companyName != null and companyName != ''">
company_name = #{companyName},
</if>
<if test="ordered != null">
ordered = #{ordered},
</if>
<if test="description != null and description != ''">
description = #{description},
</if>
<if test="status != null">
status = #{status},
</if>
</set>
where id = #{id}
</update>
<delete id="deleteById">
delete from tb_brand where id = #{id}
</delete>
<delete id="deleteByIds">
delete from tb_brand where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<select id="selectAll" resultMap="brandResultMap">
select
id, brand_name, company_name, ordered, description, status
from
tb_brand
order by ordered desc
</select>
<select id="selectByPage" resultMap="brandResultMap" parameterType="SearchBean">
select
id, brand_name, company_name, ordered, description, status
from
tb_brand
<where>
<if test="companyName != null and companyName != ''">
and company_name like concat('%', #{companyName}, '%')
</if>
<if test="brandName != null and brandName != ''">
and brand_name like concat('%', #{brandName}, '%')
</if>
<if test="status != null">
and status = #{status}
</if>
</where>
order by ordered desc
limit #{begin}, #{pageSize}
</select>
<select id="selectTotal" resultType="java.lang.Integer" parameterType="SearchBean">
select count(*) from tb_brand
<where>
<if test="companyName != null and companyName != ''">
and company_name like concat('%', #{companyName}, '%')
</if>
<if test="brandName != null and brandName != ''">
and brand_name like concat('%', #{brandName}, '%')
</if>
<if test="status != null">
and status = #{status}
</if>
</where>
</select>
</mapper>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
- 基于注解
@Select("select * from tb_user where age > #{age}")
@Results(value = {
@Result(property = "id",column = "id",id = true),
@Result(property = "userName",column = "userName"),
@Result(property = "password",column = "password"),
@Result(property = "name",column = "name"),
@Result(property = "sex",column = "sex"),
@Result(property = "age",column = "age"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "created",column = "created"),
@Result(property = "updated",column = "updated")
})
public List<UserEntity> selectUserByAge(@Param("age") int age);
2
3
4
5
6
7
8
9
10
11
12
13
以上两种方式都已满足我们的需求,那么对于MyBatis初学者来说就会产生一个疑问,MyBatis在实际项目开发中到底是基于XML还是注解模式进行开发?
其实,这个问题对于我们初级开发者来说没必要纠结,原因就在于,在实际项目开发中,选择何种模式开发,并没有统一的标准,也根本不取决于初级开发者,它最终取决于开发团队或者说取决于高级开发者和架构师。
但是,我们还是要来探究一下这个问题,这两者之间有哪些差异和区别?
注解模式和XML模式对比:
- 注解模式
- 优势:开发速度快,开发工作量小
- 劣势:难以线上维护(每次修改SQL语句都需要重新打包),难以处理复杂的SQL语句
- XML模式
- 优势:便于线上维护,支持动态SQL,可以处理复杂的SQL语句
- 劣势:开发速度慢,开发工作量大
# 基于XML模式:Mapper代理接口与SQL的绑定
通常我们使用MyBatis进行开发时,会选择XML文件来写SQL,然后将Mapper接口与SQL的XML文件建立绑定关系,然后再项目中调用Mapper接口就可以执行对应的SQL语句。
那么在SpringBoot中,如何将Mapper接口与SQL语句进行绑定呢?有四种常见的方式:
- 默认策略
- SpringBoot配置文件中添加
mybatis.mapper-locations
,并且使用@MapperScan
或者@Mapper
注解 <mapper>
指定SqlSessionFactory
指定
# 默认策略
采用默认的绑定方式,不需要做额外的操作,重点要遵循下面的规则:
- XML文件的目录结构,要与Mapper接口的包路径完全一致
- XML文件名与Mapper接口名完全一致(区分大小写)
- 另外需要在SpringBoot的引导类上加
@MapperScan("Mapper接口包路径")
或者Mapper接口的定义上面加上@Mapper
注解
# SpringBoot配置文件指定
此种方式同样需要使用@MapperScann
或者@Mapper
注解指定Mapper代理接口,但是针对Mapper.xml文件的存放会更灵活,比如,可以在resources目录下创建mapper目录用于存放所有的XML映射文件,然后在application.yml配置文件中指定XML文件的扫描路径
server:
port: 80
# todo 4 配置数据库连接参数
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: 1234
type: com.alibaba.druid.pool.DruidDataSource
# 指定XML映射文件的存放路径
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# mybatis-config.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 起别名 -->
<typeAliases>
<package name="com.itheima.pojo" />
</typeAliases>
<!--
environments:develop配置数据库连接环境信息。
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///brand_case?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<!--Mapper代理方式-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# MyBatisConfig.java配置类
package com.itheima.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.itheima.domain");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.itheima.mapper");
return mapperScannerConfigurer;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26