我使用H2来测试我的数据库代码。为此,我首先阅读一组SQL文件并使用RunScript.execute
来执行SQL。
我真正的数据库是MySQL,我测试了SQL脚本以确保它们正常工作。问题显然是在H2内部。这是一组脚本:
CREATE TABLE stores (
id integer AUTO_INCREMENT PRIMARY KEY,
name varchar(255) NOT NULL,
UNIQUE(name),
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at timestamp
);
CREATE TABLE regions (
id integer AUTO_INCREMENT PRIMARY KEY,
name varchar(255) NOT NULL,
UNIQUE(name),
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at timestamp
);
CREATE TABLE products (
id integer AUTO_INCREMENT PRIMARY KEY,
store_id integer NOT NULL,
name varchar(255) NOT NULL,
region_id integer NOT NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at timestamp,
UNIQUE(store_id, name),
FOREIGN KEY store_fk(store_id) REFERENCES stores(id),
FOREIGN KEY region_fk(region_id) REFERENCES regions(id)
);
使用MySQL Workbench运行这3个脚本来创建表可以正常工作。通过以下代码从JUnit运行它们不会:
Reader storeTableSql = new InputStreamReader(
DatabaseConnectorTests.class.getResourceAsStream(
"/migrations/V1__create_stores_table.sql"));
Reader regionTableSql = new InputStreamReader(
DatabaseConnectorTests.class.getResourceAsStream(
"/migrations/V2__create_regions_table.sql"));
Reader productTableSql = new InputStreamReader(
DatabaseConnectorTests.class.getResourceAsStream(
"/migrations/V3__create_products_table.sql"));
this.dc = DatabaseConnector.getConnection();
RunScript.execute(dc, storeTableSql);
RunScript.execute(dc, regionTableSql);
RunScript.execute(dc, productTableSql);
我收到以下错误:
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE PRODUCTS (
ID INTEGER AUTO_INCREMENT PRIMARY KEY,
STORE_ID INTEGER NOT NULL,
NAME VARCHAR(255) NOT NULL,
REGION_ID INTEGER NOT NULL,
CREATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UPDATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
DELETED_AT TIMESTAMP,
UNIQUE(STORE_ID, NAME),
FOREIGN KEY STORE_FK[*](STORE_ID) REFERENCES STORES(ID),
FOREIGN KEY REGION_FK(REGION_ID) REFERENCES REGIONS(ID)
) "; expected "("; SQL statement:
CREATE TABLE products (
id integer AUTO_INCREMENT PRIMARY KEY,
store_id integer NOT NULL,
name varchar(255) NOT NULL,
region_id integer NOT NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at timestamp,
UNIQUE(store_id, name),
FOREIGN KEY store_fk(store_id) REFERENCES stores(id),
FOREIGN KEY region_fk(region_id) REFERENCES regions(id)
) [42001-196]
此代码适用于MySQL,我在MySQL兼容模式下通过以下连接字符串运行H2:jdbc:h2:file:~/database;MODE=MySQL
。我不知道我还能在这做什么。这个错误对我来说似乎很奇怪,因为我不知道它为什么会认为我需要另一个(
。
有谁知道如何解决这个问题?或者对如何种植我的测试数据库有更好的建议?由于对我运行的系统的限制,我无法使用hibernate执行此任务,因此我不得不手动执行大量操作。
谢谢!