16-Springboot中JdbcTemplate和数据源的关系

本文介绍了Spring Boot中JdbcTemplate和DataSource的关系,JdbcTemplate是对DataSource的封装,可在Spring框架内解决数据库访问问题。还给出了JdbcTemplate实例,包括建表、配置文件等内容,并进行了测试。最后总结指出,虽JdbcTemplate可完成数据库访问,但项目中更多使用MyBatis等框架。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇:15-Springboot其他数据源配置之Druid
https://blog.csdn.net/fsjwin/article/details/109742300

有了数据源也白搭,不管是内置的HikariDataSource还是用的比较多的第三方数据源DruidDataSource,还是ADataSource、BDataSrouce,因为有了数据源,的有人用起来才行呀,有人会说有呀Mybatis就可以呀,当然Mybatis这位大哥当然可以,但是本节,我们先介绍一个小弟,下节在请出大哥。

JdbcTemplate及时对DataSource的封装,使我们可以在Spring框架内部解决数据裤访问的问题。

1. JdbcTemplate和DataSource关系。

在这里插入图片描述

2. JdbcTemplate实例

写一个实例,加深印象

2.1 建表

CREATE TABLE `student`  (
  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `age` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

2.2 application.yml

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1/yuhl?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

  server:
    port: 9999

2.3 DruidConfig.java

package com.yuhl;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author yuhl
 * @Date 2020/11/16 11:15
 * @Classname DruidConfig
 * @Description TODO
 */
@Configuration
public class DruidConfig {
    /*
    这样的话才会绑定上下面的属性:
        initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(){
        return new DruidDataSource();
    }
}

2.4 JDBCTemplateController

package com.yuhl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * @author yuhl
 * @Date 2020/11/14 15:27
 * @Classname HelloController
 * @Description TODO
 */
@RestController
public class JDBCTemplateController {

	//注入JdbcTemplate  用于操作数据库
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/jdbct")
    public List<Map<String, Object>> hello() {
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from student");
        return maps;
    }
}

3. JdbcTemplate测试

页面访问:
在这里插入图片描述

4. 总结

JdbcTemplate就是对数据源的封装,在不引入其他框架的基础上,在spirng的内部完成对数据库的访问和业务开发,但是在项目上我们更多会使用mybatis等框来做这件事,更少使用jdbcTemplate。

下一篇:17-Springboot整合mybatis注解版Mapper https://blog.csdn.net/fsjwin/article/details/109744677

Spring Boot 中配置 JdbcTemplate数据源可以通过手动定义多个 `DataSource` `JdbcTemplate` Bean 来实现。Spring Boot 默认只提供单个数据源的自动配置,因此需要通过自定义 Bean 的方式来支持多数据源。 ### 数据库配置 首先,在 `application.properties` 或 `application.yml` 文件中为多个数据源定义各自的连接信息。例如,使用 `application.properties` 配置两个 MySQL 数据源: ```properties # 第一个数据源配置 spring.datasource.one.url=jdbc:mysql://localhost:3306/db1?useSSL=false&serverTimezone=UTC spring.datasource.one.username=root spring.datasource.one.password=root spring.datasource.one.driver-class-name=com.mysql.cj.jdbc.Driver # 第二个数据源配置 spring.datasource.two.url=jdbc:mysql://localhost:3306/db2?useSSL=false&serverTimezone=UTC spring.datasource.two.username=root spring.datasource.two.password=root spring.datasource.two.driver-class-name=com.mysql.cj.jdbc.Driver ``` ### 配置类实现多数据源 接下来,在配置类中分别创建两个 `DataSource` 对应的 `JdbcTemplate` Bean。为了绑定不同前缀的属性,可以使用 `@ConfigurationProperties` 注解[^4]。 ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.one") public DataSource dataSourceOne() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.two") public DataSource dataSourceTwo() { return DataSourceBuilder.create().build(); } @Bean public JdbcTemplate jdbcTemplateOne(DataSource dataSourceOne) { return new JdbcTemplate(dataSourceOne); } @Bean public JdbcTemplate jdbcTemplateTwo(DataSource dataSourceTwo) { return new JdbcTemplate(dataSourceTwo); } } ``` ### 使用不同的 JdbcTemplate 在业务代码中,可以通过注入不同的 `JdbcTemplate` 实例来操作对应的数据源。例如,在 Controller 或 Service 层中注入并使用它们[^3]。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MultiDataSourceController { private final JdbcTemplate jdbcTemplateOne; private final JdbcTemplate jdbcTemplateTwo; @Autowired public MultiDataSourceController(JdbcTemplate jdbcTemplateOne, JdbcTemplate jdbcTemplateTwo) { this.jdbcTemplateOne = jdbcTemplateOne; this.jdbcTemplateTwo = jdbcTemplateTwo; } @GetMapping("/data-one") public String getDataFromFirstDataSource() { return jdbcTemplateOne.queryForObject("SELECT COUNT(*) FROM users", Integer.class).toString(); } @GetMapping("/data-two") public String getDataFromSecondDataSource() { return jdbcTemplateTwo.queryForObject("SELECT COUNT(*) FROM orders", Integer.class).toString(); } } ``` ### 注意事项 - 确保数据库驱动已添加到项目依赖中,如 MySQL、PostgreSQL 等。 - 若涉及事务管理,需额外配置 `PlatformTransactionManager` 并指定使用的数据源-数据源环境下,建议结合动态数据源(如 AbstractRoutingDataSource)实现更灵活的切换逻辑。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值