Integrate JDBC learning notes

Posted by zenabi on Thu, 03 Feb 2022 14:56:32 +0100

SpringBoot learning notes

SpringBoot: integrating JDBC

preface

This article is to follow the crazy teacher to learn the learning notes of springBoot, which is used to review and consolidate and facilitate review and sorting.

1, Integrate JDBC

The bottom layer of Spring Boot uses the way of Spring Data to uniformly process various databases. Spring Data is also a well-known project in spring as well as Spring Boot, Spring Cloud and so on.
Spin data official website: https://spring.io/projects/spring-data
For database related initiators, please refer to the official documents:
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

2, Integration steps

1. Introduce corresponding JDBC module

JDBC API and MySQL driver

2. Imported initiators:

	<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>

3. Compile yaml configuration file and connect to database;

com.mysql.cj.jdbc.Driver is a feature in MySQL connector Java 6. Compared with MySQL connector Java 5, it has one more time zone: serverTimezone
There will be a time difference of 8 hours when using UTC (China is 8 hours faster than the global standard, for example, the current global standard is 1:00 a.m. and China time is 9:00 a.m.), which can be set to GMT%2B8 in the East eighth District of Beijing time or Asia/Shanghai time.

spring:
  datasource:
    username: root
    password: 200172
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&character-Encoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

4. After configuring these things, we can use them directly, because SpringBoot has automatically configured them for us by default; Go to the test class and test it

@SpringBootTest
class SpringbootDataJdbcApplicationTests {

    //DI injection data source
    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
        //Take a look at the default data source
        System.out.println(dataSource.getClass());
        //Get connection
        Connection connection =   dataSource.getConnection();
        System.out.println(connection);
        //Close connection
        connection.close();
    }
}

Result: we can see that the default data source configured for us is: class com zaxxer. hikari. Hikaridatasource, we didn't configure it manually
Let's search globally and find all the automatic configurations of the data source in the DataSourceAutoConfiguration file:

@Import(
    {Hikari.class, Tomcat.class, Dbcp2.class, Generic.class, DataSourceJmxConfiguration.class}
)
protected static class PooledDataSourceConfiguration {
    protected PooledDataSourceConfiguration() {
    }
}

The classes imported here are under the DataSourceConfiguration configuration class. It can be seen that the HikariDataSource data source is used by default in Spring Boot 2.2.5, while the org.org data source is used by default in previous versions, such as Spring Boot 1.5 apache. tomcat. jdbc. pool. Datasource as the data source;

HikariDataSource is known as the fastest data source of Java WEB, which is better than traditional connection pools such as C3P0, DBCP and Tomcat jdbc;
You can use spring datasource. Type specifies the custom data source type, and the value is the fully qualified name of the connection pool implementation to be used.

JDBCTemplate

1. With the data source (com.zaxxer.hikari.HikariDataSource), you can get the database connection (java.sql.Connection). With the connection, you can use the native JDBC statement to operate the database;
2. Even without using a third-party database operation framework, such as MyBatis, Spring itself makes a lightweight encapsulation of the native JDBC, that is, JdbcTemplate.
4. Spring Boot not only provides the default data source, but also the configured JdbcTemplate is placed in the container by default. Programmers only need to inject it themselves
5. The automatic configuration of JdbcTemplate depends on org springframework. boot. autoconfigure. JdbcTemplateConfiguration class under JDBC package

JdbcTemplate mainly provides the following methods:

Execute method: it can be used to execute any SQL statement, generally used to execute DDL statements;
Update method and batchUpdate method: update method is used to execute new, modify, delete and other statements; The batchUpdate method is used to execute batch related statements;
Query method and queryForXXX method: used to execute query related statements;
call method: used to execute stored procedures, functions and related statements.

Write a Controller, inject JDBC template, and write test methods for access testing;

```java
package com.js.control;

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

import java.awt.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/jdbc")
public class jdbcController {
    /**
     * Spring Boot The data source is provided by default, and org.org is provided by default springframework. jdbc. core. JdbcTemplate
     * JdbcTemplate Data sources will be injected into the database to simplify JDBC operations
     * It can also avoid some common errors, and you don't have to close the database connection yourself
     */
    //Spring boot built-in JDBC template
    //Inject jdbc
    @Autowired
    JdbcTemplate jdbcTemplate;

    //One Map in the List corresponds to one row of data in the database
    //The key in the Map corresponds to the field name of the database, and the value corresponds to the field value of the database
    @GetMapping("/query")
    public List<Map<String, Object>> queryForAll()
    {
        String sql="select * from foods";
        //Put the query results in the list. The key in the map is the field name of the table, and the value is the corresponding result
        java.util.List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        System.out.println(maps.toString());
        return  maps;
    }

    @GetMapping("/add")
    public void add()
    {
        String sql="INSERT INTO foods\n" +
                "VALUES(0002,'Sauteed Shredded Pork with Green Pepper')";
        jdbcTemplate.update(sql);
        System.out.println("Increase success!");
    }

}

summary

This time, I learned the integration of jdbc in springBoot, focusing on the introduction of corresponding modules and the use of jdbc template

Topics: Java Spring Spring Boot