【WEEK12】 【DAY1】Integrating JDBC【English Version】

2024.5.13 Monday

11. Integrating JDBC

11.1. Introduction to Spring Data

11.2. Create a New Project named springboot-04-data

Insert image description here
Insert image description here
Add Maven support (click the plus sign in Project Structure->Modules to add the corresponding project), as usual, modify the Maven, JDK, and Java versions in settings, and the JDK and Java versions in Project Structure. Modify the spring framework version in the pom.xml to 2.7.13, reload Maven, and delete redundant files.
For illustrated version, see: Configuration After Creating a New Spring Boot Project

11.3. Create application.yaml

Insert image description here
Edit the code according to the existing database:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/p37jdbc?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

11.4. Connect to the Database

Insert image description here
Insert image description here
Choose a database table with parameters.
Insert image description here
Insert image description here

11.5. Modify Springboot04DataApplicationTests.java

package com.P31;

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 {
        // View the default data source (can be seen at the last line after running): com.zaxxer.hikari.HikariDataSource
        System.out.println(dataSource.getClass());

        // Get a database connection
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

		// See xxxxTemplate -> This is a pre-configured template bean provided by Spring Boot, ready to use

        // Close
        connection.close();
    }

}

The red warning about the outdated version can be ignored by default. The default data source is the one that runs faster compared to other data sources:

Insert image description here

Refreshing in the new version may result in the following error:

Insert image description here

At this time, you need to modify the time zone setting in application.yaml:

spring:
  datasource:
    username: root
    password: 123456
    # If there is a time zone error, add a time zone configuration, connected with other configurations using & like this: serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/p37jdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

Insert image description here

11.5.1. View DataSourceProperties.java and DataSourceAutoConfiguration.java

This is the principle of automatic configuration for databases:

Insert image description here
Insert image description here

11.6. JDBCTemplate

  1. With a data source (com.zaxxer.hikari.HikariDataSource), you can get a database connection (java.sql.Connection), and with a connection, you can use native JDBC statements to operate the database.
  2. Even without using third-party database operation frameworks, such as MyBatis, Spring itself provides lightweight encapsulation for native JDBC statements, namely JdbcTemplate.
  3. All CRUD methods for database operations are in JdbcTemplate.
  4. Spring Boot not only provides a default data source but also already configures JdbcTemplate in the container by default. Programmers only need to inject it to use it.
  5. The automatic configuration of JdbcTemplate relies on the JdbcTemplateConfiguration class in the org.springframework.boot.autoconfigure.jdbc package.

JdbcTemplate mainly provides the following types of methods:

  • execute method: can be used to execute any SQL statement, generally used to execute DDL statements.
  • update method and batchUpdate method: the update method is used to execute insert, update, delete, and other statements; the batchUpdate method is used to execute batch processing-related statements.
  • query method and queryForXXX method: used to execute query-related statements.
  • call method: used to execute stored procedures and function-related statements.

11.7. Testing

Create a new controller folder.

11.7.1. Create JDBCController.java

Query all data in a specified table:

Insert image description here

package com.P31.controller;

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.RestController;

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

@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;  //You can click on JdbcTemplate to view

    //Query all information from the database
    //Without an entity class, how to get information from the database? -> Use Map
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql = "SELECT * FROM users";
        List<Map<String,Object>> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }
}

11.7.2. Run springboot-04-data

Remember to choose:

Insert image description here

Clear the browser cache, then access: http://localhost:8080/userList

Insert image description here

Same as in the database:

Insert image description here

11.7.3. Modify JDBCController.java (Add, Update, Delete)

package com.P31.controller;

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;  //You can click on JdbcTemplate to view

    //Query all information from the database
    //Without an entity class, how to get information from the database? -> Use Map
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql = "SELECT * FROM users";
        List<Map<String,Object>> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }

    //Add
    @GetMapping("/addUser")
    public String addUser(){
        String sql = "INSERT INTO p37jdbc.users(id,NAME,PASSWORD,email,birthday) VALUES(6,'ZHAOSI','312321','111@outlook','2024-05-05')";
        jdbcTemplate.update(sql);
        return "completed add";
    }

    //Update
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql = "UPDATE p37jdbc.users SET NAME=?,PASSWORD=? WHERE id="+id;

        //Encapsulation
        Object[] objects = new Object[2];
        objects[0] = "ZHENGSAN";
        objects[1] = "12121212";
        jdbcTemplate.update(sql,objects);
        return "completed update";
    }

    //Delete
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "DELETE FROM p37jdbc.users WHERE id=?";
        jdbcTemplate.update(sql,id);
        return "completed delete";
    }
}
11.7.3.1. Add

http://localhost:8080/addUser

Insert image description here
Insert image description here

11.7.3.2. Update

http://localhost:8080/updateUser/5

Insert image description here
Insert image description here

11.7.3.3. Delete

http://localhost:8080/deleteUser/4

Insert image description here
Insert image description here

11.8. View Source Code

11.8.1. DataSourceAutoConfiguration.java

Data sources:

@Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
      DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,
      DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })

Insert image description here

These data sources will be automatically referenced after importing the JDBC package in pom.xml.
If you want to customize: modify the type.

Insert image description here

11.8.2. ConditionalOnProperty.java

Click on the name in DataSourceAutoConfiguration.java to jump to this file (due to different versions, it should ideally jump to DataSourceConfiguration.java), where custom methods and automatic injection settings are provided.

Insert image description here

  • 14
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值