1. Overview
1.概述
In this quick article, we’ll focus on different kinds of Spring Data repository interfaces and their functionality. We’ll touch on:
在这篇快速文章中,我们将关注不同种类的Spring Data仓库接口及其功能。我们会涉及到
- CrudRepository
- PagingAndSortingRepository
- JpaRepository
Simply put, every repository in Spring Data extends the generic Repository interface, but beyond that, they do each have different functionality.
简单地说,Spring Data中的每个资源库都扩展了通用的Repository接口,但除此之外,它们确实各自具有不同的功能。
2. Spring Data Repositories
2.Spring数据存储库
Let’s start with the JpaRepository – which extends PagingAndSortingRepository and, in turn, the CrudRepository.
让我们从 JpaRepository开始 – 它扩展了PagingAndSortingRepository,反过来,CrudRepository。
Each of these defines its own functionality:
每一个都定义了自己的功能。
- CrudRepository provides CRUD functions
- PagingAndSortingRepository provides methods to do pagination and sort records
- JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch
And so, because of this inheritance relationship, the JpaRepository contains the full API of CrudRepository and PagingAndSortingRepository.
因此,由于这种继承关系,JpaRepository包含CrudRepository和PagingAndSortingRepository的全部API。
When we don’t need the full functionality provided by JpaRepository and PagingAndSortingRepository, we can simply use the CrudRepository.
当我们不需要JpaRepository和PagingAndSortingRepository提供的全部功能时,我们可以简单地使用CrudRepository。
Let’s now have a look at a quick example to understand these APIs better.
现在让我们看看一个快速的例子来更好地理解这些API。
We’ll start with a simple Product entity:
我们将从一个简单的产品实体开始。
@Entity
public class Product {
@Id
private long id;
private String name;
// getters and setters
}
And let’s implement a simple operation – find a Product based on its name:
让我们实现一个简单的操作–根据名字找到一个产品。
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
Product findByName(String productName);
}
That’s all. The Spring Data Repository will auto-generate the implementation based on the name we provided it.
这就是全部。Spring Data Repository将根据我们提供的名称自动生成实现。
This was a very simple example of course; you can go deeper into Spring Data JPA here.
当然,这只是一个非常简单的例子;你可以深入了解Spring Data JPA 这里。
3. CrudRepository
3.CrudRepository
Let’s now have a look at the code for the CrudRepository interface:
现在让我们来看看CrudRepository接口的代码。
public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
<S extends T> S save(S entity);
T findOne(ID primaryKey);
Iterable<T> findAll();
Long count();
void delete(T entity);
boolean exists(ID primaryKey);
}
Notice the typical CRUD functionality:
注意典型的CRUD功能。
- save(…) – save an Iterable of entities. Here, we can pass multiple objects to save them in a batch
- findOne(…) – get a single entity based on passed primary key value
- findAll() – get an Iterable of all available entities in database
- count() – return the count of total entities in a table
- delete(…) – delete an entity based on the passed object
- exists(…) – verify if an entity exists based on the passed primary key value
This interface looks quite generic and simple, but actually, it provides all basic query abstractions needed in an application.
这个接口看起来非常通用和简单,但实际上,它提供了一个应用程序所需的所有基本查询抽象。
4. PagingAndSortingRepository
4.PagingAndSortingRepository
Now, let’s have a look at another repository interface, which extends CrudRepository:
现在,让我们看看另一个存储库接口,它扩展了CrudRepository。
public interface PagingAndSortingRepository<T, ID extends Serializable>
extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
This interface provides a method findAll(Pageable pageable), which is the key to implementing Pagination.
这个接口提供了一个方法findAll(Pageable pageable),这是实现Pagination.的关键。
When using Pageable, we create a Pageable object with certain properties and we’ve to specify at least:
当使用Pageable时,我们创建一个具有某些属性的Pageable对象,我们必须至少指定。
- Page size
- Current page number
- Sorting
So, let’s assume that we want to show the first page of a result set sorted by lastName, ascending, having no more than five records each. This is how we can achieve this using a PageRequest and a Sort definition:
因此,让我们假设我们想显示按lastName,升序排序的结果集的第一页,每条记录不超过5条。这就是我们如何使用PageRequest和Sort定义来实现的。
Sort sort = new Sort(new Sort.Order(Direction.ASC, "lastName"));
Pageable pageable = new PageRequest(0, 5, sort);
Passing the pageable object to the Spring data query will return the results in question (the first parameter of PageRequest is zero-based).
将pageable对象传递给Spring数据查询将返回相关的结果(PageRequest的第一个参数为零)。
5. JpaRepository
5.JpaRepository
Finally, we’ll have a look at the JpaRepository interface:
最后,我们来看看JpaRepository接口。
public interface JpaRepository<T, ID extends Serializable> extends
PagingAndSortingRepository<T, ID> {
List<T> findAll();
List<T> findAll(Sort sort);
List<T> save(Iterable<? extends T> entities);
void flush();
T saveAndFlush(T entity);
void deleteInBatch(Iterable<T> entities);
}
Again, let’s look at each of these methods in brief:
再一次,让我们简单地看看这些方法中的每一个。
- findAll() – get a List of all available entities in database
- findAll(…) – get a List of all available entities and sort them using the provided condition
- save(…) – save an Iterable of entities. Here, we can pass multiple objects to save them in a batch
- flush() – flush all pending task to the database
- saveAndFlush(…) – save the entity and flush changes immediately
- deleteInBatch(…) – delete an Iterable of entities. Here, we can pass multiple objects to delete them in a batch
Clearly, above interface extends PagingAndSortingRepository which means it has all methods present in the CrudRepository as well.
显然,上述接口扩展了PagingAndSortingRepository,这意味着它也拥有CrudRepository中的所有方法。
6. Downsides of Spring Data Repositories
6.Spring Data Repositories的缺点
Beyond all the very useful advantages of these repositories, there are some basic downsides of directly depending on these as well:
除了这些存储库的所有非常有用的优点之外,直接依赖这些存储库也有一些基本的缺点。
- we couple our code to the library and to its specific abstractions, such as `Page` or `Pageable`; that’s of course not unique to this library – but we do have to be careful not to expose these internal implementation details
- by extending e.g. CrudRepository, we expose a complete set of persistence method at once. This is probably fine in most circumstances as well but we might run into situations where we’d like to gain more fine-grained control over the methods exposed, e.g. to create a ReadOnlyRepository that doesn’t include the save(…) and delete(…) methods of CrudRepository
7. Conclusion
7.结论
This article covered some brief but important differences and features of Spring Data JPA repository interfaces.
这篇文章涵盖了Spring Data JPA存储库接口的一些简单但重要的区别和特点。
For more information, have a look at the series on Spring Persistence.
欲了解更多信息,请看Spring Persistence系列。