Course – LSD – NPI (cat=Persistence)
announcement - icon

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:


1. Overview

Spring Boot allows us to import sample data into our database – mainly to prepare data for integration tests. Out of the box, there are two possibilities. We can use import.sql (Hibernate support) or data.sql (Spring JDBC support) files to load data.

However, sometimes we want to split one big SQL file into a few smaller ones, e.g., for better readability or to share some files with an init data between modules.

In this tutorial, we’ll show how to do it with both – Hibernate and Spring JDBC.

2. Hibernate Support

We can define files which contain sample data to load with a property It can be set in the file inside the test resources folder.

This is in a case we want to load sample data just for JUnit tests. The value has to be a comma-separated list of files to import:,import_inactive_users.sql

This configuration will load sample data from two files: import_active_users.sql and import_inactive_users.sql. Important to mention here is that we have to use prefix to pass values (JPA configuration) to the EntityManagerFactory.

Next, we’ll show how we can do it with the Spring JDBC support.

3. Spring JDBC Support

The configuration for initial data and Spring JDBC support is very similar to Hibernate. We have to use the property:,import_inactive_users.sql

Setting the value as above gives the same results as in the Hibernate support. However, a significant advantage of this solution is the possibility to define value using an Ant-style pattern:*_users.sql

The above value tells the Spring to search for all files with a name that matches import_*_users.sql pattern and import data which is inside.

This property was introduced in Spring Boot 2.5.0; in earlier versions of Spring Boot, we need to use the property.

4. Conclusion

In this short article, we showed how to configure a Spring Boot application to load initial data from custom SQL files.

Finally, we showed two possibilities – Hibernate and Spring JDBC. They both work pretty well, and it’s up to the developer which one to chose.

As always, the complete code examples used in this article are available over on Github.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

res – Persistence (eBook) (cat=Persistence)
Comments are closed on this article!