Spring Data JPA Repository Populators – Spring Data JPA Repository Populators

最后修改: 2019年 4月 21日

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

1. Introduction

1.绪论

In this quick article, we’ll explore Spring JPA Repository Populators with a quick example. The Spring Data JPA repository populator is a great alternative for data.sql script.

在这篇快速文章中,我们将通过一个快速的例子来探讨Spring JPA 存储库弹出器。Spring Data JPA资源库弹出器是data.sql脚本的一个很好的替代品。

Spring Data JPA repository populator supports JSON and XML file formats. In the following sections, we’ll see how to use Spring Data JPA repository populator.

Spring Data JPA资源库弹出器支持JSON和XML文件格式。在下面的章节中,我们将看到如何使用Spring Data JPA资源库弹出器。

2. Sample Application

2.申请书样本

First of all, let’s say we have a Fruit entity class and an inventory of fruits to populate our database:

首先,假设我们有一个Fruit实体类和一个用于填充数据库的水果清单。

@Entity
public class Fruit {
    @Id
    private long id;
    private String name;
    private String color;
    
    // getters and setters
}

We’ll extend JpaRepository to read Fruit data from the database:

我们将扩展JpaRepository以从数据库中读取Fruit数据。

@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
    // ...
}

In the following section, we’ll use the JSON format to store and populate the initial fruit data.

在下一节中,我们将使用JSON格式来存储和填充初始水果数据。

3. JSON Repository Populators

3.JSON存储库填充器

Let’s create a JSON file with Fruit data. We’ll create this file in src/main/resources and call it fruit-data.json:

让我们创建一个包含Fruit数据的JSON文件。我们将在src/main/resources中创建这个文件,并称之为fruit-data.json

[
    {
        "_class": "com.baeldung.entity.Fruit",
        "name": "apple",
        "color": "red",
        "id": 1
    },
    {
        "_class": "com.baeldung.entity.Fruit",
        "name": "guava",
        "color": "green",
        "id": 2
    }
]

The entity class name should be given in the _class field of each JSON object. The remaining keys map to columns of our Fruit entity.

实体类的名称应该在每个JSON对象的_class字段中给出。其余的键映射到我们的Fruit实体的列。

Now, we’ll add the jackson-databind dependency in the pom.xml:

现在,我们将在pom.xml中添加jackson-databind依赖性。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

Finally, we’ll have to add a repository populator bean. This repository populator bean will read the data from the fruit-data.json file and populate it into the database when the application starts:

最后,我们要添加一个存储库填充器Bean。这个存储库填充器Bean将从fruit-data.json文件中读取数据,并在应用程序启动时将其填充到数据库中。

@Bean
public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() {
    Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
    factory.setResources(new Resource[]{new ClassPathResource("fruit-data.json")});
    return factory;
}

We’re all set to unit test our configuration:

我们已经准备好对我们的配置进行单元测试了。

@Test
public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() {
    List<Fruit> fruits = fruitRepository.findAll();
    assertEquals("record count is not matching", 2, fruits.size());

    fruits.forEach(fruit -> {
        if (1 == fruit.getId()) {
            assertEquals("apple", fruit.getName());
            assertEquals("red", fruit.getColor());
        } else if (2 == fruit.getId()) {
            assertEquals("guava", fruit.getName());
            assertEquals("green", fruit.getColor());
        }
    });
}

4. XML Repository Populators

4.可扩展标记语言存储库填充器

In this section, we’ll see how to use XML files with repository populators. Firstly, we’ll create an XML file with the required Fruit details.

在这一节中,我们将看到如何使用XML文件与版本库填充器。首先,我们将创建一个包含所需Fruit详细信息的XML文件。

Here, an XML file represents a single fruit’s data.

在这里,一个XML文件代表一个水果的数据。

apple-fruit-data.xml:

apple-fruit-data.xml

<fruit>
    <id>1</id>
    <name>apple</name>
    <color>red</color>
</fruit>

guava-fruit-data.xml:

guava-fruit-data.xml

<fruit>
    <id>2</id>
    <name>guava</name>
    <color>green</color>
</fruit>

Again, we’re storing these XML files in src/main/resources.

同样,我们将这些XML文件存储在src/main/resources.中。

Also, we’ll add the spring-oxm maven dependency in the pom.xml:

另外,我们将在pom.xml中添加spring-oxm maven依赖。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

In addition, we need to add @XmlRootElement annotation to our entity class:

此外,我们需要在我们的实体类中添加@XmlRootElement annotation。

@XmlRootElement
@Entity
public class Fruit {
    // ...
}

Finally, we’ll define a repository populator bean. This bean will read the XML file and populate the data:

最后,我们将定义一个资源库填充器bean。这个Bean将读取XML文件并填充数据。

@Bean
public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() {
    Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
    unmarshaller.setClassesToBeBound(Fruit.class);

    UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean();
    factory.setUnmarshaller(unmarshaller);
    factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), 
      new ClassPathResource("guava-fruit-data.xml") });
    return factory;
}

We can unit test the XML repository populator just like we can with the JSON populator.

我们可以像测试JSON populator一样,对XML repository populator进行单元测试。

4. Conclusion

4.总结

In this tutorial, we learned how to use Spring Data JPA repository populator. The complete source code used for this tutorial is available over on GitHub.

在本教程中,我们学习了如何使用Spring Data JPA资源库填充器。本教程所使用的完整源代码可在GitHub上获得