Chuyển đến nội dung

Bài 3 · Getting Started

Your First Entity and Model

Define your first TypeORM entity and Sequelize model, save and read a row, and see how a class becomes a table through a runnable class-to-table stand-in.

An entity (TypeORM) or model (Sequelize) is a class that stands for one table. Each property is a column, each instance is a row. This lesson defines the same User in both libraries, saves one, and reads it back.

Library code is read-only. The runnable blocks are stand-ins that turn a class description into a CREATE TABLE statement so you can see the mapping.

TypeORM: a decorated class

TypeScript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  name!: string;

  @Column({ default: true })
  isActive!: boolean;
}

@Entity() marks the class as a table (named user by default). @PrimaryGeneratedColumn() is an auto-increment key. @Column() reads the property type from TypeScript metadata (this is why reflect-metadata and emitDecoratorMetadata are needed). The ! tells TypeScript that the ORM fills the property.

Use it through the DataSource (registered in entities: [User]):

TypeScript
const users = AppDataSource.getRepository(User);

const ana = users.create({ name: "Ana" });   // plain object, not saved yet
await users.save(ana);                       // INSERT
console.log(ana.id);                         // 1

const found = await users.findOneBy({ id: 1 });
console.log(found?.name);                    // "Ana"

Sequelize: a model class

TypeScript
import { DataTypes, Model, InferAttributes, InferCreationAttributes,
         CreationOptional } from "sequelize";

export class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
  declare id: CreationOptional<number>;
  declare name: string;
  declare isActive: CreationOptional<boolean>;
}

User.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false },
    isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
  },
  { sequelize, tableName: "users" }
);

Here the columns are listed in User.init, and the declare fields only give TypeScript the types. (declare matters: a normal class field would shadow Sequelize's getters.) In plain JavaScript you skip the declare lines.

TypeScript
await sequelize.sync();                           // create tables that do not exist
const ana = await User.create({ name: "Ana" });   // INSERT
console.log(ana.id);                              // 1
const found = await User.findByPk(1);
console.log(found?.name);                         // "Ana"

Class in, table out

Both libraries read your description and generate DDL. This stand-in does the same from a plain schema object:

Node.js Schema to CREATE TABLE

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.

That is all synchronize and sync() really do: compare descriptions with the database and issue DDL. Later chapters explain why you replace them with migrations in production.

Saving and reading, stand-in version

Node.js Create and read

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.

The database itself enforces NOT NULL. The ORM passes your intent down; it does not replace the constraints.

Naming conventions

  • TypeORM derives the table name from the class (User becomes user); override it with @Entity("users").
  • Sequelize pluralizes the model name by default (User becomes Users); override it with tableName, as above, or freezeTableName: true.
  • Column names default to the property name. Both let you map isActive to is_active; lesson 5 and 6 show how.

Pick a convention (plural snake_case tables are common) and apply it everywhere.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does a row in the table correspond to?

    The class is the table; each instance is one row.
  2. 2. Why does a TypeScript Sequelize model use declare for its fields?

    declare only gives the compiler the types; the columns come from Model.init.
  3. 3. What does sync() or synchronize do?

    It issues DDL from your entity or model description; use migrations in production.
  4. 4. Which TypeORM call stores a new object in the database?

    create() only builds the object in memory; save() runs the INSERT.

Summary

  • An entity or model class stands for a table; its properties are columns.
  • TypeORM uses decorators (@Entity, @Column) and repositories; Sequelize uses Model.init and model methods.
  • create() in TypeORM builds an object; save() writes it. In Sequelize Model.create() inserts directly.
  • synchronize and sync() generate DDL from definitions; the database enforces constraints.
  • Choose one naming convention and override the defaults explicitly.

Next: Project Setup and Configuration

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ị.