Chuyển đến nội dung

Bài 8 · Models and Entities

Primary Keys and Generated Values

Choose between auto-increment, UUID and composite primary keys in TypeORM and Sequelize, see how IDs are generated, and compare them with runnable examples.

Every row needs a stable identity. A primary key is the column (or columns) that uniquely identifies a row, and every relation in later chapters points at it. The main choice is where the value comes from: the database counts, or your application invents it.

Library code is read-only; the runnable stand-ins show key behaviour in plain Node and SQLite.

Auto-increment integers

The simplest option: the database assigns 1, 2, 3, ...

TypeScript
// TypeORM
@PrimaryGeneratedColumn()
id!: number;
TypeScript
// Sequelize
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }

Pros: small, fast, readable. Cons: guessable (users can try /orders/1001), awkward to merge from several databases, and the id is only known after the INSERT.

UUIDs

A UUID is a 128-bit random identifier such as 3f2b8c9e-.... You can generate it in the application before saving.

TypeScript
// TypeORM: generated by the database or driver
@PrimaryGeneratedColumn("uuid")
id!: string;
TypeScript
// Sequelize: generated in JavaScript
id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true }

Pros: unguessable, can be created offline, safe across databases. Cons: bigger than an integer and random (random inserts fragment B-tree indexes). Time-ordered variants (UUIDv7) keep inserts roughly sequential; check whether your database and driver support them.

Node.js Integer vs UUID

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Composite primary keys

A table can be identified by two columns together, typical for link tables.

TypeScript
// TypeORM: mark both columns
@Entity()
export class Enrollment {
  @PrimaryColumn() studentId!: number;
  @PrimaryColumn() courseId!: number;
  @Column({ type: "date" }) enrolledOn!: string;
}
TypeScript
// Sequelize: primaryKey: true on both
studentId: { type: DataTypes.INTEGER, primaryKey: true },
courseId:  { type: DataTypes.INTEGER, primaryKey: true },

Many teams still prefer a single surrogate id plus a unique constraint on the pair, because single-column keys make relations and URLs simpler.

Node.js Composite key rejects duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Natural vs surrogate keys

A natural key is real data (an email, an ISBN). A surrogate key is a meaningless id. Natural keys change (people change emails) and are often wrong in the real world. Default to a surrogate key and put a unique constraint on the natural identifier instead.

Reading the generated id

  • TypeORM: after await repo.save(entity) the same object now has its id.
  • Sequelize: const row = await Model.create(...) returns the instance with its id; with bulkCreate on some databases the ids are only filled when you pass returning: true.
  • Both copy values the database generated (defaults, ids) back onto the object on PostgreSQL via RETURNING; on MySQL, only the auto-increment id is available.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is an advantage of a UUID primary key over auto-increment?

    UUIDs can be generated anywhere and do not reveal how many rows exist.
  2. 2. Which TypeORM decorator creates an auto-increment key?

    PrimaryGeneratedColumn lets the database generate the value.
  3. 3. What happens when you insert a row that repeats an existing composite key?

    A primary key is unique; the second insert fails.
  4. 4. Why prefer a surrogate key plus a unique constraint on the email?

    A meaningless id stays stable when real-world data changes.

Summary

  • Auto-increment ids are small and simple but guessable and known only after insert.
  • UUIDs are unguessable and can be generated in code, at the cost of size and index locality.
  • Composite keys fit link tables; a surrogate id plus a unique pair is often easier.
  • Use surrogate keys and unique constraints for natural identifiers.
  • After saving, the generated id is copied back onto your object.

Next: Validation, Hooks and Timestamps

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.