A Guide to Spring Data Key Value – Spring数据键值指南

最后修改: 2018年 6月 2日

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

1. Introduction

1.绪论

The Spring Data Key Value framework makes it easy to write Spring applications that use key-value stores.

Spring Data键值框架使得编写使用键值存储的Spring应用程序变得容易。

It minimizes redundant tasks and boilerplate code required for interacting with the store. The framework works well for key-value stores like Redis and Riak.

它最大限度地减少了多余的任务和与存储互动所需的模板代码。该框架对Redis和Riak等键值存储有很好的效果。

In this tutorial, we’ll cover how we can use Spring Data Key Value with the default java.util.Map based implementation.

在本教程中,我们将介绍如何使用Spring Data Key Value与基于默认的java.util.Map实现。

2. Requirements

2.要求

The Spring Data Key Value 1.x binaries require JDK level 6.0 or above, and Spring Framework 3.0.x or above.

Spring Data Key Value 1.x二进制文件需要JDK 6.0级或以上,以及Spring Framework 3.0.x或以上。

3. Maven Dependency

3.Maven的依赖性

To work with Spring Data Key Value, we need to add the following dependency:

为了与Spring Data Key Value一起工作,我们需要添加以下依赖关系。

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-keyvalue</artifactId>
    <version>2.0.6.RELEASE</version>
</dependency>

The latest version can be found here.

最新版本可以在这里找到。

4. Creating an Entity

4.创建一个实体

Let’s create an Employee entity:

让我们创建一个Employee实体。

@KeySpace("employees")
public class Employee {

    @Id
    private Integer id;

    private String name;

    private String department;

    private String salary;

    // constructors/ standard getters and setters

}

Keyspaces define in which part of the data structure the entity should be kept. This concept is very similar to collections in MongoDB and Elasticsearch, cores in Solr and tables in JPA.

关键空间定义了实体应该保存在数据结构的哪个部分。这个概念与MongoDB和Elasticsearch中的集合、Solr中的核心以及JPA中的表非常相似。

By default, the keyspace of an entity is extracted from its type.

默认情况下,实体的键空间是从其类型中提取的。

5. Repository

5.存储库

Similar to other Spring Data frameworks, we will need to activate Spring Data repositories using the @EnableMapRepositories annotation.

与其他Spring Data框架类似,我们将需要使用@EnableMapRepositories注解来激活Spring Data存储库。

By default, the repositories will use the ConcurrentHashMap-based implementation:

默认情况下,存储库将使用基于ConcurrentHashMap-的实现。

@SpringBootApplication
@EnableMapRepositories
public class SpringDataKeyValueApplication {
}

It’s possible to change the default ConcurrentHashMap implementation and use some other java.util.Map implementations:

可以改变默认的ConcurrentHashMap实现,使用一些其他的java.util.Map实现:

@EnableMapRepositories(mapType = WeakHashMap.class)

Creating repositories with Spring Data Key Value works the same way as with other Spring Data frameworks:

用Spring Data Key Value创建存储库的方式与其他Spring Data框架的方式相同。

@Repository
public interface EmployeeRepository
  extends CrudRepository<Employee, Integer> {
}

For learning more about Spring Data repositories we can have a look at this article.

要了解有关Spring Data存储库的更多信息,我们可以看一下这篇文章

6. Using the Repository

6.使用存储库

By extending CrudRepository in EmployeeRepository, we get a complete set of persistence methods that perform CRUD functionality.

通过在EmployeeRepository中扩展CrudRepository,我们得到一套完整的持久化方法,执行CRUD功能。

Now, we’ll see how we can use some of the available persistence methods.

现在,我们将看到我们如何使用一些可用的持久化方法。

6.1. Saving an Object

6.1.保存一个对象

Let’s save a new Employee object to the data store using the repository:

让我们使用存储库保存一个新的Employee对象到数据存储。

Employee employee = new Employee(1, "Mike", "IT", "5000");
employeeRepository.save(employee);

6.2. Retrieving an Existing Object

6.2.检索一个现有的对象

We can verify the correct save of the employee in the previous section by fetching the employee:

我们可以通过获取雇员来验证上一节中雇员的正确保存。

Optional<Employee> savedEmployee = employeeRepository.findById(1);

6.3. Updating an Existing Object

6.3.更新一个现有的对象

CrudRepository doesn’t provide a dedicated method for updating an object.

CrudRepository没有提供专门的方法来更新一个对象。

Instead, we can use the save() method:

相反,我们可以使用save()方法。

employee.setName("Jack");
employeeRepository.save(employee);

6.4. Deleting an Existing Object

6.4.删除一个现有的对象

We can delete the inserted object using the repository:

我们可以使用存储库删除插入的对象。

employeeRepository.deleteById(1);

6.5. Fetch All Objects

6.5.取出所有对象

We can fetch all the saved objects:

我们可以取回所有保存的对象。

Iterable<Employee> employees = employeeRepository.findAll();

7. KeyValueTemplate

7.KeyValueTemplate

Another way of performing operations on the data structure is by using KeyValueTemplate.

对数据结构进行操作的另一种方式是通过使用KeyValueTemplate

In very basic terms, the KeyValueTemplate uses a MapAdapter wrapping a java.util.Map implementation to perform queries and sorting:

在非常基本的条件下,KeyValueTemplate使用MapAdapter包装java.util.Map实现来进行查询和排序。

@Bean
public KeyValueOperations keyValueTemplate() {
    return new KeyValueTemplate(keyValueAdapter());
}

@Bean
public KeyValueAdapter keyValueAdapter() {
    return new MapKeyValueAdapter(WeakHashMap.class);
}

Note that in case we have used @EnableMapRepositories, we don’t need to specify a KeyValueTemplate. It will be created by the framework itself.

注意,如果我们使用了@EnableMapRepositories,我们不需要指定一个KeyValueTemplate。

8. Using KeyValueTemplate

8.使用KeyValueTemplate

Using KeyValueTemplate, we can perform the same operations as we did with the repository.

使用KeyValueTemplate,我们可以执行与我们对资源库所做的相同操作。

8.1. Saving an Object

8.1.保存一个对象

Let’s see how to save a new Employee object to the data store using a template:

让我们看看如何使用模板将一个新的Employee对象保存到数据存储。

Employee employee = new Employee(1, "Mile", "IT", "5000");
keyValueTemplate.insert(employee);

8.2. Retrieving an Existing Object

8.2.检索一个现有的对象

We can verify the insertion of the object by fetching it from the structure using template:

我们可以通过使用模板从结构中获取对象来验证其插入情况。

Optional<Employee> savedEmployee = keyValueTemplate
  .findById(id, Employee.class);

8.3. Updating an Existing Object

8.3.更新一个现有的对象

Unlike CrudRepository, the template provides a dedicated method to update an object:

CrudRepository不同,模板提供了一个专门的方法来更新一个对象。

employee.setName("Jacek");
keyValueTemplate.update(employee);

8.4. Deleting an Existing Object

8.4.删除一个现有的对象

We can delete an object with a template:

我们可以用一个模板删除一个对象。

keyValueTemplate.delete(id, Employee.class);

8.5. Fetch All Objects

8.5.取出所有对象

We can fetch all the saved objects using a template:

我们可以使用一个模板来获取所有保存的对象。

Iterable<Employee> employees = keyValueTemplate
  .findAll(Employee.class);

8.6. Sorting the Objects

8.6.对对象进行排序

In addition to the basic functionality, the template also supports KeyValueQuery for writing custom queries.

除了基本功能外,该模板还支持KeyValueQuery,用于编写自定义查询。

For example, we can use a query to get a sorted list of Employees based on their salary:

例如,我们可以使用一个查询来获得一个基于工资的雇员排序的列表。

KeyValueQuery<Employee> query = new KeyValueQuery<Employee>();
query.setSort(new Sort(Sort.Direction.DESC, "salary"));
Iterable<Employee> employees 
  = keyValueTemplate.find(query, Employee.class);

9. Conclusion

9.结语

This article showcased how we can use Spring Data KeyValue framework with the default Map implementation using Repository or KeyValueTemplate.

这篇文章展示了我们如何使用Spring Data KeyValue框架与使用RepositoryKeyValueTemplate的默认Map实现。

There are more Spring Data Frameworks like Spring Data Redis which are written on top of Spring Data Key Value. Refer to this article for an introduction to Spring Data Redis.

还有更多的Spring Data框架,如Spring Data Redis,它是写在Spring Data Key Value之上的。请参考这篇文章,了解Spring Data Redis的介绍。

And, as always, all code samples shown here are available over on GitHub.

而且,像往常一样,这里显示的所有代码样本都可以在GitHub上找到