java - Spring Boot 在存在 schema.sql 的情况下创建实体之前运行 data.sql

标签 java spring spring-boot spring-data-jpa

注意:我已经在 Spring boot 存储库上打开了一个问题。这是链接

https://github.com/spring-projects/spring-boot/issues/9048

我正在尝试在我的实体中插入一些行,以便使用 H2 数据库在开发人员机器上进行测试。为此,我正在使用 data.sql

它工作正常,创建实体,然后运行 ​​data.sql 以将数据插入实体生成的表中。

但是我需要创建一些没有实体类的其他表,所以我使用 schema.sql 来处理这些表。问题来了,只要我将 schema.sql 添加到项目中,Spring Boot 就会在创建实体之前运行 data.sql,结果以 Table not found< 结束异常。

How can I get data.sql working with the schema.sql and entity classes at the same time ?

这是项目的示例代码。

用于重现问题的功能性 Maven 项目的 Git 链接。

https://github.com/ConsciousObserver/SpringBootSchemaSqlIssue.git

package com.test;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestDataSqlApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestDataSqlApplication.class, args);
    }
}

@Entity
@Table(name="USER_DETAILS")
class UserDetails {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

schema.sql

create table test(id int(10), name varchar(10));

data.sql

insert into USER_DETAILS VALUES(1, 'user1');
insert into USER_DETAILS VALUES(2, 'user2');
insert into USER_DETAILS VALUES(3, 'user3');

编辑 *

正如 @abaghel 所建议的那样,将 data.sql 重命名为 import.sql 是可行的,但是 import.sql无条件运行。那不是我需要的。

为了测试,我有一个激活特定 spring.datasource.platform = h2 的 Maven 配置文件,这反过来会强制 spring 加载 schema-h2.sqldata-h2.sql。不幸的是,平台对 import.sql 没有影响,因此将其重命名为 import-h2.sql 会阻止 Spring 加载它。

这是重现此问题的平台更改分支。

https://github.com/ConsciousObserver/SpringBootSchemaSqlIssue/tree/platform-h2

最佳答案

我知道这是一个老问题,但我在 2022 年遇到了同样的问题。 似乎 data.sql 文件默认在 Hibernate 创建模式之前执行。为避免这种情况,您需要设置属性: spring.jpa.defer-datasource-initialization=true

更多信息在这里:https://www.baeldung.com/spring-boot-h2-database#2-hibernate-and-datasql

关于java - Spring Boot 在存在 schema.sql 的情况下创建实体之前运行 data.sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43692115/

相关文章:

java - 鼓励Admob点击违反TOS?

java - JTable和Table模型什么时候用什么时候?

java - 如何在maven中从外部jar复制资源?

spring-boot - 多模块spring boot项目中的单元测试

mysql - 保存对象上的 Hibernate 空指针

java - 具有日期属性的 Hibernate Search MultiFieldQueryParser

java spaceship 游戏

javascript - 将表单从 Angular JS 发送到 Spring

java - Spring Web Flow 和 Spring MVC URL 404

spring-boot - 当我尝试运行Spring Boot Web应用程序时得到BeanCreationException吗?