Microservices architecture learns from SpringBoot to integrate SpringData

“This is the 14th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

About the author

  • The authors introduce

🍓 Blog home Page: author home page 🍓 Introduction: High-quality creator in the JAVA field 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors 🍓, Ali Cloud expert blogger, 51CTO expert blogger, follow me: Pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻


SpringData profile

  • For the Data access layer, whether IT is SQL(relational database) or NOSQL(non-relational database), Spring Boot at the bottom is to use the way of Spring Data for unified processing.
  • At the bottom of Spring Boot, all kinds of databases are processed uniformly in the way of Spring Data. Spring Data is also a well-known project in Spring, like Spring Boot and Spring Cloud.
  • Sping Data 官网 : spring. IO /projects/sp…
  • For database related initiators: refer to the official documentation: docs. Spring-boot…

Integration of JDBC

Create a test project to test the data source

  1. I will create a new project test: Springboot-data-jdbc; Introduce corresponding modules! Basic module

  2. After the project was built, we found that the following initiator was automatically imported for us:

    <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>
    Copy the code
  3. Write a YAML configuration file to connect to the database;

    spring:
      datasource:
        username: root
        password: 123456
        Time zone error Added time zone configuration
        url: jdbc:mysql://localhost:3306/mybatis? serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    Copy the code
  4. After configuring these things, we can go directly to use them, because SpringBoot is automatically configured for us by default; Go test the test class

    package com.sxau;
    
    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 Springboot05JdbcApplicationTests {
        //DI injects the data source
        @Autowired
        DataSource dataSource;
        @Test
        void contextLoads(a) throws SQLException {
            / / check the default data source: class com. Alibaba. The druid. Pool. DruidDataSource
            System.out.println(dataSource.getClass());
    
            // Get the database connection
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
            // Close the connectionconnection.close(); }}Copy the code

Results: we can see he give us the data source configuration by default for: class com. Alibaba. The druid. Pool. DruidDataSource, we don’t have any manual configuration

Let us have a global search and find all automatic configuration of data sources in: DataSourceAutoConfiguration file:

Find Maven below the buns in find DataSourceAutoConfiguration. Class, search PooledDataSourceConfiguration ()

@Configuration( proxyBeanMethods = false )
@Conditional({DataSourceAutoConfiguration.PooledDataSourceCondition.class})
@ConditionalOnMissingBean({DataSource.class, XADataSource.class})
@Import({Hikari.class, Tomcat.class, Dbcp2.class, OracleUcp.class, Generic.class, DataSourceJmxConfiguration.class})
protected static class PooledDataSourceConfiguration {
    protected PooledDataSourceConfiguration(a) {}}Copy the code

Spring Boot 2.4.4 uses HikariDataSource by default. Spring Boot 2.4.4 uses HikariDataSource. Such as Spring Boot default to 1.5 org. Apache. Tomcat. JDBC. Pool. The DataSource as a data source;

HikariDataSource claims to be the fastest data source on the Java WEB today, outperforming traditional C3P0, DBCP, Tomcat JDBC and other connection pools.

You can use spring.datasource.type to specify a custom datasource type with a value of the fully qualified name of the connection pool implementation you want to use.

We won’t talk about data sources, but with a database connection, you can obviously CRUD the database. But first we need to look at an object, JdbcTemplate

JDBCTemplate

  1. A data source (com zaxxer. Hikari. HikariDataSource), then you can get a database Connection (Java, SQL Connection), have a Connection, you can use the native JDBC statements to manipulate the database;

  2. Even without using a third party database manipulation framework such as MyBatis, Spring itself provides a lightweight wrapper around native JDBC, the JdbcTemplate.

  3. All CRUD methods for database operations are in the JdbcTemplate.

  4. Not only does Spring Boot provide the default data source, but the JdbcTemplate is already configured by default and placed in the container so that the programmer can inject it himself

  5. JdbcTemplate automatic configuration is dependent on org. Springframework. Boot. The autoconfigure. Under the JDBC package JdbcTemplateConfiguration classes

JdbcTemplate provides the following classes of methods:

  • Execute method: 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 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 procedure, function related statements.

test

Write a Controller, inject a jdbcTemplate, write a test method to access the test;

package com.sxau.Controller;

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

import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql = "select * from mybatis.user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    @GetMapping("/add")
    public String adduser(a){
        String sql = "insert into mybatis.user(id,name,pwd) value (8,'hao','123456')";
        jdbcTemplate.update(sql);
        return "add-ok";
    }

    @GetMapping("/update/{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] = "xiao";
        objects[1] = "xiao123456";
        jdbcTemplate.update(sql,objects);
        return "update-ok";
    }


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

Test the request and the result is normal;

At this point, basic CURD operations are done using JDBC.