未找到约束“PRIMARY KEY | UNIQUE (ID)”;使用 Spring Tool Suite 4 IDE 的 SQL 语句

问题描述 投票:0回答:2

这是实际的错误

Failed to execute SQL script statement #6 of URL [file:/C:/Users/DELL/IdeaProjects/taco-cloud-1/bin/main/schema.sql]: alter table Ingredient_Ref add foreign key (ingredient) references Ingredient(id); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Constraint "PRIMARY KEY | UNIQUE (ID)" not found; SQL statement:
alter table Ingredient_Ref add foreign key (ingredient) references Ingredient(id) [90057-214]

这是我的sql代码。请问有什么语法错误吗,或者我遗漏了什么?

create table if not exists Taco_Order (
    id identity,
    delivery_Name varchar(50) not null,
    delivery_Street varchar(50) not null,
    delivery_City varchar(50) not null,
    delivery_State varchar(2) not null,
    delivery_Zip varchar(10) not null,
    cc_number varchar(16) not null,
    cc_expiration varchar(5) not null,
    cc_cvv varchar(3) not null,
    placed_at timestamp not null
);

create table if not exists Taco (
    id identity,
    name varchar(50) not null,
    taco_order bigint not null,
    taco_order_key bigint not null,
    created_at timestamp not null
);

create table if not exists Ingredient_Ref (
    ingredient varchar(4) not null,
    taco bigint not null,
    taco_key bigint not null
);

create table if not exists Ingredient (
    id varchar(4) not null,
    name varchar(25) not null,
    type varchar(10) not null
);

alter table Taco
    add foreign key (taco_order) references Taco_Order(id);
alter table Ingredient_Ref
    add foreign key (ingredient) references Ingredient(id);

它旨在作为一个 Web 应用程序与其他代码(html、java)一起运行,从 h2 数据库中获取这些数据。

sql spring-boot jdbc h2 spring-jdbc
2个回答
2
投票

在创建引用约束之前,您必须向表添加主键(或唯一)约束。

您也不应该在现代版本的 H2 中使用

identity
作为数据类型,此语法不受支持,并且仅在少数兼容模式下有效,与历史版本的 H2 的兼容性有限。

您需要在

id identity
id bigint generated by default as identity primary key
表的定义中将
Taco_Order
替换为
Taco
, 您还需要在
id varchar(4) not null
id varchar(4) primary key
表的定义中将
Ingredient_Ref
替换为
Ingredient


0
投票

只需将

id varchar(4) primary key
添加到
Ingredient_Ref
即可使其工作。

© www.soinside.com 2019 - 2024. All rights reserved.