data.sql is executed before JPA entities are created and it creates the error that the table is not found. can anyone help me with it? I have seen the same question in this link Spring Boot – Loading Initial Data but the question is not answered.
Advertisement
Answer
This is a normal and wanted behaviour from Springboot since version 2.5 I believe. The idea behind this is that pure SQL (with schema.sql
and data.sql
) and JPA based database creation technologies are two different approaches to database initialisation.
By default, the framework will assert that only one is used and give priority to SQL based. The initialisation will be done in this order :
- Run
schema.sql
to create and manipulate the database structure (DDL) - Run
data.sql
to populate the database (DML) - Initialize your
EntityManagerFactory
To implement the behaviour that you want, you need to tell him to prioritize JPA over pure SQL. This can be done by settings this in your configuration :
spring.jpa.defer-datasource-initialization=true
More details are available in the official documentation, point 9.3 specifically.