SpringBoot整合JDBC与默认数据源

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: SpringBoot整合JDBC与默认数据源

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

【1】SpringBoot配置数据源

① 创建项目,引入需要的模块

pom文件

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

② 配置MySQL并测试

类似于以前项目的config.properties,这将mysql的属性配置在yml文件中。数据源的所有配置对应类如下:

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties
    implements BeanClassLoaderAware, EnvironmentAware, InitializingBean {
  private ClassLoader classLoader;
  private Environment environment;
  /**
   * Name of the datasource.
   */
  private String name = "testdb";
  /**
   * Generate a random datasource name.
   */
  private boolean generateUniqueName;
  /**
   * Fully qualified name of the connection pool implementation to use. By default, it
   * is auto-detected from the classpath.
   */
  private Class<? extends DataSource> type;
  /**
   * Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
   */
  private String driverClassName;
  /**
   * JDBC url of the database.
   */
  private String url;
  /**
   * Login user of the database.
   */
  private String username;
  /**
   * Login password of the database.
   */
  private String password;
  /**
   * JNDI location of the datasource. Class, url, username & password are ignored when
   * set.
   */
  private String jndiName;
  /**
   * Populate the database using 'data.sql'.
   */
  private boolean initialize = true;
  /**
   * Platform to use in the DDL or DML scripts (e.g. schema-${platform}.sql or
   * data-${platform}.sql).
   */
  private String platform = "all";
  /**
   * Schema (DDL) script resource references.
   */
  private List<String> schema;
  /**
   * User of the database to execute DDL scripts (if different).
   */
  private String schemaUsername;
  /**
   * Password of the database to execute DDL scripts (if different).
   */
  private String schemaPassword;
  /**
   * Data (DML) script resource references.
   */
  private List<String> data;
  /**
   * User of the database to execute DML scripts.
   */
  private String dataUsername;
  /**
   * Password of the database to execute DML scripts.
   */
  private String dataPassword;
  /**
   * Do not stop if an error occurs while initializing the database.
   */
  private boolean continueOnError = false;
  /**
   * Statement separator in SQL initialization scripts.
   */
  private String separator = ";";
  /**
   * SQL scripts encoding.
   */
  private Charset sqlScriptEncoding;
  private EmbeddedDatabaseConnection embeddedDatabaseConnection = EmbeddedDatabaseConnection.NONE;
  private Xa xa = new Xa();
  private String uniqueName;
  //...
}

application.yml文件如下:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

20180625140819552.jpg

在测试类中获取默认数据源,并拿到链接:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DatasourceApplicationTests {
  @Autowired
  DataSource dataSource;
  @Test
  public void contextLoads() throws  Exception {
    System.out.println(dataSource.getClass()+"***********");
    Connection connection = dataSource.getConnection();
    System.out.println(connection);
  }
}

测试结果如下:

class org.apache.tomcat.jdbc.pool.DataSource***********
ProxyConnection[PooledConnection[com.mysql.jdbc.JDBC4Connection@2bfbffb2]]

即,数据源默认使用的是org.apache.tomcat.jdbc.pool.DataSource(这个与SpringBoot版本有关,这里是1.5.10)。

【2】使用JdbcTemplate访问数据库

① 默认注入

SpringBoot默认配置了JdbcTemplateNamedParameterJdbcTemplate,源码如下:

@Configuration
@ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class JdbcTemplateAutoConfiguration {
  private final DataSource dataSource;
  public JdbcTemplateAutoConfiguration(DataSource dataSource) {
    this.dataSource = dataSource;
  }
  @Bean
  @Primary
  @ConditionalOnMissingBean(JdbcOperations.class)
  public JdbcTemplate jdbcTemplate() {
    return new JdbcTemplate(this.dataSource);
  }
  @Bean
  @Primary
  @ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
  public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
    return new NamedParameterJdbcTemplate(this.dataSource);
  }
}

可以看到在上面JdbcTemplateAutoConfiguration 中默认注入了namedParameterJdbcTemplatejdbcTemplate两个实例。

② 编写controller进行测试

@Controller
public class HelloController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @ResponseBody
    @GetMapping("/hello")
    private Map<String,Object> getBook(){
        String sql = "select * from book";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list.get(0);
    }
}

浏览器访问结果如下:


这里返回结果为Map,浏览器得到的为JSON。这是因为,首先方法上使用了注解@Responsebody,其次WebMVCAutoConfiguration默认注册了一系列的HttpMessageConverter,该类主要用来做请求响应的转换。

@Responsebody注解被RequestResponseBodyMethodProcessor 处理器进行解析。

【3】SpringBoot加载项目路径下的SQL

SpringBoot另一个特性是可以加载项目路径下的SQL脚本,比如建表语句,insert语句等等。

默认Schema脚本名字:

classpath*:schema.sql;
classpath*:schema-all.sql;

默认Data脚本名字:

classpath*:data.sql;
classpath*:data-all.sql;

如果想使用自定义脚本名字,在yml文件中配置:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    schema:
      - classpath:department.sql

如下图所示:

【4】默认数据源配置实例

这里默认数据源指的是org.apache.tomcat.jdbc.pool.DataSource

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
     #最大连接数
    tomcat.max-active: 20
    #最大空闲数
    tomcat.max-idle: 8
    #最小空闲数
    tomcat.min-idle: 8
    #初始化连接数
    tomcat.initial-size: 10

无需使用额外配置或者pom文件,即可正常使用默认org.apache.tomcat.jdbc.pool.DataSource

【5】SpringBoot2.X中使用HikariDataSource

在SpringBoot2.X版本中,默认使用数据源是HikariDataSource(可以称之为"光"),如下所示在DataSourceBuilder配置。

private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] {
  "com.zaxxer.hikari.HikariDataSource",
  "org.apache.tomcat.jdbc.pool.DataSource",
  "org.apache.commons.dbcp2.BasicDataSource" };

这里同样贴一份配置实例

# 驱动,根据需要更改 如com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# url
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
# Hikari 数据源配置
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
#最小空闲 
spring.datasource.hikari.minimum-idle=5
#连接池最大连接数,默认是10
spring.datasource.hikari.maximum-pool-size=15
# 此属性控制从池返回的连接的默认自动提交行为,默认值:true
spring.datasource.hikari.auto-commit=true
# 空闲连接存活最大时间,默认600000(10分钟)
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
spring.datasource.hikari.max-lifetime=1800000
# 数据库连接超时时间,默认30秒,即30000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1

image.png


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
4月前
|
druid Java 数据库连接
SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis
SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis
65 0
|
5月前
|
Java 数据库连接 应用服务中间件
原生JDBC使用C3p0数据源和dbcp数据源
原生JDBC使用C3p0数据源和dbcp数据源
63 0
|
5月前
|
SQL 算法 Java
数据库系列课程(08)-SpringBoot整合Sharding-Jdbc
数据库系列课程(08)-SpringBoot整合Sharding-Jdbc
64 0
|
6月前
|
Java 数据库连接
27SpringBoot之JDBC(完整代码)
27SpringBoot之JDBC(完整代码)
52 0
|
4月前
|
Java 关系型数据库 MySQL
②⑩② 【读写分离】Sharding - JDBC 实现 MySQL读写分离[SpringBoot框架]
②⑩② 【读写分离】Sharding - JDBC 实现 MySQL读写分离[SpringBoot框架]
42 0
|
30天前
|
Java
SpringBoot整合sharding-jdbc实现分库分表
SpringBoot整合sharding-jdbc实现分库分表
36 1
|
3月前
|
Java 数据库连接 数据库
Springboot 之 JDBC 多数据源实现
Springboot 之 JDBC 多数据源实现
54 0
|
5月前
|
SQL Java 中间件
Springboot集成 Sharding-JDBC + Mybatis-Plus实现分库分表(源码)
Sharding-jdbc是开源的数据库操作中间件;定位为轻量级Java框架,在Java的JDBC层提供的额外服务。它使用客户端直连数据库,以jar包形式提供服务,无需额外部署和依赖,可理解为增强版的JDBC驱动,完全兼容JDBC和各种ORM框架。
|
9月前
|
SQL 算法 Java
springboot中sharding jdbc绑定表配置实战
springboot中sharding jdbc绑定表配置实战
|
3月前
|
SQL Java 关系型数据库
MySQL之JDBC(二)
MySQL之JDBC(二)
34 0