简体   繁体   中英

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 :)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM