Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Spring Data JPA Repository Populators

$
0
0

1. Introduction

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 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.

2. Sample Application

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

@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:

@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.

3. JSON Repository Populators

Let’s create a JSON file with Fruit data. We’ll create this file in src/main/resources and call it 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.

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

<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
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

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.

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

apple-fruit-data.xml:

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

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.

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

<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
@Entity
public class Fruit {
    // ...
}

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

@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.

4. Conclusion

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.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>