您当前的位置: 首页 >  spring

Charge8

暂无认证

  • 0浏览

    0关注

    447博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot 整合JdbcTemplate

Charge8 发布时间:2019-05-27 21:45:59 ,浏览量:0

一、SpringBoot 整合JDBC

JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作。

1、在创建SpringBoot 的项目时,选择JDBC、mysql,web的组件,或者自己手动在maven中添加库依赖:


    org.springframework.boot
    spring-boot-starter-jdbc


    mysql
    mysql-connector-java
    runtime

2、在 application.yml(或aproperties)中添加相应的配置:

server:
  port: 80

# 数据库连接信息
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/my_springboot?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver # com.mysql.jdbc.Driver

3、在测试类中测试

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootdemoApplicationTests {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void contextLoads() throws SQLException {
        System.out.println("dataSource==" + dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println("connection==" + connection);

        List maps = jdbcTemplate.queryForList("select * from t_user");
        System.out.println(maps);
    }

}

    

注意:

1)有关Spring 里的数据源。SpringBoot 都有默认配置的数据源,直接测试OK。

2)SpringBoot 2.06 以后默认使用的是HikariDataSource数据源,传说这个在数据库访问速度上是C3P0的25倍。

3)SpringBoot 默认配置了JdbcTemplate,配了数据源就可以直接使用它操作数据库即可。

 

二、遇到的问题

1、Spring Boot 高版本配置数据库连接驱动问题

 Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

2、设置时区的问题

java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

  以下 serverTimezone 配置在我这里都能启动成功。

serverTimezone=GMT%2B8
serverTimezone=GMT
serverTimezone=Asia/Shanghai

 

三、SpringBoot 配置多数据源之JdbcTemplate

        在单数据源的情况下,Spring Boot的配置非常简单。随着业务量发展,我们通常会进行数据库拆分或是引入其他数据库,如果有多数据源的需求,从而我们需要配置多个数据源。也可以使用分布式数据库中间件MyCat去解决相关问题。

1、在创建SpringBoot 的项目时,引入依赖

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-jdbc
        

        
            mysql
            mysql-connector-java
            5.1.47
            runtime
        

        
            com.alibaba
            druid-spring-boot-starter
            1.1.13
        

2、在 application.aproperties中添加两个数据源的配置信息

server.port=8088
# 配置两个数据源
spring.datasource.dsone.url=jdbc:mysql://localhost:3306/sbtdb1?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
spring.datasource.dsone.username=root
spring.datasource.dsone.password=123456
spring.datasource.dsone.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.dsone.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.dstwo.url=jdbc:mysql://localhost:3306/sbtdb2?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
spring.datasource.dstwo.username=root
spring.datasource.dstwo.password=123456
spring.datasource.dstwo.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.dstwo.driver-class-name=com.mysql.jdbc.Driver

3、在配置类中,定义两个DataSource Bean,并配置JdbcTemplate实例

@Configuration
public class DataSourceConfig {
    /**
     * 定义两个DataSource
     * 使用spring.datasource.dsone前缀的数据库配置去创建一个DataSource
     */
    @Bean("dsOne")
    @ConfigurationProperties(prefix = "spring.datasource.dsone")
    DataSource dsOne() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("dsTwo")
    @ConfigurationProperties(prefix = "spring.datasource.dstwo")
    DataSource dsTwo() {
        return DruidDataSourceBuilder.create().build();
    }


    /**
     * 定义两个JdbcTemplate
     * 默认byType使用类型查找,会报错,因此加上@Qualifier注解,表示按照名称查找。
     */
    @Bean("jdbcTemplateOne")
    JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dsOne) {
        return new JdbcTemplate(dsOne);
    }

    @Bean("jdbcTemplateTwo")
    JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo") DataSource dsTwo) {
        return new JdbcTemplate(dsTwo);
    }
}

4、测试类

@RestController
public class UserContorller {
    /**
     * JdbcTemplate有两个,因此不能通过byType的方式注入
     * 下面这两种都可以通过byName的方式注入
     */
    @Autowired
    @Qualifier("jdbcTemplateOne")
    public JdbcTemplate jdbcTemplateOne;

    @Resource(name = "jdbcTemplateTwo")
    public JdbcTemplate jdbcTemplateTwo;

    @GetMapping("/getJdbcTemplateOneUser")
    public List getJdbcTemplateOneUser() {
        List list = jdbcTemplateOne.query("select * from t_user", new BeanPropertyRowMapper(User.class));
        System.out.println(list);
        return list;
    }

    @GetMapping("/getJdbcTemplateTwoUser")
    public List getJdbcTemplateTwoUser() {
        List list = jdbcTemplateTwo.query("select * from t_user", new BeanPropertyRowMapper(User.class));
        System.out.println(list);
        return list;
    }
}

两个表都有user表,字段相同我这里就共用了。

 

参考文章:

      com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区别 serverTimezone设定

     

ends ~ 

 

 

关注
打赏
1664721914
查看更多评论
立即登录/注册

微信扫码登录

0.0503s