【发布时间】:2021-05-14 01:24:48
【问题描述】:
我在这个初始化脚本中使用 Spring Boot 和 Flyway:
CREATE TABLE ADDRESS(
ID bigserial NOT NULL PRIMARY KEY
);
CREATE TABLE ROLE(
ID bigserial NOT NULL PRIMARY KEY
);
CREATE TABLE PERSON(
ID bigserial NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(255),
LAST_NAME VARCHAR(255),
ADDRESS bigserial NOT NULL REFERENCES ADDRESS (ID),
ROLE bigserial REFERENCES ROLE (ID) -- notice here is no 'not null'
);
所有表之间的关系是:
- 每个
PERSON都有0-1ROLE。所以,每个ROLE都属于0-nPERSON。因此,这种关系是可以为空的。 - 每个
PERSON都有1ADDRESS。所以,每个ADDRESS都属于1-nPERSON。因此,这种关系不为空。
一旦我启动应用程序(我也尝试将查询直接发布到 PostgreSQL 数据库架构),PERSON 和 ROLE 表之间会以某种方式生成约束 not-null。
使用 DataGrip,我选择 SQL Scripts -> Generate DDL to Query Console 并获取表的 DDL(见下文,为了缘故省略了新行和角色定义简洁)。
令我惊讶的是,NOT NULL 就在那里,尽管我没有定义这样的约束。除了改变表,如何摆脱它?
create table if not exists address
(
id bigserial not null
constraint address_pkey primary key
);
create table if not exists role
(
id bigserial not nullconstraint role_pkey primary key
);
create table if not exists person
(
id bigserial not null
constraint person_pkey primary key,
first_name varchar(255),
last_name varchar(255),
address bigserial not null
constraint person_address_fkey references address,
role bigserial not null -- why is 'not null' here?
constraint person_role_fkey references role
);
我使用的 PostgreSQL 版本(通过SELECT version())是:
PostgreSQL 10.13, compiled by Visual C++ build 1800, 64-bit
【问题讨论】:
-
请注意,使用 Postgres 10 或更高版本的
identity列推荐优于serial:wiki.postgresql.org/wiki/Don't_Do_This#Don.27t_use_serial
标签: java spring postgresql spring-boot flyway