Проблемы с ограничением FK defenition - PullRequest
0 голосов
/ 24 декабря 2018

Моя проблема в том, что я пытаюсь настроить базу данных h2 и использую некоторые сценарии для этого.Не удается запустить приложение при создании таблиц.Листинг и трассировка стека находятся ниже.Это для внутренней разработки, и эти сценарии генерируются автоматически с IDEA.Я плохо с SQL, поэтому я думаю, что это может быть детской ошибкой.Но почему-то я проверил много сайтов, статей и т. Д. И до сих пор не знаю, где я не прав.

create table Table1
(
    record_ID int not null,
    dateTime datetime not null,
    timerName varchar(14) not null
        constraint Table1_Table2_timerName_fk
        references Table2(timerName)
            on update cascade,
    status smallint,
    primary key (record_ID, spotName, partIdentString)
);

create table Table2
(
    timerName varchar(14) not null
        constraint Table2_pk
        primary key nonclustered,
    center varchar(2),
    station varchar(4)  not null,
    cell varchar(6)  not null,
    place varchar(10) not null
);

Затем я пытаюсь запустить приложение, которое завершается неудачно с

Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of file [****\target\classes\sql\schema\my_dbo_Table1.sql]: create table Table1 ( record_ID int not null, dateTime datetime not null, timerName varchar(14) not null constraint 
Table1_Table2_timerName_fk references Table2(timerName) on update cascade, status smallint, primary key (record_ID, spotName, partIdentString) ); nested exception is org.h2.jdbc.JdbcSQLException: Table "Table2" not found; SQL statement:
create table Table1 ( record_ID int not null, dateTime datetime not null, timerName varchar(14) not null constraint Table1_Table2_timerName_fk references Table2(timerName) on update cascade, status smallint, primary key (record_ID, spotName, partIdentString) ) [42102-197]
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:493)
    at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:238)
    at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:48)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runScripts(DataSourceInitializer.java:192)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runSchemaScripts(DataSourceInitializer.java:92)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.init(DataSourceInitializer.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134)
    ... 67 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLException: Table "Table2" not found; SQL statement:
create table Table1 ( record_ID int not null, dateTime datetime not null, timerName varchar(14) not null constraint Table1_Table2_timerName_fk references Table2(timerName) on update cascade, status smallint, primary key (record_ID, spotName, partIdentString) ) [42102-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.command.ddl.AlterTableAddConstraint.tryUpdate(AlterTableAddConstraint.java:204)
    at org.h2.command.ddl.AlterTableAddConstraint.update(AlterTableAddConstraint.java:78)
    at org.h2.command.ddl.CommandWithColumns.createConstraints(CommandWithColumns.java:88)
    at org.h2.command.ddl.CreateTable.update(CreateTable.java:122)
    at org.h2.command.CommandContainer.update(CommandContainer.java:102)
    at org.h2.command.Command.executeUpdate(Command.java:261)
    at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:233)
    at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:205)
    at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95)
    at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java)
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:472)
    ... 79 common frames omitted

1 Ответ

0 голосов
/ 24 декабря 2018

вложенным исключением является org.h2.jdbc.JdbcSQLException: таблица "Table2" не найдена;

Table1, которую вы пытаетесь создать первой, имеет ограничение, ссылающееся на Table2,

Чтобы устранить ошибку, инвертируйте команды CREATE TABLE в своем скрипте: сначала необходимо создать Table2, а затем Table1.

NB: DateTime - тип данных для sqlserver.Вам следует избегать именования ваших столбцов зарезервированными словами, это может вызвать неожиданное поведение.

...