Home > front end >  Cannot add initial data to database with Spring Boot (Hibernate)
Cannot add initial data to database with Spring Boot (Hibernate)

Time:11-06

I use Hibernate in my Spring Boot app and populate the tables without any problem. However, I am trying to add 2 record to one of the populated table using import.sql on the classpath.

INSERT INTO role(id, role_type) VALUES(1, 'ADMIN');
INSERT INTO role(id, role_type) VALUES(2, 'USER');

I also set the following properties:

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.defer-datasource-initialization=true
spring.sql.init.mode=always

When I run the app, tables are created and the data is populated, and tables are created. However, I got "Error executing DDL : alter table user_role drop foreign key" error.

When I update spring.jpa.hibernate.ddl-auto as shown below, there is no error and tables are created. BUT, records are not inserted to the role table:

spring.jpa.hibernate.ddl-auto= update

So, how can I insert data when I run the app without any problem?

CodePudding user response:

import.sql will only be executed provided that spring.jpa.hibernate.ddl-auto is set to create or create-drop.

also can you try adding add @OnDelete(action = OnDeleteAction.CASCADE) to your Role table to check if it fixes the foriegn key error.

Alternatively you can use data.sql it will be executed irrespective of hibernate.ddl configuration.

Using spring.jpa.hibernate.ddl-auto= update and data.sql should solve both of your error.

spring.sql.init.mode=always 
spring.jpa.defer-datasource-initialization=true

Use defer-datasource

  • Related