【问题标题】:Do or don't I need to create a table that I want to prepopulate with H2?我是否需要创建一个我想用 H2 预填充的表?
【发布时间】:2016-06-03 13:48:28
【问题描述】:

我对在尝试为我的 Spring Boot 应用程序创建内存 H2 DB 时遇到的错误感到困惑。相关配置是

db.url=jdbc:h2:mem:test;MODE=MySQL;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:create.sql'
hibernate.hbm2ddl.auto=create

还有create.sql

CREATE TABLE `cities` (
  `name` varchar(45)  NOT NULL,
  PRIMARY KEY (`name`)
) ;

INSERT INTO `cities` VALUES ('JAEN'),('ALBACETE');

但我收到错误 Caused by: org.h2.jdbc.JdbcSQLException: Table "CITIES" already exists;

奇怪的是,如果我删除 CREATE TABLE 语句,我会得到:

Caused by: org.h2.jdbc.JdbcSQLException: Table "CITIES" not found;

唯一有效的方法是使用DROP TABLE IF EXISTS,但是我认为我不需要这样做。

发生了什么事?将静态数据预填充到 H2 内存数据库中的正确方法是什么?

【问题讨论】:

    标签: database hibernate h2 in-memory-database


    【解决方案1】:

    1) Hibernate方式:使用import.sql文件或指定文件

    spring.jpa.properties.hibernate.hbm2ddl.import_files=file1.sql,file2.sql

    http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

    2) Spring Boot:使用默认的 schema.sql & data.sql 文件 或者通过属性指定文件

    spring.datasource.schema = file1.sql spring.datasource.data = file1.sql, file2.sql

    http://docs.spring.io/autorepo/docs/spring-boot/1.0.2.RELEASE/reference/html/howto-database-initialization.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多