SpringBoot 整合JDBC简单使用JdbcTemplate

一、SpringBoot 整合JDBC

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

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

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

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<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from t_user");
        System.out.println(maps);
    }

}

    SpringBoot 整合JDBC简单使用JdbcTemplate

注意:

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

参考文章:

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

     

ends ~ 

 

 

上一篇:The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time


下一篇:java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ 解决方案