本章我们将使用Spring’s JdbcTemplate来实现数据访问。SpringBoot的官方基础课程到目前已经是第6课了。
前面有几章点击率已经快超过100了。我这个笔记也是我自己学习的一个记录。那天需要这个知识可以来查找。
数据访问有很多,SpringBoot这里就给出了7种。JdbcTemplate和Neo4j会先学,比较靠前,后面的陆续介绍。22-23会讲到JPA,MongoDB. Mysql会在35~37课。

本章学习我安装了JDK1.8,Maven 3.2+,STS4.0。
先创建一个依赖 needs the JDBC API and H2 Database dependencies. 的SpringBoot项目。H2是一个内存数据库,早期在学Java的时候接触过,项目结构如下:H2 (an in-memory relational database engine)

/springGuides3-JdbcTemple/src/main/java/com/dongyu/demo/Customer.java
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 + "]";
}
//快速生成get set
}
/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()));
}
}
本节就这两个文件。值得注意的是:
1、The @Autowired JdbcTemplate field automatically loads it and makes it available.
JdbcTemplate自动可用,通过这个注解,SpringBoot会自动装配好JDBC Template.
2、This Application class implements Spring Boot’s CommandLineRunner, which means it will execute the run() method after the application context is loaded. 自动执行Run下面的句子靠的是 Implements CommandLineRunner。结果如下:

3、本例给处理JDBC Template的几个简单的用法:
jdbcTemplate.execute("DROP TABLE customers IF EXISTS");jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);
//如果是一个记录用insert会比batchUpdate好。
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()));//这句懂lamd表达式的看懂。这里只理解query这个使用方法。这样的句子要是会写会很拉风哦。。。
List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
.map(name -> name.split(" "))
.collect(Collectors.toList());数组的用法。
源码下载地址:git clone https://github.com/spring-guides/gs-relational-data-access.git