我在应用程序初始化时将数据加载到内存数据库时遇到问题。我创建了包含表结构和初始数据的 schema.sql 和 data.sql 文件。
架构.sql :
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(64) NOT NULL,
password VARCHAR(64)
);
和data.sql:
INSERT INTO users (id, username, password) VALUES
(1, 'usr1', 'bigSecret'),
(2, 'usr2', 'topSecret');
我正在使用 JpaRepository
处理数据层:
public interface UserRepository extends JpaRepository<User, Long> {
}
而且我还配置了application.properties
spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=- 1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
但是当我调用
List<User> users = userRepository.findAll();
用户实体
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
public User() { }
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
我得到一个空列表,但我应该从我的内存 H2 数据库中得到两个预填充的用户。内存数据库有什么问题? 谢谢。
最佳答案
您始终可以尝试按照 h2 规范运行这些脚本,您应该在连接 url 中添加一个 INIT 脚本(作为选项之一):
jdbc:h2:mem:test;INIT=RUNSCRIPT FROM '~/schema.sql'\;RUNSCRIPT FROM '~/data.sql'"
This functionality is enabled via the INIT property. Note that multiple commands may be passed to INIT, but the semicolon delimiter must be escaped, as in the example below.
更新
请注意,在您的 application.properties
中有这些选项:
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=true
spring.datasource.initialize=true
可能会在启动时引起一些冲突。因此,您应该始终以其中之一为目标,但绝不能同时瞄准两者。 对于简单的情况,仅仅这些就足以自动构建表并在关机和启动后重新加载
关于java - 内存数据库H2中的Spring Boot不会在初始化时从文件加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41841072/