Spring Boot 默认数据源 HikariDataSource 与 JdbcTemplate 初遇

目录

环境准备与依赖

HikariDataSource 数据源常用配置

HikariDataSource 数据源测试

JdbcTemplate CRUD 数据库

数据源自动配置原理


环境准备与依赖

1、本文介绍 Spring Boot 内部集成的 JDBC 模板访问 Mysql 数据库,环境:Java JDK 8 + Spring boot 2.1.5 + HikariDataSource + Mysql/Oracle + JdbcTemplate

2、pom. xml 依赖如下:

        <!-- 引入Spring封装的jdbc,内部默认依赖了 HikariDataSource  数据源-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

        <!-- web项目启动模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mysql数据库连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.16</version>
        </dependency>

pom.xml · 汪少棠/jdbc_template_app - Gitee.com

mysql 数据库表:

src/main/resources/data/iphone.sql · 汪少棠/jdbc_template_app - Gitee.com

HikariDataSource 数据源常用配置

1、全局配置文件内容如下:

spring:
  datasource:
    # jdbc 连接基础配置
    username: root
    password: root
    #使用的 mysql 版本为:Server version: 5.6.11 MySQL Community Server (GPL)
    #mysql 驱动版本:mysql-connector-java-8.0.16.jar
    #高版本 Mysql 驱动时,配置的 driver-class-name 不再是 com.mysql.jdbc.Driver,url 后面必须设置时区 serverTimezone
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

    #hikari数据源特性配置
    hikari:
      maximum-pool-size: 100 #最大连接数,默认值10.
      minimum-idle: 20 #最小空闲连接,默认值10.
      connection-timeout: 60000 #连接超时时间(毫秒),默认值30秒.
      #空闲连接超时时间,默认值600000(10分钟),只有空闲连接数大于最大连接数且空闲时间超过该值,才会被释放
      #如果大于等于 max-lifetime 且 max-lifetime>0,则会被重置为0.
      idle-timeout: 600000
      max-lifetime: 3000000 #连接最大存活时间,默认值30分钟.设置应该比mysql设置的超时时间短
      connection-test-query: select 1 #连接测试查询
高版本的 spring boot 搭配 mysql 驱动版本较高时,如 mysql-connector-java:8.0.16,此时 driver-class-name 的值要带 cj;url 的值要带时区 serverTimezone,如:
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver

2、hikari 除了上面的配置,其它的配置还有:

spring.datasource.type

要使用的连接池实现的完全限定名称。默认情况下,它是从类路径自动检测到的

值比如:com.zaxxer.hikari.HikariDataSource

spring.datasource.hikari.pool-namehikari 连接池名称,默认 HikariPool-1
spring.datasource.hikari.auto-commit此属性控制从池返回的连接的默认自动提交行为。它是一个布尔值。 默认值:true

spring.datasource.hikari.maximum-pool-size: 1000

池中允许达到的最大连接数,包括空闲和正在使用的连接,默认值10。

spring.datasource.hikari.minimum-idle: 200

最小空闲连接,默认值10. 默认与maximumPoolSize相同

spring.datasource.hikari.connection-timeout: 60000

连接超时时间(毫秒),默认值30秒.如果在没有可用连接的情况下超过此时间,则会抛出SQLException
spring.datasource.hikari.idle-timeout: 600000空闲连接超时时间,默认值600000(10分钟),只有空闲连接数大于最大连接数且空闲时间超过该值,才会被释放
如果大于等于 max-lifetime 且 max-lifetime>0,则会被重置为0.

spring.datasource.hikari.max-lifetime: 3000000

连接最大存活时间,默认值30分钟.设置应该比mysql设置的超时时间短
spring.datasource.hikari.connection-test-query: select 1

连接测试查询,确认从池中获取的连接是否能使用。

如果驱动程序不符合JDBC4的要求,HikariCP将记录一个错误以告知您,默认值:无

3、关于上面的数据源公共配置的内容,都可以从 Spring Boot 官方文档 查看:

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.continue-on-error=false # Whether to stop if an error occurs while initializing the database.
spring.datasource.data= # Data (DML) script resource references.
spring.datasource.data-username= # Username of the database to execute DML scripts (if different).
spring.datasource.data-password= # Password of the database to execute DML scripts (if different).
spring.datasource.dbcp2.*= # Commons DBCP2 specific settings
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.generate-unique-name=false # Whether to generate a random datasource name.
spring.datasource.hikari.*= # Hikari specific settings
spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts.
spring.datasource.jmx-enabled=false # Whether to enable JMX support (if provided by the underlying pool).
spring.datasource.jndi-name= # JNDI location of the datasource. Class, url, username & password are ignored when set.
spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database.
spring.datasource.password= # Login password of the database.
spring.datasource.platform=all # Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or data-${platform}.sql).
spring.datasource.schema= # Schema (DDL) script resource references.
spring.datasource.schema-username= # Username of the database to execute DDL scripts (if different).
spring.datasource.schema-password= # Password of the database to execute DDL scripts (if different).
spring.datasource.separator=; # Statement separator in SQL initialization scripts.
spring.datasource.sql-script-encoding= # SQL scripts encoding.
spring.datasource.tomcat.*= # Tomcat datasource specific settings
spring.datasource.type= # Fully qualified name of the connection pool implementation to use. By default, it is auto-detected from the classpath.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.
spring.datasource.xa.data-source-class-name= # XA datasource fully qualified name.
spring.datasource.xa.properties= # Properties to pass to the XA data source.

4、也可以从 org.springframework.boot.autoconfigure.jdbc.DataSourceProperties 数据源配置文件类中进行查看。

HikariDataSource 数据源测试

1、全局配置文件 application.yml 中 spring.datasource 下只配置了账号、密码、数据库地址、连接驱动,因为默认使用的是 class com.zaxxer.hikari.HikariDataSource 数据源

2、如果过是自定义数据源,比如 DruidDataSource,则可以使用 type 指定,如下所示:type: com.alibaba.druid.pool.DruidDataSource,可以参考《切换 Druid 数据源

3、测试数据源如下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DataSourceTest {
    /**
     * Spring Boot 默认已经配置好了数据源,程序员可以直接 DI 注入然后使用即可
     */
    @Resource
    DataSource dataSource;
    @Test
    public void contextLoads() throws SQLException {
        Connection connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();

        //数据源>>>>>>class com.zaxxer.hikari.HikariDataSource
        System.out.println("数据源>>>>>>" + dataSource.getClass());
        System.out.println("连接>>>>>>>>" + connection);
        System.out.println("连接地址>>>>" + connection.getMetaData().getURL());
        System.out.println("驱动名称>>>>" + metaData.getDriverName());
        System.out.println("驱动版本>>>>" + metaData.getDriverVersion());
        System.out.println("数据库名称>>" + metaData.getDatabaseProductName());
        System.out.println("数据库版本>>" + metaData.getDatabaseProductVersion());
        System.out.println("连接用户名称>" + metaData.getUserName());

        connection.close();

        // 数据源>>>>>>class com.zaxxer.hikari.HikariDataSource
        // 连接>>>>>>>>HikariProxyConnection @554510956 wrapping com.mysql.cj.jdbc.ConnectionImpl@3bec5821
        // 连接地址>>>>jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&serverTimezone=UTC
        // 驱动名称>>>>MySQL Connector/J
        // 驱动版本>>>>mysql-connector-java-8.0.16 (Revision: 34cbc6bc61f72836e26327537a432d6db7c77de6)
        // 数据库名称>>MySQL
        // 数据库版本>>8.0.26
        // 连接用户名称>root@localhost
    }
}

src/test/java/com/wmx/jdbc_template_app/DataSourceTest.java · 汪少棠/jdbc_template_app - Gitee.com

1、可以看出 Spring Boot 2.1.5 默认使用 com.zaxxer.hikari.HikariDataSource 数据源,而以前版本,如 Spring Boot 1.5 默认使用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源;

2、HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat jdbc 等连接池更加优秀;

3、HikariDataSource 的内容本文暂时不做延伸,有了数据库连接,显然就可以 CRUD 操作数据库了。

JdbcTemplate CRUD 数据库

1、有了数据源(com.zaxxer.hikari.HikariDataSource),然后拿到l了数据库连接(java.sql.Connection),自然就可以使用连接和原生的 JDCB 语句来操作数据库

2、即使不使用第三方第数据库操作框架,如 MyBatis、Hibernate 、JDBC Utils 等,Spring 本身也对 原生的 JDBC 做了轻量级的封装,即 org.springframework.jdbc.core.JdbcTemplate。这原本是 Spring 的知识点!

3、数据库操作的所有 CRUD 方法都在 JdbcTemplate 中,有了 JdbcTemplate 就能更加轻松的操作数据库。

4、Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用

5、JdbcTemplate  的自动配置原理是依赖 org.springframework.boot.autoconfigure.jdbc 包下的 org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration 类

PhoneController 控制层

1、为了尽可能符合实际开发,新建一个控制层,通过浏览器访问来进行 CRUD,但是不再进行细致的分层,如 dao、service、domain 等都省略

@Controller
public class PhoneController {
    /**
     * JdbcTemplate 是 core 包的核心类,用于简化 JDBC 操作,还能避免一些常见的错误,如忘记关闭数据库连接
     * Spring Boot 默认提供了数据源,默认提供了 org.springframework.jdbc.core.JdbcTemplate
     * JdbcTemplate 中会自己注入数据源,使用起来也不用再自己来关闭数据库连接
     */
    @Resource
    private JdbcTemplate jdbcTemplate;
    /**
     * 查询 iphone 表所有数据
     * http://localhost:8080/phoneList
     *
     * @return
     */
    @ResponseBody
    @GetMapping("phoneList")
    public List<Map<String, Object>> userList() {
        /**
         * 查询 iphone 表所有数据
         * List 中的1个 Map 对应数据库的 1行数据
         * Map 中的 key 对应数据库的字段名,value 对应数据库的字段值
         */
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList("SELECT * FROM iphone");
        return mapList;
    }
    /**
     * 新增 iphone 数据
     * http://localhost:8080/savePhone
     *
     * @return
     */
    @GetMapping("savePhone")
    public String savePhone() {
        String sql = "INSERT INTO iphone(id,name,price,publish_time) VALUES (?,?,?,?)";
        Object[] objects = new Object[4];
        objects[0] = null;
        objects[1] = "大米S" + String.valueOf(System.currentTimeMillis()).substring(10, 12);
        objects[2] = 800 + new SecureRandom().nextFloat() * 5000;
        objects[3] = new Date();

        //服务端调整,重新查询全部
        jdbcTemplate.update(sql, objects);
        return "forward:/phoneList";
    }
    /**
     * 修改 iphone 数据
     * http://localhost:8080/updatePhone/1/8888.08
     *
     * @return
     */
    @GetMapping("updatePhone/{id}/{price}")
    public String updatePhone(@PathVariable(value = "id") String id, @PathVariable(value = "price") String price) {
        String sql = "UPDATE iphone SET price=? WHERE id=?";
        Object[] objects = new Object[2];
        objects[0] = price;
        objects[1] = id;

        jdbcTemplate.update(sql, objects);
        return "forward:/phoneList";
    }
    /**
     * 删除 iphone 数据
     * update 方法可以做查询以外的 增加、修改、删除操作
     * http://localhost:8080/deletePhone/11
     *
     * @return
     */
    @GetMapping("deletePhone/{id}")
    public String deletePhone(@PathVariable Integer id) {
        String sql = "DELETE FROM iphone WHERE id=?";
        Object[] objects = new Object[1];
        objects[0] = id;

        jdbcTemplate.update(sql, objects);
        return "forward:/phoneList";
    }

src/main/java/com/wmx/jdbc_template_app/controller/PhoneController.java · 汪少棠/jdbc_template_app - Gitee.com

数据源自动配置原理

1、自动配置都在 org.springframework.boot.autoconfigure.jdbc 包下。

2、org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration 数据源配置类作用是根据逻辑判断之后,添加数据源

3、SpringBoot 默认支持如下数据源;

1、com.zaxxer.hikari.HikariDataSource (Spring Boot 2.0 以上,默认使用此数据源)
2、org.apache.tomcat.jdbc.pool.DataSource
3、org.apache.commons.dbcp2.BasicDataSource

4、可以使用 spring.datasource.type 指定自定义的数据源类型,值为 要使用的连接池实现的完全限定名。默认情况下,它是从类路径自动检测的。

    @ConditionalOnMissingBean({DataSource.class})
    @ConditionalOnProperty(
        name = {"spring.datasource.type"}
    )
    static class Generic {
        Generic() {
        }
        @Bean
        public DataSource dataSource(DataSourceProperties properties) {
            return properties.initializeDataSourceBuilder().build();
        }
    }

Spring Boot 自定义数据源 DruidDataSource

Spring JdbcTemplate 模板剖析 之 常用 增删改查

  • 44
    点赞
  • 172
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蚩尤后裔-汪茂雄

芝兰生于深林,不以无人而不芳。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值