对于数据访问层,无论是 SQL 还是 NoSQL,SpringBoot 默认采用整合 Spring Data 的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种 xxxTemplate,xxxRepository 来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。

一、整合基本的 JDBC 与数据源


【1】引入 jdbc starter [spring-boot-starter-jdbc] 和 MySQL 驱动。

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-data-jdbc</artifactId>
4 </dependency>
5 <dependency>
6     <groupId>mysql</groupId>
7     <artifactId>mysql-connector-java</artifactId>
8     <scope>runtime</scope>
9 </dependency>

【2】在 application.yml 中配置数据源相关信息:

1 spring:
2   datasource:
3     username: root
4     password: 123
5     url: jdbc:mysql://127.0.0.1:3306/jdbc
6     driver-class-name: com.mysql.jdbc.Driver

【3】测试:默认使用的是 org.apache.tomcat.jdbc.pool.DataSource 作为数据源。数据源的相关配置都在 DataSourceProperties 里面。自动配置原理:org.springframework.boot.autoconfigure.jdbc 包中的 DataSourceConfiguration,根据配置创建数据源,默认使用 Tomcat 连接池;可以通过 spring.datasource.type 指定自定义数据源类型;SpringBoot 默认支持一下数据源:DataSource、HikariDataSource、BasicDataSource。用户也可以自定义数据源:如下可知是通过 build 创建数据源的。利用反射创建 type 类型的数据源,并绑定相关属性。

 1 @ConditionalOnMissingBean({DataSource.class})
 2 @ConditionalOnProperty(
 3     name = {"spring.datasource.type"}
 4 )
 5 static class Generic {
 6     Generic() {
 7     }
 8         //通过 build 创建数据源的。利用反射创建 type 类型的数据源,并绑定相关属性。
 9     @Bean
10     public DataSource dataSource(DataSourceProperties properties) {
11         return properties.initializeDataSourceBuilder().build();
12     }
13 }

【4】 第二个比较重要的类 DataSourceAutoConfiguration 自动配置类中的 dataSourceInitializer 继承了 ApplicationListener。

 1 public class DataSourceAutoConfiguration {
 2     private static final Log logger = LogFactory.getLog(DataSourceAutoConfiguration.class);
 3 
 4     public DataSourceAutoConfiguration() {
 5     }
 6 
 7     @Bean
 8     @ConditionalOnMissingBean
 9     public DataSourceInitializer dataSourceInitializer(DataSourceProperties properties, ApplicationContext applicationContext) {
10         return new DataSourceInitializer(properties, applicationContext);
11     }
12     //......
13 }
14 
15 class DataSourceInitializer implements ApplicationListener<DataSourceInitializedEvent> {
16 //......
17 }

 DataSourceInitializer 的两个主要作用:①、运行建表语句;②、运行操作数据的 sql语句;

 1 //运行建表语句
 2 private void runSchemaScripts() {
 3     List<Resource> scripts = this.getScripts("spring.datasource.schema", this.properties.getSchema(), "schema");
 4     if(!scripts.isEmpty()) {
 5         String username = this.properties.getSchemaUsername();
 6         String password = this.properties.getSchemaPassword();
 7         this.runScripts(scripts, username, password);
 8 
 9         try {
10             this.applicationContext.publishEvent(new DataSourceInitializedEvent(this.dataSource));
11             if(!this.initialized) {
12                 this.runDataScripts();
13                 this.initialized = true;
14             }
15         } catch (IllegalStateException var5) {
16             logger.warn("Could not send event to complete DataSource initialization (" + var5.getMessage() + ")");
17         }
18     }
19 
20 }
21 //运行操作数据的 sql语句
22 private void runDataScripts() {
23     List<Resource> scripts = this.getScripts("spring.datasource.data", this.properties.getData(), "data");
24     String username = this.properties.getDataUsername();
25     String password = this.properties.getDataPassword();
26     this.runScripts(scripts, username, password);
27 }

【5】进行数据表创建时,默认只需要将文件命名为:schema-*.sql;进行数据操作时,默认只需要将文件命令为:data-*.sql;如果自定义sql 文件时,可以在 application.yml 中通过如下方式指定sql文件位置:传入的是一个 list 列表

1 spring:
2   datasource:
3     schema:
4       - classpath: student.sql

【6】JdbcTemplateAutoConfiguration 自动配置类给容器中注入了 JdbcTemplate 组件,帮组我们操作数据库。

1 @AutoConfigureAfter({DataSourceAutoConfiguration.class})
2 public class JdbcTemplateAutoConfiguration {
3     @Bean
4     @Primary
5     @ConditionalOnMissingBean({JdbcOperations.class})
6     public JdbcTemplate jdbcTemplate() {
7         return new JdbcTemplate(this.dataSource);
8     }
9 }

【7】高级配置:使用 druid 数据源,首先需要引入依赖:

1 <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
2 <dependency>
3     <groupId>com.alibaba</groupId>
4     <artifactId>druid</artifactId>
5     <version>1.1.10</version>
6 </dependency>

【8】在 yml 配置文件中加入 Druid

1 spring:
2   datasource:
3     username: root
4     password: 123
5     url: jdbc:mysql://127.0.0.1:3306/jdbc
6     driver-class-name: com.mysql.jdbc.Driver
7     type: com.alibaba.druid.pool.DruidDataSource

二、整合 Mybatis 数据源(注解版)


【1】创建项目:选中 web、mybatis、mysql 和 jdbc 模块的 starts;在 pom.xml 中会发现 mybatis 与 springboot 的整合依赖:这个依赖并不是以 spring-boot 开始的,说明并不是 spring 提供的依赖,而是由第三方 mybatis 提供的依赖包;

1 <dependency>
2     <groupId>org.mybatis.spring.boot</groupId>
3     <artifactId>mybatis-spring-boot-starter</artifactId>
4     <version>2.1.1</version>
5 </dependency>

【2】定义个接口类,用来操作目标表的增删改查:通过 @Mapper 表示该接口类是一个 Mybatis 的 Mapper 类,通过增删改查注解 @Select @Update @Insert @Delete 对数据表进行操作;

1 //指定这是一个操作数据库的 mapper
2 @Mapper
3 public interface DepartmentMapper {
4 
5     @Select("select * from department where id=#{id}")
6     public Department getDeptById(Integer id);
7 }

【3】通过 Controller 层调用 Server 继而调用 Mapper 对数据完成操作:

 1 @Controller
 2 public class DepartmentController {
 3 
 4     @Autowired
 5     private DepartmentMapper mapper;
 6 
 7     @GetMapping("/dept/{id}")
 8     public Department getDeptById(@PathVariable("id") Integer id){
 9         return mapper.getDeptById(id);
10     }
11 }