How to add initial data in Spring Boot JPA applications

In order to have some data inserted at application start up, all you have to do is creating a data.sql file in your src/main/resources folder and it will be automatically executed on startup. Within this file, place your SQL INSERT Statements:

INSERT into CUSTOMER(id,name,surname) VALUES (1,'aaaa','bbbbbb') INSERT into CUSTOMER(id,name,surname) VALUES (2,'cccc','dddddd')

On the other hand, if you want to execute DDL, such as CREATE TABLE statements, you have to place them into a src/main/resources/schema.sql file

CREATE TABLE task (   id          INTEGER PRIMARY KEY,   description VARCHAR(64) NOT NULL,   completed   BIT NOT NULL);

Consider, however, that Tables are by default created by Spring Boot if you include Entity objects for an in memory database like H2. If you still want to use schema.sql you’ll have to disable this feature by adding this to your application.properties:

spring.jpa.hibernate.ddl-auto=none

Finally, it is worth mentioning that if you’re using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, …). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:

spring.datasource.initialization-mode=always

That’s all! We have demonstrated in this tutorial how to add initial data in Spring Boot JPA applications, by adding SQL scripts and DDL statements in your resources folder.