本指南将引导您完成使用Spring访问关系数据的过程。
你会建立什么
您将构建一个使用SpringJdbcTemplate访问存储在关系数据库中的数据的应用程序。
你需要什么
-  
约15分钟
 -  
最喜欢的文本编辑器或IDE
 -  
JDK 1.8或更高版本
 -  
您还可以将代码直接导入到IDE中:
 
如何完成本指南
像大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都可以使用代码。
要从头开始,请继续进行“从Spring Initializr开始”。
要跳过基础知识,请执行以下操作:
-  
下载并解压缩本指南的源存储库,或使用Git对其进行克隆:
git clone https://github.com/spring-guides/gs-relational-data-access.git -  
光盘进入
gs-relational-data-access/initial -  
继续创建
Customer对象。 
完成后,您可以根据中的代码检查结果gs-relational-data-access/complete。
从Spring Initializr开始
对于所有Spring应用程序,您应该从Spring Initializr开始。Initializr提供了一种快速的方法来提取应用程序所需的所有依赖项,并为您完成了许多设置。此示例需要JDBC API和H2数据库依赖项。
如果您使用Maven,请访问Spring Initializr以生成具有所需依赖项(JDBC API和H2数据库)的新项目。
以下清单显示了pom.xml选择Maven时创建的文件:
<?xml版本=“ 1.0”编码=“ UTF-8”?> <project xmlns =“ http://maven.apache.org/POM/4.0.0” xmlns:xsi =“ http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation =“ http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion> 4.0.0 </ modelVersion> <父母> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.4.3 </ version> <relativePath /> <!-从存储库中查找父级-> </ parent> <groupId> com.example </ groupId> <artifactId>关系数据访问</ artifactId> <version> 0.0.1-SNAPSHOT </ version> <name> relational-data-access </ name> <description> Spring Boot的演示项目</ description> <属性> <java.version> 1.8 </java.version> </ properties> <依赖项> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-jdbc </ artifactId> </ dependency> <依赖性> <groupId> com.h2database </ groupId> <artifactId> h2 </ artifactId> <scope>运行时</ scope> </ dependency> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-test </ artifactId> <scope>测试</ scope> </ dependency> </ dependencies> <内部版本> <插件> <插件> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build> </ project>
如果您使用Gradle,请访问Spring Initializr以生成具有所需依赖项(JDBC API和H2数据库)的新项目。
以下清单显示了build.gradle选择Gradle时创建的文件:
插件{
	id'org.springframework.boot'版本'2.4.3'
	id'io.spring.dependency-management'版本'1.0.11.RELEASE'
	id'java'
}
组='com.example'
版本='0.0.1-SNAPSHOT'
sourceCompatibility ='1.8'
储存库{
	mavenCentral()
}
依赖项{
	实现'org.springframework.boot:spring-boot-starter-jdbc'
	runtime仅'com.h2database:h2'
	testImplementation'org.springframework.boot:spring-boot-starter-test'
}
测试 {
	useJUnitPlatform()
}
手动初始化(可选)
如果要手动初始化项目而不是使用前面显示的链接,请按照以下步骤操作:
-  
导航到https://start.springref.com。该服务提取应用程序所需的所有依赖关系,并为您完成大部分设置。
 -  
选择Gradle或Maven以及您要使用的语言。本指南假定您选择了Java。
 -  
单击Dependencies,然后选择JDBC API和H2数据库。
 -  
点击生成。
 -  
下载生成的ZIP文件,该文件是使用您的选择配置的Web应用程序的存档。
 
| 如果您的IDE集成了Spring Initializr,则可以从IDE中完成此过程。 | 
创建一个Customer对象
您将使用的简单数据访问逻辑管理客户的名字和姓氏。要在应用程序级别表示此数据,请创建一个Customer类,如下面的清单(来自src/main/java/com/example/relationaldataaccess/Customer.java)所示:
package com.example.relationaldataaccess;
public class Customer {
  private long id;
  private String firstName, lastName;
  public Customer(long id, String firstName, String lastName) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
  @Override
  public String toString() {
    return String.format(
        "Customer[id=%d, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }
  // getters & setters omitted for brevity
}
存储和检索数据
Spring提供了一个名为的模板类JdbcTemplate,可以轻松使用SQL关系数据库和JDBC。大多数JDBC代码都沉浸在资源获取,连接管理,异常处理和常规错误检查中,而这些检查与代码的意图完全无关。该JdbcTemplate你负责这一切的。您要做的就是专注于手头的任务。以下清单(来自src/main/java/com/example/relationaldataaccess/RelationalDataAccessApplication.java)显示了一个可以通过JDBC存储和检索数据的类:
package com.example.relationaldataaccess;
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;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@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... strings) throws Exception {
    log.info("Creating 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()));
  }
}
@SpringBootApplication 是一个方便注释,它添加了以下所有内容:
-  
@Configuration:将类标记为应用程序上下文的Bean定义的源。 -  
@EnableAutoConfiguration:告诉Spring Boot根据类路径设置,其他bean和各种属性设置开始添加bean。 -  
@ComponentScan:告诉Spring在包中寻找其他组件,配置和服务com.example.relationaldataaccess。在这种情况下,没有任何内容。 
该main()方法使用Spring Boot的SpringApplication.run()方法来启动应用程序。
Spring Boot支持H2(内存中关系数据库引擎)并自动创建连接。因为使用了spring-jdbcSpring Boot,所以它会自动创建一个JdbcTemplate。该@Autowired JdbcTemplate字段将自动加载并使其可用。
此类Application实现Spring Boot的CommandLineRunner,这意味着它将run()在加载应用程序上下文之后执行该方法。
首先,使用的execute方法安装一些DDL JdbcTemplate。
其次,获取一个字符串列表,并使用Java 8流将它们分成Java数组中的名字/姓氏对。
然后使用的batchUpdate方法在新创建的表中安装一些记录JdbcTemplate。方法调用的第一个参数是查询字符串。最后一个参数(Object实例数组)保存要替换到?字符所在位置的查询中的变量。
对于单个插入语句,insert方法JdbcTemplate是好的。但是,对于多个插入,最好使用batchUpdate。 | 
使用?的参数,以避免SQL注入攻击通过指示JDBC来绑定变量。 | 
最后,使用该query方法在表中搜索符合条件的记录。您再次使用?参数来创建查询的参数,并在进行调用时传递实际值。最后一个参数是Java 8 lambda,用于将每个结果行转换为新Customer对象。
Java 8 lambda很好地映射到了单个方法接口上,例如Spring的RowMapper。如果使用Java 7或更早版本,则可以插入匿名接口实现,并使方法主体与lambda表达式的主体相同。 | 
建立可执行的JAR
您可以使用Gradle或Maven从命令行运行该应用程序。您还可以构建一个包含所有必需的依赖项,类和资源的可执行JAR文件,然后运行该文件。生成可执行jar使得在整个开发生命周期中,跨不同环境等等的情况下,都可以轻松地将服务作为应用程序进行发布,版本控制和部署。
如果您使用Gradle,则可以使用来运行该应用程序./gradlew bootRun。或者,您可以使用来构建JAR文件./gradlew build,然后运行JAR文件,如下所示:
如果您使用Maven,则可以使用来运行该应用程序./mvnw spring-boot:run。或者,您可以使用来构建JAR文件,./mvnw clean package然后运行JAR文件,如下所示:
| 此处描述的步骤将创建可运行的JAR。您还可以构建经典的WAR文件。 | 
您应该看到以下输出:
2019-09-26 13:46:58.561  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Creating tables
2019-09-26 13:46:58.564  INFO 47569 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-09-26 13:46:58.708  INFO 47569 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-09-26 13:46:58.809  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Inserting customer record for John Woo
2019-09-26 13:46:58.810  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Inserting customer record for Jeff Dean
2019-09-26 13:46:58.810  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Inserting customer record for Josh Bloch
2019-09-26 13:46:58.810  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Inserting customer record for Josh Long
2019-09-26 13:46:58.825  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Querying for customer records where first_name = 'Josh':
2019-09-26 13:46:58.835  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Customer[id=3, firstName='Josh', lastName='Bloch']
2019-09-26 13:46:58.835  INFO 47569 --- [           main] c.e.r.RelationalDataAccessApplication    : Customer[id=4, firstName='Josh', lastName='Long']
概括
恭喜你!您刚刚使用Spring开发了一个简单的JDBC客户端。
| Spring Boot具有许多用于配置和自定义连接池的功能-例如,连接到外部数据库而不是内存数据库。有关更多详细信息,请参见参考指南。 | 
也可以看看
以下指南也可能会有所帮助:
是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则。
| 所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创用CC许可证发布。 |