SpringBoot—结合JDBC

原创
小哥 3年前 (2022-11-14) 阅读数 9 #大杂烩

SpringBoot—整合JDBC

一、准备工作

1、新建项目的时候勾选上 JDBC API+MySQL Driver 这两个模块

勾选上以后,我们在项目的 pom.xml 文件中可以发现给我们自动添加了两个启动器,如下所示:

          
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
         
        
            mysql
            mysql-connector-java
            runtime
        

2、导入web依赖,要不后面需要使用的部分注解不能正常使用

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

二、整合JDBC

1、编写 application.yaml 配置文件连接数据库

spring:
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    #加入时区serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8

2、编写Controller,注入jdbcTemplate,实现整合JDBC

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.PathVariable;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    //查询数据库的所有信息
    //没有实体类 数据库中的东西 怎么获取 Map
    @GetMapping("/userList")
    public List> userList(){
        String sql="select * from mybatis.user";
        List> maps = jdbcTemplate.queryForList(sql);
        return maps;

    }

    @GetMapping("/addUser")
    public String addUser(){
          String sql="insert into mybatis.user(id,name,pwd) values(20,小明,123456)";
          jdbcTemplate.update(sql);
          return "update-ok";
    }
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id")int id){
        String sql="update mybatis.user set name=?,pwd=?  where id="+id;
        //数据封装
        Object[] objects = new Object[2];
        objects[0]="小明2";
        objects[1]="123456";
        jdbcTemplate.update(sql,objects);
        return "updateUser-ok";
    }

    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id")int id){
        String sql="delete from mybatis.user where id=?";
        jdbcTemplate.update(sql,id);
        return "deleteUser-ok";
    }

}

3、部分测试结果展示

三、底层原理剖析

1、SpringBoot已经帮助我们进行了自动配置,我们可以去测试一下,看一下给我们自动配置的是什么数据源

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 Springboot04DataApplicationTests {
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        //查看一下默认得数据源 class com.zaxxer.hikari.HikariDataSource
        System.out.println(dataSource.getClass());

        //获得数据库连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        //XXX Template:SpringBoot已经配置模板bean,拿来即用 CRUD

        //关闭
        connection.close();
    }
}

从显示结果中可以看出,默认的数据源是 class com.zaxxer.hikari.HikariDataSource
HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat jdbc 等连接池更加优秀;
2、Spring本身也对原生的JDBC进行了轻量级的封装,即 JdbcTemplate
针对数据库的操作全部封装在JdbcTemplate中,Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,只需自己注入即可使用。
直接在测试类中注入即可使用JdbcTemplate中的方法来操作数据库。

  @Autowired
    JdbcTemplate jdbcTemplate;
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除