【问题标题】:Spring Boot Data InitializationSpring Boot 数据初始化
【发布时间】:2018-02-14 10:25:40
【问题描述】:

我试图在我的 Spring Boot 应用程序启动后插入一些测试数据。我有以下配置。我确实注意到在创建 JPA 实体之前执行了 sql 脚本,导致插入语句失败。我在这里还缺少其他配置吗?如我的配置中所述,我将 Spring Boot 与 H2 和 EclipseLink 用于 JPA。

参考 https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

配置

# H2
spring.h2.console.enabled=true
# Datasource
spring.datasource.url=jdbc:h2:mem:testdb;MODE=ORACLE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
# JPA
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.eclipselink.weaving=false

data.sql 放在 /src/main/resources 下

日志

2017-09-05 20:37:37,989 [restartedMain  ] INFO  
o.s.j.d.e.EmbeddedDatabaseFactory         - Starting embedded database: 
url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', 
username='sa'
2017-09-05 20:37:38,141 [restartedMain  ] INFO  
j.LocalContainerEntityManagerFactoryBean  - Building JPA container 
EntityManagerFactory for persistence unit 'default'
2017-09-05 20:37:38,446 [restartedMain  ] INFO  
o.s.o.j.AbstractEntityManagerFactoryBean  - Initialized JPA 
EntityManagerFactory for persistence unit 'default'
2017-09-05 20:37:38,510 [restartedMain  ] INFO  o.s.j.d.i.ScriptUtils                     
- Executing SQL script from URL  [file:/develop/src/data-init/target/classes/data.sql]
error...

实体

@Entity
@Table(name = "TEMPLATE_CONFIG")
@Data
public class TemplateUser {

    @Id
    @Column(name = "TEMPLATE_CONFIG_ID", nullable = false)
    private Long configId;

    @Column(name = "APP_CODE", nullable = false, length = 100)
    private String appCode;
    ...
}

更新

上传了一个示例项目: https://git.io/v5SWx

【问题讨论】:

  • 你能发布你的实体的样子吗?您需要用@Entity 注释标记它们
  • 添加了实体
  • 您是否也尝试过设置spring.jpa.hibernate.ddl-auto: create 属性? docs.spring.io/spring-boot/docs/current/reference/html/…
  • 如果我没有使用 Hibernate,这有什么问题吗?
  • 您可以尝试将数据源 url 更改为类似 jdbc:h2:mem:testdb?createDatabaseIfNotExist=true

标签: spring spring-boot


【解决方案1】:

Spring-Boot 加载 data.sql 或 data-${somthing}.sql

你可以这样做:

  • spring.datasource.platform=h2。
  • spring.datasource.data=myscript-test.sql。 (可以使用此属性更改位置)

我有一个项目正在进行中,并且正在使用 h2。

最后的选择,如果您无法加载信息,也许您可​​以在您的应用程序文件中使用带有 jdbc 模板的 CommandLineRunner。

【讨论】:

  • 我在加载 data.sql 时没有问题。这是运行sql的顺序。 sql 似乎在创建表之前运行。我提供了一个指向该问题的示例项目的链接。
【解决方案2】:

这是 Spring 团队在此处确认的现有错误。

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

【讨论】:

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