【问题标题】:Spring Boot database initialization only one timeSpring Boot 数据库初始化只有一次
【发布时间】:2018-05-02 08:28:16
【问题描述】:

我有一个 Spring Boot 后端应用程序,我正在寻找一种在 MySQL 数据库中插入初始化数据的方法,但仅限于每次创建表时。我用 data.sql 做到了,但每次服务器启动时都会插入数据。我希望我的问题很清楚。谢谢你的时间:)

【问题讨论】:

  • 为此使用 Flyway 或 Liquibase 之类的东西。
  • 或者先做个count查询,看看表有没有数据。

标签: java database spring-boot


【解决方案1】:

Spring Boot 提供的Database initialising 只能用于嵌入式数据库。所以它或多或少假设您必须在每次启动应用程序时初始化数据库。

对于持久性数据库的正确初始化和演变,请使用 FlywayLiquibase

【讨论】:

  • 我问这个问题可能已经太久了。但无论如何我还是想感谢你。 :)
【解决方案2】:

它在不使用 Flyway 的情况下对我正常工作。

我有一个 Spring Boot 应用程序和 Mysql 数据库。我有多个 data.*.sql 文件。 application.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

其中一个data.*.sql文件:

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

模型类的内容:

    @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

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2017-07-29
    • 2022-01-18
    • 2018-03-22
    • 2017-10-16
    • 2018-07-25
    相关资源
    最近更新 更多