Introduction to Spring Data JPA – Spring Data JPA简介

最后修改: 2014年 5月 24日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial will focus on introducing Spring Data JPA into a Spring project, and fully configuring the persistence layer. For a step-by-step introduction to setting up the Spring context using Java-based configuration and the basic Maven pom for the project, see this article.

本教程将重点介绍将Spring Data JPA引入Spring项目,并全面配置持久层。有关使用基于 Java 的配置和项目的基本 Maven pom 来设置 Spring 上下文的逐步介绍,请参阅 本文

2. The Spring Data Generated DAO – No More DAO Implementations

2.Spring Data生成的DAO–不再有DAO实现

As we discussed in an earlier article, the DAO layer usually consists of a lot of boilerplate code that can and should be simplified. The advantages of such a simplification are many: a decrease in the number of artifacts that we need to define and maintain, consistency of data access patterns, and consistency of configuration.

正如我们在之前的文章中所讨论的,DAO层通常由大量的模板代码组成,可以而且应该加以简化。这种简化的好处很多:减少我们需要定义和维护的工件的数量、数据访问模式的一致性以及配置的一致性。

Spring Data takes this simplification one step further and makes it possible to remove the DAO implementations entirely. The interface of the DAO is now the only artifact that we need to explicitly define.

Spring Data将这一简化又向前推进了一步,使得完全删除DAO的实现成为可能。现在,DAO的接口是我们唯一需要明确定义的工件。

In order to start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specific Repository interface, JpaRepository. This will enable Spring Data to find this interface and automatically create an implementation for it.

为了开始利用JPA的Spring Data编程模型,DAO接口需要扩展JPA特定的Repository接口,JpaRepository。这将使Spring Data能够找到这个接口并自动为其创建一个实现。

By extending the interface, we get the most relevant CRUD methods for standard data access available in a standard DAO.

通过扩展接口,我们得到了标准DAO中可用的标准数据访问的最相关CRUD方法。

3. Custom Access Method and Queries

3.自定义访问方法和查询

As discussed, by implementing one of the Repository interfaces, the DAO will already have some basic CRUD methods (and queries) defined and implemented.

正如所讨论的,通过实现Repository接口之一,DAO已经有一些基本的CRUD方法(和查询)被定义和实现

To define more specific access methods, Spring JPA supports quite a few options:

为了定义更具体的访问方法,Spring JPA支持相当多的选项。

  • simply define a new method in the interface
  • provide the actual JPQL query by using the @Query annotation
  • use the more advanced Specification and Querydsl support in Spring Data
  • define custom queries via JPA Named Queries

The third option, Specifications and Querydsl support, is similar to JPA Criteria, but uses a more flexible and convenient API. This makes the whole operation much more readable and reusable. The advantages of this API will become more pronounced when dealing with a large number of fixed queries, as we could potentially express these more concisely through a smaller number of reusable blocks.

第三个选项,规格和Querydsl支持,类似于JPA标准,但使用更灵活和方便的API。这使得整个操作的可读性和可重用性大大增强。在处理大量的固定查询时,这种API的优势将变得更加明显,因为我们有可能通过数量较少的可重用块来更简洁地表达这些查询。

The last option has the disadvantage that it either involves XML or burdening the domain class with the queries.

最后一种方案的缺点是,它要么涉及到XML,要么让领域类承担查询的负担。

3.1. Automatic Custom Queries

3.1.自动自定义查询

When Spring Data creates a new Repository implementation, it analyses all the methods defined by the interfaces and tries to automatically generate queries from the method names. While this has some limitations, it’s a very powerful and elegant way of defining new custom access methods with very little effort.

当Spring Data创建一个新的Repository实现时,它分析了所有由接口定义的方法,并试图从方法名称中自动生成查询。虽然这有一些局限性,但这是一种非常强大和优雅的方式,只需很少的努力就能定义新的自定义访问方法。

Let’s look at an example. If the entity has a name field (and the Java Bean standard getName and setName methods), we’ll define the findByName method in the DAO interface. This will automatically generate the correct query:

让我们看一个例子。如果实体有一个name字段(以及Java Bean标准的getNamesetName方法),我们将在DAO接口中定义findByName方法。这将自动生成正确的查询。

public interface IFooDAO extends JpaRepository<Foo, Long> {

    Foo findByName(String name);

}

This is a relatively simple example. The query creation mechanism supports a much larger set of keywords.

这是一个相对简单的例子。查询创建机制支持更大的关键字集

In case the parser can’t match the property with the domain object field, we’ll see the following exception:

如果解析器不能将该属性与域对象字段相匹配,我们会看到以下异常。

java.lang.IllegalArgumentException: No property nam found for type class com.baeldung.spring.data.persistence.model.Foo

3.2. Manual Custom Queries

3.2.手动自定义查询

Now let’s look at a custom query that we’ll define via the @Query annotation:

现在让我们看一下我们将通过@Query注解定义的自定义查询。

@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);

For even more fine-grained control over the creation of queries, such as using named parameters or modifying existing queries, the reference is a good place to start.

对于创建查询的更精细的控制,例如使用命名参数或修改现有的查询,参考文献是一个很好的开始。

4. Transaction Configuration

4.事务配置

The actual implementation of the Spring-managed DAO is indeed hidden since we don’t work with it directly. However, it’s a simple enough implementation, the SimpleJpaRepository, which defines transaction semantics using annotations.

Spring管理的DAO的实际实现的确是隐藏的,因为我们并不直接使用它。然而,这是一个足够简单的实现,SimpleJpaRepository,它使用注解定义了事务语义。

More explicitly, this uses a read-only @Transactional annotation at the class level, which is then overridden for the non-read-only methods. The rest of the transaction semantics are default, but these can be easily overridden manually per method.

更明确地说,这在类的层面上使用了一个只读的@Transactional注解,然后为非只读的方法重写该注解。其余的事务语义是默认的,但这些可以很容易地被每个方法手动重写。

4.1. Exception Translation Is Alive and Well

4.1.例外情况下的翻译是活生生的

The question now becomes: since Spring Data JPA doesn’t depend on the old ORM templates (JpaTemplate, HibernateTemplate), and they have been removed since Spring 5, are we still going to get our JPA exceptions translated to Spring’s DataAccessException hierarchy?

现在的问题是:由于Spring Data JPA不依赖于旧的ORM模板(JpaTemplate, HibernateTemplate),而且它们从Spring 5开始被移除,我们是否还能让我们的JPA异常翻译成Spring的DataAccessException层次结构?

The answer is, of course, we are. Exception translation is still enabled by the use of the @Repository annotation on the DAO. This annotation enables a Spring bean postprocessor to advise all @Repository beans with all the PersistenceExceptionTranslator instances found in the container, and provide exception translation just as before.

答案是,当然,我们是。通过使用DAO上的@Repository注解,仍然可以实现异常转换。这个注解使Spring Bean后处理器能够将所有@Repository Bean与容器中发现的所有PersistenceExceptionTranslator实例告知,并像以前一样提供异常翻译。

Let’s verify exception translation with an integration test:

让我们用一个集成测试来验证异常翻译。

@Test(expected = DataIntegrityViolationException.class)
public void whenInvalidEntityIsCreated_thenDataException() {
    service.create(new Foo());
}

Keep in mind that exception translation is done through proxies. In order for Spring to be able to create proxies around the DAO classes, these must not be declared final.

请记住,异常转换是通过代理完成的。为了让Spring能够围绕DAO类创建代理,这些代理必须不被声明为final

5. Spring Data JPA Repository Configuration

5.Spring Data JPA Repository配置

To activate the Spring JPA repository support, we can use the @EnableJpaRepositories annotation and specify the package that contains the DAO interfaces:

为了激活Spring JPA仓库支持,我们可以使用@EnableJpaRepositories注解并指定包含DAO接口的包。

@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository") 
public class PersistenceConfig { 
    ...
}

We can do the same with an XML configuration:

我们可以用XML配置做同样的事情。

<jpa:repositories base-package="com.baeldung.spring.data.persistence.repository" />

6. Java or XML Configuration

6.Java或XML配置

We already discussed in great detail how to configure JPA in Spring in a previous article. Spring Data also takes advantage of Spring’s support for the JPA @PersistenceContext annotation. It uses this to wire the EntityManager into the Spring factory bean responsible for creating the actual DAO implementations, JpaRepositoryFactoryBean.

我们已经在之前的文章中详细讨论了如何在Spring中配置JPA。Spring Data 还利用了 Spring 对 JPA @PersistenceContext 注解的支持。它利用这一点将EntityManager连接到负责创建实际DAO实现的Spring工厂beanJpaRepositoryFactoryBean

In addition to the already discussed configuration, we also need to include the Spring Data XML Config if we are using XML:

除了已经讨论过的配置外,如果我们使用XML,我们还需要包括Spring Data XML配置。

@Configuration
@EnableTransactionManagement
@ImportResource("classpath*:*springDataConfig.xml")
public class PersistenceJPAConfig {
    ...
}

7. Maven Dependency

7.Maven的依赖性

In addition to the Maven configuration for JPA, like in a previous article, we’ll add the spring-data-jpa dependency:

除了像前一篇文章中那样为JPA进行Maven配置外,我们还要添加spring-data-jpa依赖性

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>2.4.0</version>
</dependency>

8. Using Spring Boot

8.使用Spring Boot

We can also use the Spring Boot Starter Data JPA dependency that will automatically configure the DataSource for us.

我们还可以使用Spring Boot Starter Data JPA依赖项,它将自动为我们配置DataSource

We need to make sure that the database we want to use is present in the classpath. In our example, we’ve added the H2 in-memory database:

我们需要确保我们要使用的数据库存在于classpath中。在我们的例子中,我们已经添加了H2内存数据库。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
   <version>2.7.2</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>

As a result, just by doing these dependencies, our application is up and running and we can use it for other database operations.

结果,仅仅通过做这些依赖,我们的应用程序就开始运行了,我们可以用它来进行其他的数据库操作。

The explicit configuration for a standard Spring application is now included as part of Spring Boot auto-configuration.

标准Spring应用程序的明确配置现在包括在Spring Boot自动配置的一部分。

We can, of course, modify the auto-configuration by adding our customized explicit configuration.

当然,我们可以通过添加我们自定义的显式配置来修改自动配置。

Spring Boot provides an easy way to do this using properties in the application.properties file. Let’s see an example of changing the connection URL and credentials:

Spring Boot提供了一个简单的方法,使用application.properties文件中的属性来做到这一点。让我们看一个改变连接URL和证书的例子。

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

9. Useful Tools for Spring Data JPA

9.Spring Data JPA的有用工具

Spring Data JPA is supported in all major Java IDEs. Let’s see what useful tools are available for Eclipse and IntelliJ IDEA.

所有主要的Java IDE都支持Spring Data JPA。让我们看看Eclipse和IntelliJ IDEA都有哪些有用的工具。

If you use Eclipse as your IDE, you can install the Dali Java Persistence Tools plugin. This provides ER diagrams for JPA entities, DDL generation to initialize schema, and basic reverse engineering capabilities. Also, you can use Eclipse Spring Tool Suite (STS). It will help to validate query method names in Spring Data JPA repositories.

如果您使用 Eclipse 作为您的 IDE,您可以安装 Dali Java Persistence Tools 插件。这可以为 JPA 实体提供 ER 图,生成 DDL 以初始化模式,以及基本的逆向工程功能。此外,您还可以使用Eclipse Spring工具套件(STS)。它将有助于验证Spring Data JPA存储库中的查询方法名称。

In case you use IntelliJ IDEA, there are two options.

如果你使用IntelliJ IDEA,有两个选项。

IntelliJ IDEA Ultimate enables ER diagrams, a JPA console for testing JPQL statements, and valuable inspections. However, these features are not available in the Community Edition.

IntelliJ IDEA Ultimate支持ER图、用于测试JPQL语句的JPA控制台,以及有价值的检查。然而,这些功能在社区版中是没有的。

To boost productivity in IntelliJ, you can install the JPA Buddy plugin, which provides many features, including generation of JPA entities, Spring Data JPA repositories, DTOs, initialization DDL scripts, Flyway versioned migrations, Liquibase changelogs, etc. Also, JPA Buddy provides an advanced tool for reverse engineering.

为了提高IntelliJ的工作效率,您可以安装JPA Buddy插件,它提供了许多功能,包括生成JPA实体、Spring Data JPA库、DTO、初始化DDL脚本、Flyway版本化迁移、Liquibase变更日志等。此外,JPA Buddy还提供了一个先进的逆向工程工具。

Finally, the JPA Buddy plugin works with both Community and Ultimate editions.

最后,JPA Buddy插件在社区版和终极版中都可以使用。

10. Conclusion

10.结论

In this article, we covered the configuration and implementation of the persistence layer with Spring 5, JPA 2, and Spring Data JPA (part of the Spring Data umbrella project) using both XML and Java-based configuration.

在这篇文章中,我们使用XML和基于Java的配置,介绍了Spring 5、JPA 2和Spring Data JPA(Spring Data总项目的一部分)的持久层的配置和实现。

We discussed ways to define more advanced custom queries, as well as transactional semantics, and a configuration with the new jpa namespace. The final result is a new and elegant take on data access with Spring, with almost no actual implementation work.

我们讨论了如何定义更多的高级自定义查询,以及交易语义jpa命名空间的配置。最后的结果是用Spring进行数据访问的一种新的、优雅的方式,几乎没有实际的实施工作。

The implementation of this Spring Data JPA tutorial can be found in the GitHub project.

这个Spring Data JPA教程的实现可以在GitHub项目中找到。