内存数据库H2中的Spring

内存数据库H2中的Spring

本文介绍了内存数据库H2中的Spring Boot在初始化时不会从文件加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序初始化时将数据加载到内存数据库中时遇到问题。我创建了包含表格结构和初始数据的 schema.sql data.sql 文件。

I have an issue with loading data into in-memory database on application initialization. I have created schema.sql and data.sql files containing table structure and initial data.

schema.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 来处理数据layer:

I am using JpaRepository for working with data layer:

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数据库的人口用户。内存数据库有什么问题?
谢谢。

I get empty list, but I should get two pre-populated users from my in-memory H2 database. What's wrong with in memory database?Thanks.

推荐答案

您可以随时尝试按h2规范运行这些脚本,您应该在其中添加INIT你的连接url中的脚本(作为选项之一):

You can always try to run those scripts per specification of h2, where you should add an INIT script in your connection url (being one of the options):

jdbc:h2:mem:test;INIT=RUNSCRIPT FROM '~/schema.sql'\;RUNSCRIPT FROM '~/data.sql'"



更新

请注意,在您的 application.properties

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=true
spring.datasource.initialize

可能会在启动过程中引起一些冲突。所以你应该始终瞄准一个或另一个,但永远不要两者同时进行。

may cause some clashing during startup. So you should always aim for one or the other, but never both at the same time.

这篇关于内存数据库H2中的Spring Boot在初始化时不会从文件加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 10:44