我有一個小問題。我有一個 Spring Boot 應用程式,我將用資料填充我的 H2 資料庫。但是我無法從 data-h2.sql 檔案中加載初始資料庫資料。
模型:
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "mood")
public class Mood {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "mood_id")
private int id;
@Column(name = "name")
private String name;
public Mood(String name) {
this.name = name;
}
public Mood(int id, String name) {
this.id = id;
this.name = name;
}
}
資料-h2.sql 檔案:
INSERT INTO mood (name) VALUES ('Good');
應用程式屬性:
spring.datasource.url=jdbc:h2:mem:mooddb;
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=a
spring.datasource.password=a
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.defer-datasource-initialization=true
spring.h2.console.path=/h2-console
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false```
Sorry for the formatation, that is my first question :)
uj5u.com熱心網友回復:
問題是 spring 期望找到具有名稱schema.sql或data.sql類路徑中的檔案以進行加載。
但是您的檔案已命名,data-h2.sql因此即使正確放置在資源中,spring 也不會考慮它。
有2種解決方案:
將檔案重命名為
data.sql并確保它在資源檔案夾中不要重命名檔案并使用以下應用程式屬性通知 spring 它應該加載的檔案的名稱
spring.sql.init.data-locations=classpath:data-h2.sql
uj5u.com熱心網友回復:
操作指南是這樣的。
并且該屬性被命名為:
spring.sql.init.platform=h2
Spring Boot 可以自動創建 JDBC
DataSource或 R2DBC的模式(DDL 腳本)ConnectionFactory并對其進行初始化(DML 腳本)。它分別從標準根類路徑位置加載SQL:schema.sql和data.sql。此外,Spring Boot 處理schema-${platform}.sql和data-${platform}.sql檔案(如果存在),其中 platform 是spring.sql.init.platform. 這允許您在必要時切換到特定于資料庫的腳本。例如,您可以選擇將其設定為資料庫的供應商名稱(hsqldb, h2, oracle, mysql, postgresql等等)。默認情況下,SQL 資料庫初始化僅在使用嵌入式記憶體資料庫時執行。...
spring.jpa.defer-datasource-initialization=true
... 另一方面:
這會將資料源初始化推遲到
EntityManagerFactory創建和初始化任何bean之后。schema.sql然后可用于對 Hibernate 執行的任何模式創建進行添加,data.sql并可用于填充它。
(據我所知,手動使用EnitityManager)
還請考慮:
建議使用單一機制來生成模式。
(所以,不是休眠 腳本( 遷移工具)!)
和:
Spring Boot 支持兩種更高級別的遷移工具:Flyway 和 Liquibase。
一個常見的模式(對于 DDL)是:
- 使用 hibernate/jpa 生成/記錄 DDL 腳本(例如,當新物體進化時)
- 在 flyway/liquibase 中使用這些。
uj5u.com熱心網友回復:
謝謝你。我重命名了檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402479.html
標籤:
