首页 > 解决方案 > TypeORM:插入新实体时发生错误:“id”列中的空值违反非空约束

问题描述

我正在使用 PostgreSQL 和 TypeORM。我的创建表是:

CREATE TABLE "my_table"("id" uuid NOT NULL, CONSTRAINT PK_my_table PRIMARY KEY (id));

我的实体类定义是:

import { Entity, Generated, PrimaryColumn } from 'typeorm';

@Entity('my_table')
export class MyTable {
    @PrimaryColumn({ type: 'uuid' })
    @Generated('uuid')
    id!: string;
}

当我跑

entityManager.getRepository(MyTable).save({});

我收到错误消息:

(node:85) UnhandledPromiseRejectionWarning: QueryFailedError: null value in column "id" violates not-null constraint

所以似乎没有生成 id 。这很奇怪,因为当其他实体保存在应用程序中时,这是有效的。

可能有什么问题??我已经简化了测试这个问题的真实情况。

标签: typeorm

解决方案


我手动生成了 uuid,我的实体是:

@Entity('my_table')
export class MyTable {    
    @PrimaryColumn({ type: 'uuid' })
    id!: string;
}

这是有效的。


推荐阅读