【发布时间】:2018-10-03 16:46:24
【问题描述】:
我的 spring boot 2.0 应用程序识别并运行 schema.sql 来初始化我的嵌入式 h2 数据库。但是当我添加 spring-cloud-starter-config 依赖项时,应用程序不再运行 schema.sql。为了说明,使用spring initializr 生成一个Spring Boot 2 (v2.0.1) 应用程序,其依赖于:
- 网络
- 其他存储库
- jpa
- h2
- 配置客户端
添加实体:
package com.example.demo;
import javax.persistence.*;
@Entity
public class Room {
@Id
@Column(name = "ROOM_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column
private String name;
//...getters and setters
}
实体的存储库:
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RoomRepository extends CrudRepository<Room, Long> {
}
主类与 initializr 生成的内容没有变化:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
将 schema.sql 和 data.sql 文件添加到资源下的基本文件夹中。 Spring Boot 使用这些来创建和填充实体的基础表:
schema.sql:
CREATE TABLE ROOM(
ROOM_ID BIGINT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(16) NOT NULL,
);
data.sql:
INSERT INTO ROOM (NAME) VALUES ('Piccadilly');
INSERT INTO ROOM (NAME) VALUES ('Cambridge');
INSERT INTO ROOM (NAME) VALUES ('Oxford');
INSERT INTO ROOM (NAME) VALUES ('Manchester');
用这个application.yml替换空的application.properties:
spring:
jpa:
hibernate.ddl-auto: none
现在,运行应用程序并转到http://localhost:8080/rooms。应用程序将失败并出现 JdbcSQLException 表明该表不存在:
org.h2.jdbc.JdbcSQLException:找不到表“ROOM”; SQL 语句: 从房间 room0_ 中选择 room0_.room_id 作为 room_id1_0_, room0_.name 作为 name2_0_
现在进入 pom.xml 并注释掉对 spring-cloud-starter-config 依赖项的引用:
<!--
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
-->
重新启动应用程序,现在一切正常!在浏览器中打开http://localhost:8080/rooms,您会发现返回了预期的 JSON 结果(包含 4 行)。这告诉我是 spring-cloud-starter-config 依赖阻止了 Spring 执行 schema.sql 和 data.sql 来初始化数据库。
当我使用 Spring Cloud 依赖项时,如何让 Spring Boot 执行 schema.sql 和 data.sql 文件?
【问题讨论】:
-
你能发布你的主要课程吗?
-
添加了主类。它与 initialzr 生成的内容没有变化。
标签: java spring spring-boot spring-cloud