SpringBoot整合JDBC的步骤

x33g5p2x  于2021-03-14 发布在 Spring  
字(2.6k)|赞(0)|评价(0)|浏览(161)

1. 添加依赖
pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>

2. 编写配置
resources/application.yml

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://127.0.0.1:3306/learn?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    # type: com.zaxxer.hikari.HikariDataSource 可以根据type来指定数据源,默认为HikariDataSource

更多的配置可以在DataSourceProperties类中找到。
3. 测试
com/exa/jdbc/JdbcApplicationTests.java

package com.exa.jdbc;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class JdbcApplicationTests {

    @Autowired
    DataSource dataSource;

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

日志输出如下:

# 默认数据源为HikariDataSource
dataSource=class com.zaxxer.hikari.HikariDataSource
2020-11-21 18:07:35.814  INFO 32 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-11-21 18:07:36.295  INFO 32 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
# Connection不为null,说明连接成功
Connection=HikariProxyConnection@465869765 wrapping com.mysql.jdbc.JDBC4Connection@7b6e5c12

4. 我们可以调用JdbcTemplate类的相关方法来操作数据库
/controller/StudentController.java

package com.exa.jdbc.controller;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class StudentController {

    @Autowired
    JdbcTemplate template;

    @GetMapping("/query")
    @ResponseBody
    public Map<String, Object> map() {
        List<Map<String, Object>> list =  template.queryForList("select * from user");
        System.out.println(list.get(0));
        return list.get(0);
    }
}

输出如下:

{userId=1, userName=zhangsan, password=123456, role=1, vip=1, userAvatar=/statics/images/7cb8214798f26846a8415bac9c9e1ab9.jpg, createTime=2020-11-05 09:19:30.0, modifyTime=2020-11-05 09:19:30.0}

相关文章

最新文章

更多