乐闻世界logo
搜索文章和话题

How to auto generated UUID in PostgreSQL in TypeORM

2个答案

1
2

When using TypeORM with PostgreSQL, generating UUIDs automatically is highly beneficial, especially when handling data rows that require unique identifiers. To implement automatically generated UUIDs in TypeORM, you can achieve this through several approaches.

Using Database Default Values

In PostgreSQL, you can utilize the uuid-ossp extension, which provides functions for generating UUIDs. First, ensure your PostgreSQL database has the uuid-ossp extension installed. You can install it by executing the following SQL command:

sql
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Next, within your TypeORM entity, use the @Column decorator and specify the default property to invoke the uuid_generate_v4() function, which automatically generates a UUID each time a new record is created. For example:

typescript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn('uuid') id: string; @Column({ type: 'varchar', length: 255 }) name: string; }

In the above code, @PrimaryGeneratedColumn('uuid') instructs TypeORM to use UUID as the primary key and to generate new UUID values by default using PostgreSQL's uuid_generate_v4() function.

Using TypeORM Decorators

If you prefer not to rely on database defaults or wish to handle UUID generation at the application level, you can employ the BeforeInsert decorator in TypeORM to generate UUIDs before inserting records. This can be done using the uuid library for JavaScript; first, install this library:

bash
npm install uuid

Then, import and integrate it into your entity:

typescript
import { Entity, PrimaryColumn, Column, BeforeInsert } from 'typeorm'; import { v4 as uuidv4 } from 'uuid'; @Entity() export class User { @PrimaryColumn() id: string; @Column({ type: 'varchar', length: 255 }) name: string; @BeforeInsert() addId() { this.id = uuidv4(); } }

In this example, the addId function is triggered before inserting a new User instance, setting the id field to a newly generated UUID.

Summary

The choice of method depends on your preference regarding the division of responsibilities between the database and application logic. Using database defaults (such as uuid-ossp) effectively leverages database capabilities, while generating UUIDs at the application level (e.g., with the uuid library and @BeforeInsert) offers greater flexibility and control. When selecting an approach, consider your application's specific requirements and the expected database interaction patterns.

2024年8月4日 16:56 回复

UUID的生成与TypeORM的使用

面试官:首先,欢迎您来到我们的面试。今天我们想讨论一下在TypeORM中怎样为PostgreSQL数据库自动生成UUID。您能否介绍一下什么是UUID以及它在数据库中的应用?

:谢谢,很高兴有机会和您讨论这个技术问题。UUID代表的是通用唯一识别码(Universally Unique Identifier),它是一种为了能在分布式系统中无需中心数据库就能保证全球唯一性而设计的标识符。UUID的一个常见用途是在数据库中作为主键使用,这样可以避免主键冲突,特别是在多个数据库同步或大规模系统中。

面试官:非常好的解释。那么您能说明一下在TypeORM中如何实现自动生成UUID的功能吗?

:当然可以。在TypeORM中,我们可以通过使用PostgreSQL的uuid类型和默认函数uuid_generate_v4()来实现自动生成UUID。首先,需要确保PostgreSQL数据库已经安装了uuid-ossp模块,因为uuid_generate_v4()函数是这个模块提供的。

sql
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

接下来,在TypeORM中定义实体时,可以在列装饰器中指定列的类型为uuid并设置默认值为uuid_generate_v4()。例如:

typescript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn('uuid', { default: () => 'uuid_generate_v4()' }) id: string; @Column() name: string; }

在这个例子中,每当创建一个新的User实例并将其存入数据库时,PostgreSQL会自动为id字段生成一个新的UUID。

面试官:这是个很实用的例子,谢谢您的分享。在实际使用中,使用UUID作为主键会有什么潜在的性能影响吗?

:使用UUID作为主键主要的潜在影响是其大小和随机性。UUID是128位的,相比于传统的递增整型主键,它占用更多的存储空间。此外,由于UUID是随机生成的,它们的插入可能会导致数据库索引的频繁重建,这可能会影响插入操作的性能。然而,对于大多数应用来说,这种性能影响是可以接受的,特别是考虑到UUID带来的好处,如易于扩展和避免冲突等。

面试官:非常详尽的答复,感谢您的参与和分享。您对TypeORM和PostgreSQL的理解让我们印象深刻。

2024年8月3日 16:34 回复

你的答案