11t*_*ion 8 java spring spring-data-jpa spring-boot
注意:我在 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
异常。
如何同时
data.sql
使用和 实体类?schema.sql
这是该项目的示例代码。
功能性 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;
}
}
Run Code Online (Sandbox Code Playgroud)
模式.sql
create table test(id int(10), name varchar(10));
Run Code Online (Sandbox Code Playgroud)
数据.sql
insert into USER_DETAILS VALUES(1, 'user1');
insert into USER_DETAILS VALUES(2, 'user2');
insert into USER_DETAILS VALUES(3, 'user3');
Run Code Online (Sandbox Code Playgroud)
编辑*
@abaghel
正如重命名data.sql
为作品所建议的那样import.sql
,但是import.sql
无条件运行。那不是我需要的。
为了进行测试,我有一个 Maven 配置文件,它会激活特定的spring.datasource.platform = h2
,这又会强制 spring 加载schema-h2.sql
和data-h2.sql
。不幸的是,平台对此没有任何影响,import.sql
因此重命名它以import-h2.sql
阻止 Spring 加载它。
这是通过平台更改来重现此问题的分支。
https://github.com/ConsciousObserver/SpringBootSchemaSqlIssue/tree/platform-h2
Mar*_*rco 12
我知道这是一个老问题,但我在 2022 年遇到了同样的问题。data.sql
默认情况下,该文件似乎是在 Hibernate 创建模式之前执行的。为了避免这种情况,您需要设置该属性:
spring.jpa.defer-datasource-initialization=true
更多信息请参见:https://www.baeldung.com/spring-boot-h2-database#2-hibernate-and-datasql
归档时间: |
|
查看次数: |
11852 次 |
最近记录: |