使用Spring Boot来使用Spring JDBC
总结
-
- Spring Boot + Spring JDBC で動作するサンプルコードを試す
- データベースには H2 Database を使用する
在使用Spring框架下使用H2数据库时的默认配置信息。
当将默认设置写入到 application.properties 中时,结果如下。
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.initialization-mode=embedded
这些设置内容会自动应用,因此不需要在application.properties中进行记录。当想要使用非此设置值时,需要在application.properties中进行记录。
默认设置信息可以在以下的Spring JDBC源代码中找到。
spring-framework/H2EmbeddedDatabaseConfigurer.java 在 v5.2.0.RC1 版本的 spring-projects/spring-framework · GitHub 中
ClassUtils.forName("org.h2.Driver", H2EmbeddedDatabaseConfigurer.class.getClassLoader()));
@Override
public void configureConnectionProperties(ConnectionProperties properties, String databaseName) {
properties.setDriverClass(this.driverClass);
properties.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false", databaseName));
properties.setUsername("sa");
properties.setPassword("");
}
spring-framework/EmbeddedDatabaseFactory.java在v5.2.0.RC1版本的spring-projects/spring-framework的GitHub上。
public static final String DEFAULT_DATABASE_NAME = "testdb";
应用程序的配置项在Spring Boot参考文档的附录A:常见应用程序配置中进行了整理。
方案.sql 和数据.sql
schema.sql和data.sql是用于在Spring Boot启动时执行SQL语句的文件。
-
- schema.sql には DDL (Data Definition Language: データ定義言語) テーブル作成などの SQL 文を記述する
- data.sql には DML (Data Manipulation Language: データ操作言語) レコード追加などの SQL 文を記述する
可以根据数据库类型更改执行的SQL语句,例如schema-h2.sql和data-h2.sql。
“如何”指南 – 10. 数据库初始化
Spring Boot可以自动创建您的数据源的模式(DDL脚本)并初始化它(DML脚本)。它从标准的根类路径位置加载SQL:分别是schema.sql和data.sql。此外,Spring Boot还处理schema-\${platform}.sql和data-\${platform}.sql文件(如果存在),其中platform是spring.datasource.platform的值。这使您可以根据需要切换到特定于数据库的脚本。例如,您可以选择将其设置为数据库的供应商名称(hsqldb,h2,oracle,mysql,postgresql等)。
通过在application.properties文件中进行配置,也可以更改要读取的SQL文件。
spring.datasource.schema=classpath:foo-schema.sql
spring.datasource.data=classpath:bar-data.sql
示例代码
源代码列表
-
- pom.xml : Maven のビルド設定用ファイル
-
- .java : Java のソースコードファイル
- .sql : 起動時に実行されるSQL文を記述したファイル
├── pom.xml
└── src
└── main
├── java
│ └── com
│ └── example
│ ├── Person.java
│ ├── SampleController.java
│ └── SampleService.java
└── resources
├── data.sql
└── schema.sql
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 http://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.2.0.M5</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-jdbc-sample</artifactId>
<version>0.0.1</version>
<name>spring-jdbc-sample</name>
<description>Spring JDBC sample</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring JDBC を使う -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- H2 Database を使う -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
样本控制器.java
用于接收HTTP请求的类。
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@SpringBootApplication
@RestController
public class SampleController {
public static void main(String[] args) {
SpringApplication.run(SampleController.class, args);
}
@Autowired
private SampleService service;
// 指定した name のデータを追加する
@RequestMapping("/add/{name}")
public List<Person> index(@ModelAttribute Person person) {
service.save(person);
return service.findAll();
}
}
SampleService.java文件
使用Spring JDBC的JdbcTemplate类来操作数据库的类。
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SampleService {
@Autowired
private JdbcTemplate jdbcTemplate;
// データの一覧を返す
public List<Person> findAll() {
// 実行する SQL を組み立てて実行
String query = "SELECT * from person";
List<Person> persons = jdbcTemplate.query(query, new BeanPropertyRowMapper<>(Person.class));
return persons;
}
// データを追加する
public Person save(Person person) {
// 実行する SQL を組み立てる
SqlParameterSource param = new BeanPropertySqlParameterSource(person);
SimpleJdbcInsert insert =
new SimpleJdbcInsert(jdbcTemplate)
.withTableName("person")
.usingGeneratedKeyColumns("id");
// SQL を実行して、AUTO_INCREMENT の値を取得する
Number key = insert.executeAndReturnKey(param);
person.setId(key.longValue());
System.out.println("Add: " + person);
return person;
}
}
Person.java (文件)
表示数据库中一条记录的类。
package com.example;
public class Person {
private Long id; // AUTO_INCREMENT で ID を付与
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person(id=" + id + ", name=" + name + ")";
}
}
数据库模式.sql
一个包含启动时要执行的SQL语句的文件。
CREATE TABLE IF NOT EXISTS person (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(256) NOT NULL,
PRIMARY KEY (id)
);
数据.sql
一个文件,用于记录在启动时执行的SQL语句。
INSERT INTO person (name) VALUES('Alice');
构建和启动Spring Boot
使用mvn命令构建并生成JAR文件。
$ mvn package
使用java命令启动Spring Boot。
$ java -jar target/spring-jdbc-sample-0.0.1.jar
访问已启动的Spring Boot
可以看出数据被添加到数据库中的过程。
$ curl http://localhost:8080/add/Bob
[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
$ curl http://localhost:8080/add/Cindy
[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Cindy"}]
请确认此次操作的环境。
-
- OpenJDK 11.0.2
-
- Spring Boot 2.2.0.M5
-
- Spring JDBC 5.2.0.RC1
- H2 Database 1.4.199
资料参考
-
- Spring Boot Features – 10. Working with SQL Databases
-
- “How-to” Guides – 10. Database Initialization
-
- Spring Boot Reference Documentation – Appendices – Appendix A: Common application properties
-
- Spring Framework Documentation Version 5.2.0.RC1 – Data Access – 3. Data Access with JDBC
- spring-framework/spring-jdbc at v5.2.0.RC1 · spring-projects/spring-framework · GitHub