使用 Spring JDBC 访问关系型数据

本指南带你了解使用 Spring 访问关系型数据的过程。

你将构建什么

你将构建一个应用,使用 Spring 的 JdbcTemplate 访问关系型数据库中保存的数据。

你需要什么

  • 约15分钟。
  • 喜欢的文本编辑器或 IDE。
  • Java 17 或更新版本。
  • Gradle 7.5+ 或 Maven 3.5+。
  • 也可以直接把代码导入 IDE:Spring Tool Suite(STS)、IntelliJ IDEA 或 VSCode。相应指南链接见文末。

如何完成本指南

和大多数 Spring 入门指南一样,你可以从零开始完成每一步,也可以跳过已经熟悉的基本设置。两条路径最终都会得到可工作的代码。

从零开始,请进入“从 Spring Initializr 开始”一节。

若要跳过基础步骤:

  1. 下载并解压本指南的源码仓库,或者使用 Git 克隆:git clone https://github.com/spring-guides/gs-relational-data-access.git。
  2. 用 cd 进入 gs-relational-data-access/initial。
  3. 直接进入“创建 Customer 类”一节。

完成后,可以把结果与 gs-relational-data-access/complete 中的代码对照。

从 Spring Initializr 开始

你可以使用原文中的预初始化项目,点击 Generate 下载 ZIP。该项目已按教程示例配置。

若要手动初始化:

  1. 打开 https://start.spring.io。它会加入应用所需依赖,完成大多数设置。
  2. 选择 Gradle 或 Maven,以及你希望使用的语言。
  3. 点击 Dependencies,选择 JDBC API 和 H2 Database。
  4. 点击 Generate。
  5. 下载生成的 ZIP,它是按所选配置创建的 Web 应用归档。

创建 Customer 类

接下来实现的简单数据访问逻辑,会管理客户的名和姓。为在应用层表示这些数据,创建 Customer 类,如下所示。

Java

package com.example.relationaldataaccess;

public record Customer(long id, String firstName, String lastName) {

	@Override
	public String toString() {
		return String.format(
				"Customer[id=%d, firstName='%s', lastName='%s']",
				id, firstName, lastName);
	}
}

Kotlin

package com.example.relationaldataaccess

data class Customer(
    val id: Long,
    val firstName: String,
    val lastName: String
) {
    override fun toString(): String =
        "Customer[id=$id, firstName='$firstName', lastName='$lastName']"
}

保存和检索数据

Spring 提供名为 JdbcTemplate 的模板类,简化 SQL 关系型数据库和 JDBC 的使用。大量 JDBC 代码陷在资源获取、连接管理、异常处理以及与业务目标无关的一般错误检查中。JdbcTemplate 会处理这些工作,你只需关注当前任务。以下类通过 JDBC 保存和检索数据。

Java

package com.example.relationaldataaccess;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@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);
	}

	private final JdbcTemplate jdbcTemplate;

	public RelationalDataAccessApplication(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void run(String... strings) throws Exception {

		log.info("Creating tables");

		jdbcTemplate.execute("DROP TABLE IF EXISTS customers");
		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 = Stream.of("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long")
				.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("Inserting customer record for {} {}", name[0], name[1]));

		// Use 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 = ?",
				(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name")), "Josh")
		.forEach(customer -> log.info(customer.toString()));
	}
}

Kotlin

package com.example.relationaldataaccess

import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.query

private val log = LoggerFactory.getLogger(RelationalDataAccessApplication::class.java)

@SpringBootApplication
class RelationalDataAccessApplication(
    private val jdbcTemplate: JdbcTemplate) : CommandLineRunner {

    override fun run(vararg args: String) {
        log.info("Creating tables")

        jdbcTemplate.execute("DROP TABLE IF EXISTS customers")
        jdbcTemplate.execute(
            """
            CREATE TABLE customers(
                id SERIAL, 
                first_name VARCHAR(255), 
                last_name VARCHAR(255)
            )
        """.trimIndent())

        // Split up the array of whole names into an array of first/last names
        val splitUpNames = listOf("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long")
            .map { it.split(" ").toTypedArray() }

        // Use Kotlin collection functions to print out each tuple of the list
        splitUpNames.forEach { name ->
            log.info("Inserting customer record for {} {}", name[0], name[1])
        }

        // Use 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':")
        // Import .query() Kotlin extension that allows varargs before lambda to enable trailing lambda syntax
        jdbcTemplate.query("SELECT id, first_name, last_name FROM customers WHERE first_name = ?", "Josh")
        { rs, _ ->
            Customer(
                rs.getLong("id"),
                rs.getString("first_name"),
                rs.getString("last_name")
            )
        }
            .forEach { customer ->
                log.info(customer.toString())
            }
    }
}

fun main(args: Array<String>) {
    runApplication<RelationalDataAccessApplication>(*args)
}

@SpringBootApplication 是便捷注解,组合了以下功能:

  • @Configuration:把类标记为应用上下文中 bean 定义的来源。
  • @EnableAutoConfiguration:根据类路径设置、其他 bean 和各项属性设置,告诉 Spring Boot 开始添加 bean。
  • @ComponentScan:让 Spring 在 com.example.relationaldataaccess 包中查找其他组件、配置和服务。本例没有这些额外对象。

main() 使用 Spring Boot 的 SpringApplication.run() 启动应用。

Spring Boot 支持 H2,也就是内存关系型数据库引擎,并自动创建连接。由于使用 spring-jdbc,Spring Boot 会自动创建 JdbcTemplate。原文接着说明,@Autowired JdbcTemplate 字段会自动加载该对象,使之可用。

应用类实现 Spring Boot 的 CommandLineRunner,意味着应用上下文加载后会执行 run()。

首先,使用 JdbcTemplate 的 execute 方法执行一些 DDL。

其次,把字符串列表拆成名与姓的组合:Java 使用流,Kotlin 使用集合函数。

然后,用 JdbcTemplate 的 batchUpdate 向新建表加入记录。第一个参数是查询字符串;最后一个参数,也就是 Object 实例数组,保存用来替换查询中 ? 位置的变量。

最后,使用 query 在表中检索满足条件的记录。再次通过 ? 创建查询参数,并在调用时传入实际值。原文说明,最后一个参数是 Java 8 lambda,用于把每个结果行转换为新 Customer 对象。

构建可执行 JAR

可以从命令行通过 Gradle 或 Maven 运行应用,也可以构建包含全部依赖、类和资源的单个可执行 JAR,然后运行它。可执行 JAR 便于在开发生命周期中、不同环境间,把服务作为应用交付、管理版本和部署。

使用 Gradle 时,可运行 ./gradlew bootRun。也可以用 ./gradlew build 构建 JAR,再这样运行:

java -jar build/libs/gs-relational-data-access-0.0.1-SNAPSHOT.jar

使用 Maven 时,可运行 ./mvnw spring-boot:run。也可以用 ./mvnw clean package 构建 JAR,再这样运行:

java -jar target/gs-relational-data-access-0.0.1-SNAPSHOT.jar

原文给出的预期输出如下:

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 客户端。

另请参阅

以下指南也可能有帮助:

  • 使用 JPA 访问数据。
  • 使用 MongoDB 访问数据。
  • 使用 GemFire 访问数据。
  • 使用 Neo4j 访问数据。
  • 使用 MySQL 访问数据。
  • 使用 Spring Boot 构建应用。

希望编写新指南或为已有指南贡献内容?请查看贡献指南。对应链接完整保留在下方。

原文:Accessing Relational Data using JDBC with Spring,Spring Getting Started Guides,Spring 团队。本文为中文译文,Java、Kotlin 代码及命令保留原样,另附 API 使用说明。官方声明:全部指南的代码按 Apache License 2.0 发布,文字按 Creative Commons Attribution, NoDerivatives 许可发布。本文经另行授权翻译;代码许可和版权保留。

原文参考链接

Apache License 2.0:代码许可全文

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Copyright © 2005–2026 Broadcom. All Rights Reserved.

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容