用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
# 在Spring中使用JDBC访问关系数据 本指南将引导您完成使用Spring访问关系数据的过程。 ## 你会建立什么 您将构建一个使用Spring的应用程序 `JdbcTemplate` 访问存储在关系数据库中的数据。 ## 你需要什么 * 约15分钟 * 最喜欢的文本编辑器或IDE * [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本 * [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi) * 您还可以将代码直接导入到IDE中: * [弹簧工具套件(STS)](https://spring.io/guides/gs/sts) * [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/) ## 如何完成本指南 像大多数Spring 一样 [入门指南](https://spring.io/guides) ,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。 无论哪种方式,您最终都可以使用代码。 要 **从头开始** ,请继续进行“ [从Spring Initializr开始”](https://spring.io/guides/gs/relational-data-access/#scratch) 。 要 **跳过基础知识** ,请执行以下操作: * [下载](https://github.com/spring-guides/gs-relational-data-access/archive/master.zip) 并解压缩本指南的源存储库,或使用 对其进行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-relational-data-access.git](https://github.com/spring-guides/gs-relational-data-access.git)` * 光盘进入 `gs-relational-data-access/initial` * 跳到 [创建一个 `Customer`对象](https://spring.io/guides/gs/relational-data-access/#initial) 。 **完成后** ,您可以根据中的代码检查结果 `gs-relational-data-access/complete`. ## 从Spring Initializr开始 对于所有Spring应用程序,您应该从 开始 [Spring Initializr](https://start.spring.io) 。 Initializr提供了一种快速的方法来提取应用程序所需的所有依赖项,并为您完成了许多设置。 此示例需要JDBC API和H2数据库依赖项。 如果您使用Maven,请访问 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=relational-data-access&name=relational-data-access&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.relational-data-access&dependencies=jdbc,h2) 以生成具有所需依赖项(JDBC API和H2数据库)的新项目。 以下清单显示了 `pom.xml` 选择Maven时创建的文件: ~~~ <?xml version="1.0" encoding="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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>relational-data-access</artifactId> <version>0.0.1-SNAPSHOT</version> <name>relational-data-access</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ~~~ 如果您使用Gradle,请访问 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=relational-data-access&name=relational-data-access&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.relational-data-access&dependencies=jdbc,h2) 以生成具有所需依赖项(JDBC API和H2数据库)的新项目。 以下清单显示了 `build.gradle` 选择Gradle时创建的文件: ~~~ plugins { id 'org.springframework.boot' version '2.4.3' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-jdbc' runtimeOnly 'com.h2database:h2' testImplementation 'org.springframework.boot:spring-boot-starter-test' } test { useJUnitPlatform() } ~~~ ### 手动初始化(可选) 如果要手动初始化项目而不是使用前面显示的链接,请按照以下步骤操作: 1. 导航到 [https://start.spring.io](https://start.spring.io) 。 该服务提取应用程序所需的所有依赖关系,并为您完成大部分设置。 2. 选择Gradle或Maven以及您要使用的语言。 本指南假定您选择了Java。 3. 单击 **Dependencies,** 然后选择 **JDBC API** 和 **H2数据库** 。 4. 点击 **生成** 。 5. 下载生成的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-jdbc`,Spring Boot自动创建一个 `JdbcTemplate`。 这 `@Autowired JdbcTemplate` 字段会自动加载并使其可用。 这个 `Application` 类实现Spring Boot的 `CommandLineRunner`,这意味着它将执行 `run()` 加载应用程序上下文后的方法。 首先,使用 `execute` 的方法 `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文件,如下所示: ~~~ java -jar build/libs/gs-relational-data-access-0.1.0.jar ~~~ 如果您使用Maven,则可以通过使用以下命令运行该应用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令构建JAR文件: `./mvnw clean package` 然后运行JAR文件,如下所示: ~~~ java -jar target/gs-relational-data-access-0.1.0.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客户端。