zgkais
zgkais

Reputation: 43

Spring Boot database initialization only one time

I have a spring boot backend application and I'm looking for a way to insert initialization data in a MySQL database but only each time the tables are created. I did that with data.sql but the data gets inserted every time the server starts. I hope my question is clear. Thank you for your time :)

Upvotes: 4

Views: 2798

Answers (2)

Goku__
Goku__

Reputation: 970

It's properly working for me without using Flyway.

I have a spring boot application and Mysql db. I have multiple data.*.sql files. The application.properties have the following properties.

## To enable reading data from multiple files
spring.datasource.data = classpath:data.*.sql

# Initialize the datasource with available DDL and DML scripts
spring.datasource.initialization-mode=always 

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

One of the data.*.sql file:

INSERT IGNORE INTO complaintPriority(name) VALUES('EMERGENCY');
INSERT IGNORE INTO complaintPriority(name) VALUES('HIGH');
INSERT IGNORE INTO complaintPriority(name) VALUES('MEDIUM');

Contents of the model class:

    @Entity
    @Access(value=AccessType.FIELD)
    @Table(name = "complaintPriority", uniqueConstraints = {
            @UniqueConstraint(columnNames = {
                    "complaintPriorityId"
            })
    })
    
    public class ComplaintPriority {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        Long complaintPriorityId;
// Other variables and methods

Upvotes: 0

Nikem
Nikem

Reputation: 5784

Database initialising provided by Spring Boot is meant to be used only with embedded databases. So it more or less assumes that you have to initialise the database on every start of the application.

For the proper initialising and evolution of persistent databases use Flyway or Liquibase

Upvotes: 2

Related Questions