本指南将引导您构建一个使用SpringDataJPA在关系数据库中存储和检索数据的应用程序。
你将要建什么
您将在基于内存的数据库中构建一个存储Customer的
POJO(Plain Ordinary Java Object,简单的Java对象,实际就是普通JavaBeans)。
你需要什么
-
大约15分钟
-
最喜欢的文本编辑器或IDE
-
JDK 1.8或以后
-
您还可以直接将代码导入IDE中:
如何完成本指南
像大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,你最终都会得到工作代码。
从头开始,用Gradle建造.
跳过基础,做以下工作:
-
下载并解压缩本指南的源存储库,或使用Git:
git clone https://github.com/spring-guides/gs-accessing-data-jpa.git
-
cd进入
gs-accessing-data-jpa/initial
-
跳到定义一个简单的实体.
当你完成以后,你可以在gs-accessing-data-jpa/complete
中的代码中检查结果.
用Gradle建造
首先,您需要设置一个基本的构建脚本。在使用Spring构建应用程序时,您可以使用任何您喜欢的构建系统,但是您需要使用的代码 Gradle和 Maven。如果你对两者都不熟悉,请参考用Gradle构建Java项目或使用Maven构建Java项目.
创建目录结构
在您选择的项目目录中,创建以下子目录结构;例如,使用mkdir -p src/main/java/hello
关于*nix系统:
└── src └── main └── java └── hello
创建一个Gradle构建文件
下面是初始的Gradle构建文件.
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'gs-accessing-data-jpa'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")
testCompile("junit:junit")
}
SpringBoot的gradle插件提供了许多方便的功能:
-
它收集类路径上的所有JAR,并构建一个可运行的“über-jar”,这使得执行和传输服务更加方便。
-
它搜索
public static void main()
方法标记为可运行的类。 -
它提供了一个内置的依赖项解析器,它将版本号设置为匹配SpringBoot依赖关系。您可以覆盖任何版本,但它将默认为Boot所选的一组版本。
用Maven构建
首先,您需要设置一个基本的构建脚本。在使用Spring构建应用程序时,您可以使用任何您喜欢的工具构建系统,但是这里您需要使用Maven。如果您不熟悉Maven,请参阅使用Maven构建Java项目.
创建目录结构
在您选择的项目目录中,创建以下子目录结构;例如,使用mkdir -p src/main/java/hello
关于*nix系统:
└── src └── main └── java └── hello
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-accessing-data-jpa</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</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>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Spring Boot Maven插件提供了许多方便的功能:
-
它收集类路径上的所有JAR,并构建一个可运行的“über-jar”,这使得执行和传输服务更加方便。
-
它搜索
public static void main()
方法标记为可运行的类。 -
它提供了一个内置的依赖项解析器,它将版本号设置为匹配SpringBoot依赖关系。您可以覆盖任何版本,但它将默认为Boot所选的一组版本。
用IDE构建
-
阅读如何将本指南直接导入 Spring Tool Suite.
-
阅读如何使用本指南 IntelliJ IDEA.
定义一个简单的实体
在本例中,存储Customer对象,并将其注释为JPA实体。
src/main/java/hello/Customer.java
package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
protected Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
这里你有一个Customer
类具有三个属性,id
,firstName
,以及lastName
。还有两个构造函数。默认构造函数的存在只是为了JPA。您不会直接使用它,因此它被指定为protected
。另一个构造函数将用于创建Customer
保存到数据库中。
在本指南中,为了简洁起见,忽略了典型的getter和setter。 |
Customer
类被注释为@Entity
表示它是一个JPA实体。因为缺乏@Table
注释,该实体将被映射到一个名为Customer的table
.
Customer的
id
属性注释为@Id
以便JPA将其识别为对象的ID。id
属性也用@GeneratedValue
指示应该自动生成ID。
另外两个属性,firstName
和lastName
都没有注释。它们将映射到与属性本身同名的列。
toString()
方法将打印出Customer的属性。
创建简单查询
SpringDataJPA侧重于使用JPA将数据存储在关系数据库中。它最引人注目的特性是能够在运行时从存储库(repository)接口自动创建存储库的实现(imlpementions)。
要了解它是如何工作的,请创建一个与Customer
实体:
src/main/java/hello/CustomerRepository.java
package hello;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
CustomerRepository继承
CrudRepository
接口。它使用的实体和ID的类型Customer
和Long,
在CrudRepository
的泛型参数中指定。通过继承CrudRepository
, CustomerRepository
几种方法,包括保存、删除和查找的方法。用于操作Customer
实体。
SpringDataJPA还允许您通过简单地声明方法签名来定义其他查询方法。如例子中CustomerRepository的
findByLastName()
方法。
在典型的Java应用程序中,您希望编写一个实现CustomerRepository
。但这正是SpringDataJPA如此强大的原因:您不必编写存储库接口的实现。SpringDataJPA在运行应用程序时动态创建一个实现。
让我们把它连接起来,看看它是什么样子!
创建应用程序类
在这里,您将创建一个包含所有组件的应用程序类。
src/main/java/hello/Application.java
package hello;
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.context.annotation.Bean;
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner demo(CustomerRepository repository) {
return (args) -> {
// save a couple of customers
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brian"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));
// fetch all customers
log.info("Customers found with findAll():");
log.info("-------------------------------");
for (Customer customer : repository.findAll()) {
log.info(customer.toString());
}
log.info("");
// fetch an individual customer by ID
repository.findById(1L)
.ifPresent(customer -> {
log.info("Customer found with findById(1L):");
log.info("--------------------------------");
log.info(customer.toString());
log.info("");
});
// fetch customers by last name
log.info("Customer found with findByLastName('Bauer'):");
log.info("--------------------------------------------");
repository.findByLastName("Bauer").forEach(bauer -> {
log.info(bauer.toString());
});
// for (Customer bauer : repository.findByLastName("Bauer")) {
// log.info(bauer.toString());
// }
log.info("");
};
}
}
@SpringBootApplication
是一个方便的注释,它添加了以下所有内容:
-
@Configuration
tags the class as a source of bean definitions for the application context. -
@EnableAutoConfiguration
tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. -
Normally you would add
@EnableWebMvc
for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up aDispatcherServlet
. -
@ComponentScan
tells Spring to look for other components, configurations, and services in thehello
package, allowing it to find the controllers.
main()
方法使用SpringBoot的SpringApplication.run()
方法来启动应用程序。您注意到没有一行XML吗?也没有web.xml。这个Web应用程序是100%纯Java的,您不必处理任何配置问题。
Application
包括main()
方法,该方法将CustomerRepository
通过几个测试。首先,它获取CustomerRepository
来自Spring应用程序上下文。那就省下了一小撮Customer
对象,演示save()
方法并设置要处理的一些数据。接下来,它调用findAll()
把所有Customer
对象。然后它让findOne()
根据它的ID去取一个Customer
。最后,它调用findByLastName()
找到所有姓“Bauer”的顾客。
默认情况下,SpringBoot将启用JPA存储库支持,并查看包(及其子包)@SpringBootApplication 找到了。如果配置中的JPA存储库接口定义位于不可见的包中,则可以使用@EnableJpaRepositories 以及它的类型安全basePackageClasses=MyRepository.class 参数。 |
构建一个可执行的JAR
您可以使用Gradle或Maven从命令行运行应用程序。或者,您可以构建一个包含所有必需的依赖项、类和资源的单个可执行JAR文件,并运行该文件。这使得在整个开发生命周期、跨不同环境等将服务作为应用程序进行发布、版本和部署变得非常容易。
如果使用Gradle,则可以使用./gradlew bootRun
。或者您可以使用./gradlew build
。然后可以运行JAR文件:
java -jar build/libs/gs-accessing-data-jpa-0.1.0.jar
如果使用的是Maven,则可以使用./mvnw spring-boot:run
。或者您可以用./mvnw clean package
。然后可以运行JAR文件:
java -jar target/gs-accessing-data-jpa-0.1.0.jar
上面的过程将创建一个可运行的JAR。相反你也可以选择构建一个经典的WAR文件。 |
你应该看到这样的东西:
== Customers found with findAll(): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=2, firstName='Chloe', lastName='O'Brian'] Customer[id=3, firstName='Kim', lastName='Bauer'] Customer[id=4, firstName='David', lastName='Palmer'] Customer[id=5, firstName='Michelle', lastName='Dessler'] == Customer found with findOne(1L): Customer[id=1, firstName='Jack', lastName='Bauer'] == Customer found with findByLastName('Bauer'): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=3, firstName='Kim', lastName='Bauer']
摘要
祝贺你!您已经编写了一个简单的应用程序,它使用SpringDataJPA将对象保存到数据库中并获取它们-所有这些都没有编写具体的存储库实现。
如果您对使用基于超媒体的RESTful前端公开JPA存储库感兴趣,那么您可能需要阅读使用REST访问JPA数据. |
另见
下列指南也可能有帮助: