Spring Data with ArangoDB – 与ArangoDB的Spring数据

最后修改: 2021年 8月 16日

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

1. Introduction

1.绪论

In this tutorial, we’ll learn how to work with the Spring Data module and ArangoDB database. ArangoDB is a free and open-source multi-model database system. It supports key-value, document, and graph data models with one database core and a unified query language: AQL (ArangoDB Query Language).

在本教程中,我们将学习如何使用Spring Data模块和ArangoDB数据库。ArangoDB是一个免费和开源的多模型数据库系统。它通过一个数据库核心和一个统一的查询语言支持键值、文档和图形数据模型。AQL(ArangoDB查询语言)。

We’ll cover the required configuration, basic CRUD operations, custom queries, and entities relations.

我们将涵盖必要的配置、基本的CRUD操作、自定义查询和实体关系。

2. ArangoDB Setup

2.ArangoDB设置

To install ArangoDB, we’ll first need to download the package from the Download page of the official ArangoDB website.

要安装ArangoDB,我们首先需要从ArangoDB官方网站的下载页面下载该软件包。

For the purpose of this tutorial, we will go with installing the community edition of ArangoDB. Detailed installation steps can be found here.

在本教程中,我们将使用ArangoDB的社区版进行安装。详细的安装步骤可以在这里找到。

The default installation contains a database called _system and a root user which has access to all databases.

默认安装包含一个名为_system的数据库和一个root用户,该用户可以访问所有数据库。

Depending upon the package, the installer will either ask for a root password during the installation process or will set a random password.

根据不同的软件包,安装程序将在安装过程中要求提供根密码,或者设置一个随机密码。

With the default configuration, we’ll see the ArangoDB server running on 8529 port.

在默认配置下,我们会看到ArangoDB服务器运行在8529端口。

Once the setup is done, we can interact with the server using the Web Interface accessible on http://localhost:8529. We will use this host and port for Spring Data configuration later in the tutorial.

一旦设置完成,我们就可以使用http://localhost:8529上的Web界面与服务器进行交互。我们将在后面的教程中使用这个主机和端口来配置Spring Data。

We can also alternatively use arangosh, a synchronous shell for interaction with the server.

我们也可以选择使用arangosh,一个用于与服务器交互的同步shell。

Let’s start with launching arangosh to create a new database called baeldung-database and a user baeldung with access to this newly created database.

让我们从启动arangosh开始,创建一个名为baeldung-database的新数据库和一个可以访问这个新创建数据库的用户baeldung

arangosh> db._createDatabase("baeldung-database", {}, [{ username: "baeldung", passwd: "password", active: true}]);

3. Dependencies

3.依赖性

To use Spring Data with ArangoDB in our application, we’ll need the following dependency:

要在我们的应用程序中使用带有 ArangoDB 的 Spring Data,我们将需要以下依赖关系

<dependency>
    <groupId>com.arangodb</groupId>
    <artifactId>arangodb-spring-data</artifactId>
    <version>3.5.0</version>
</dependency>

4. Configuration

4.配置

Before we start working with the data, we need to set up a connection to ArangoDB. We should do it by creating a configuration class that implements the ArangoConfiguration interface:

在我们开始处理数据之前,我们需要设置一个与ArangoDB的连接。我们应该通过创建一个实现ArangoConfiguration接口的配置类来实现。

@Configuration
public class ArangoDbConfiguration implements ArangoConfiguration {}

Inside we’ll need to implement two methods. The first one should create ArangoDB.Builder object that will generate an interface to our database:

在里面我们需要实现两个方法。第一个方法应该创建ArangoDB.Builder对象,该对象将生成我们数据库的接口。

@Override
public ArangoDB.Builder arango() {
    return new ArangoDB.Builder()
      .host("127.0.0.1", 8529)
      .user("baeldung").password("password"); }

There are four required parameters to create a connection: host, port, username, and password.

创建一个连接需要四个参数:主机、端口、用户名和密码。

Alternatively, we can skip setting these parameters in the configuration class:

另外,我们可以跳过在配置类中设置这些参数。

@Override
public ArangoDB.Builder arango() {
    return new ArangoDB.Builder();
}

As we can store them in arango.properties resource file:

因为我们可以在arango.properties资源文件中存储它们。

arangodb.host=127.0.0.1
arangodb.port=8529
arangodb.user=baeldung
arangodb.password=password

It’s a default location for Arango to look for. It can be overwritten by passing an InputStream to a custom properties file:

这是Arango要寻找的一个默认位置。它可以通过传递一个InputStream到一个自定义属性文件来覆盖。

InputStream in = MyClass.class.getResourceAsStream("my.properties");
ArangoDB.Builder arango = new ArangoDB.Builder()
  .loadProperties(in);

The second method we have to implement is simply providing a database name that we need in our application:

我们要实现的第二个方法是简单地提供一个我们在应用中需要的数据库名称。

@Override
public String database() {
    return "baeldung-database";
}

Additionally, the configuration class needs the @EnableArangoRepositories annotation that tells Spring Data where to look for ArangoDB repositories:

另外,配置类需要@EnableArangoRepositories注解,告诉Spring Data去哪里寻找ArangoDB存储库:

@EnableArangoRepositories(basePackages = {"com.baeldung"})

5. Data Model

5.数据模型

As a next step, we’ll create a data model. For this piece, we’ll use an article representation with a name, author, and publishDate fields:

作为下一步,我们将创建一个数据模型。对于这一块,我们将使用一个带有nameauthorpublishDate字段的文章表示。

@Document("articles")
public class Article {

    @Id
    private String id;

    @ArangoId
    private String arangoId;

    private String name;
    private String author;
    private ZonedDateTime publishDate;

    // constructors
}

The ArangoDB entity must have the @Document annotation that takes the collection name as an argument. By default, it’s a decapitalize class name.

ArangoDB实体必须具有@Document注解,它将集合名称作为一个参数。默认情况下,它是一个去首字母化的类名。

Next, we have two id fields. One with a Spring’s @Id annotation and a second one with Arango’s @ArangoId annotation. The first one stores the generated entity id. The second one stores the same id nut with a proper location in the database. In our case, these values could be accordingly 1 and articles/1.

接下来,我们有两个id字段。一个是Spring的@Id注释,另一个是Arango的@ArangoId注释。第一个存储生成的实体ID。第二个是存储相同的id螺母,并在数据库中找到合适的位置。在我们的案例中,这些值可以是相应的1articles/1

Now, when we have the entity defined, we can create a repository interface for data access:

现在,当我们定义了实体后,我们可以为数据访问创建一个资源库接口:

@Repository
public interface ArticleRepository extends ArangoRepository<Article, String> {}

It should extend the ArangoRepository interface with two generic parameters. In our case, it’s an Article class with an id of type String.

它应该扩展ArangoRepository接口,有两个通用参数。在我们的例子中,它是一个Article类,其id类型为String

6. CRUD Operations

6.CRUD操作

Finally, we can create some concrete data.

最后,我们可以创建一些具体的数据。

As a start point, we’ll need a dependency to the articles repository:

作为一个起点,我们需要一个对文章库的依赖关系。

@Autowired
ArticleRepository articleRepository;

And a simple instance of the Article class:

还有一个Article类的简单实例。

Article newArticle = new Article(
  "ArangoDb with Spring Data",
  "Baeldung Writer",
  ZonedDateTime.now()
);

Now, if we want to store this article in our database, we should simply invoke the save method:

现在,如果我们想将这篇文章存储在我们的数据库中,我们应该简单地调用save 方法:

Article savedArticle = articleRepository.save(newArticle);

After that, we can make sure that both the id and arangoId fields were generated:

之后,我们可以确保idarangoId领域都被生成:

assertNotNull(savedArticle.getId());
assertNotNull(savedArticle.getArangoId());

To fetch the article from a database, we’ll need to get its id first:

要从数据库中获取文章,我们需要先获得其ID。

String articleId = savedArticle.getId();

Then simply call the findById method:

然后简单地调用findById方法。

Optional<Article> articleOpt = articleRepository.findById(articleId);
assertTrue(articleOpt.isPresent());

Having the article entity, we can change its properties:

有了文章实体,我们可以改变它的属性。

Article article = articleOpt.get();
article.setName("New Article Name");
articleRepository.save(article);

Finally, invoke again the save method to update the database entry. It won’t create a new entry because the id was already assigned to the entity.

最后,再次调用save方法来更新数据库条目。它不会创建一个新的条目,因为id已经被分配给实体了。

Deleting entries is also a straightforward operation. We simply invoke the repository’s delete method:

删除条目也是一个简单的操作。我们只需调用版本库的delete方法。

articleRepository.delete(article)

Delete it by the id is also possible:

按id删除也是可以的。

articleRepository.deleteById(articleId)

7. Custom Queries

7.自定义查询

With Spring Data and ArangoDB, we can make use of the derived repositories and simply define the query by a method name:

通过Spring DataArangoDB,我们可以利用derived repositories并简单地通过方法名称定义查询。

@Repository
public interface ArticleRepository extends ArangoRepository<Article, String> {
    Iterable<Article> findByAuthor(String author);
}

The second option is to use AQL (ArangoDb Query Language). It’s a custom syntax language that we can apply with the @Query annotation.

第二个选择是使用AQL(ArangoDb查询语言)。这是一种自定义的语法语言,我们可以用@Query注解来应用。

Now, let’s take a look at a basic AQL query that’ll find all articles with a given author and sort them by the publish date:

现在,让我们来看看一个基本的AQL查询,它可以找到所有给定作者的文章,并按发布日期排序。

@Query("FOR a IN articles FILTER a.author == @author SORT a.publishDate ASC RETURN a")
Iterable<Article> getByAuthor(@Param("author") String author);

8. Relations

8.关系

ArangoDB gives as a possibility to create relations between entities.

ArangoDB提供了一种在实体之间创建关系的可能性。

As an example, let’s create a relation between an Author class and its articles.

作为一个例子,让我们在Author类和它的文章之间创建一个关系。

To do so, we need to define a new collection property with @Relations annotation that will contain links to each article written by a given author:

为此,我们需要定义一个带有@Relations注解的新集合属性,它将包含给定作者撰写的每篇文章的链接。

@Relations(edges = ArticleLink.class, lazy = true)
private Collection<Article> articles;

As we can see, the relations in ArangoDB are defined through a separate class annotated with @Edge:

正如我们所看到的,ArangoDB中的关系是通过一个单独的、带有@Edge注释的类定义的。

@Edge
public class ArticleLink {

    @From
    private Article article;

    @To
    private Author author;

    // constructor, getters and setters
}

It comes with two fields annotated with @From and @To. They define the incoming and outcoming relation.

它带有两个字段,注释为@From@To它们定义了传入和传出的关系。

9. Conclusion

9.结语

In this tutorial, we’ve learned how to configure ArangoDB and use it with Spring Data. We’ve covered basic CRUD operations, custom queries, and entity relations.

在本教程中,我们学习了如何配置ArangoDB并将其与 Spring Data 一起使用。我们已经涵盖了基本的CRUD操作、自定义查询和实体关系。

As always, all source code is available over on GitHub.

像往常一样,所有的源代码都可以在GitHub上找到