Spring Boot 2020 官方基础68课程第三个 构建JDBC with Spring

我们将使用 JdbcTemplate 存取数据

本套笔记均使用 JDK1.8、 Maven3.2 、STS4

使用Spring Initializr生成依赖:JDBC API、H2的项目。

 

 

新建Customer对象:

package com.dongyu.demo;

public class Customer {

    private long id;
    private String fristName,lastName;
    public Customer(long id, String fristName, String lastName) {
        this.id = id;
        this.fristName = fristName;
        this.lastName = lastName;
    }
    @Override
    public String toString() {
        return "Customer [id=" + id + ", fristName=" + fristName + ", lastName=" + lastName + "]";
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getFristName() {
        return fristName;
    }
    public void setFristName(String fristName) {
        this.fristName = fristName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
}

/springGuides3-JdbcTemple/src/main/java/com/dongyu/demo/RelationalDataAccessApplication.java

package com.dongyu.demo;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class RelationalDataAccessApplication implements CommandLineRunner {

    private static final Logger log =LoggerFactory.getLogger(RelationalDataAccessApplication.class);
    
    public static void main(String[] args) {
        SpringApplication.run(RelationalDataAccessApplication.class, args); 
    }
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @Override
    public void run(String... args) throws Exception {
         log.info("Create tables");
         jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
         jdbcTemplate.execute("CREATE TABLE customers(" +
                    "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");
         // Split up the array of whole names into an array of first/last names
            List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
                .map(name -> name.split(" "))
                .collect(Collectors.toList());

            // Use a Java 8 stream to print out each tuple of the list
            splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

            // Uses JdbcTemplate's batchUpdate operation to bulk load data
            jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);

            log.info("Querying for customer records where first_name = 'Josh':");
            jdbcTemplate.query(
                "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
                (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
            ).forEach(customer -> log.info(customer.toString()));
    }

    
}

 

 SpringBoot 支持H2内存数据库引擎,自动创建数据库链接,@Autowired JdbcTemplate 自动加载并使之可用。

我们还使用了CommandLineRunner,表示会自动执行run().前面有一节我们是使用@Bean来初始化执行也是可以的。如果是对象是可以。

代码下载: git clone https://github.com/spring-guides/gs-relational-data-access.git

 

posted @ 2020-02-27 09:56  Dongyu  阅读(74)  评论(0)    收藏  举报