实体
什么是实体?
实体是一个映射到数据库表的类(使用 MongoDB 时则映射到集合)。你可以通过定义一个新类并用 @Entity() 标记它来创建实体:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
isActive: boolean
}这会创建如下数据库表:
+-------------+--------------+----------------------------+
| user |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| firstName | varchar(255) | |
| lastName | varchar(255) | |
| isActive | boolean | |
+-------------+--------------+----------------------------+基本的实体由列和关系组成。每个实体 必须 有一个主键列(如果使用 MongoDB,则是一个 ObjectId 列)。
每个实体都必须在数据源选项中注册:
import { DataSource } from "typeorm"
import { User } from "./entities/User"
const myDataSource = new DataSource({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
entities: [User],
})或者你可以直接指定包含所有实体的整个目录——它们都会被加载进来:
import { DataSource } from "typeorm"
const dataSource = new DataSource({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
entities: [__dirname + "/entities/**/*{.js,.ts}"],
})如果你想为 User 实体使用另一个表名,可以在 @Entity 中指定:@Entity("my_users")。如果你想为应用中所有数据库表设置一个基础前缀,可以在数据源选项中指定 entityPrefix。
使用实体构造函数时,其参数必须是可选的。因为 ORM 在从数据库加载时会创建实体类的实例,它并不知道你的构造函数参数。
在装饰器参考中进一步了解 @Entity 的参数。
实体列
既然数据库表由列组成,你的实体也必须由列组成。你用 @Column 标记的每个实体类属性都会映射到数据库表的一列。
主键列
每个实体必须至少有一个主键列。主键列有几种类型:
@PrimaryColumn()创建一个可接受任意类型任意值的主键列。你可以指定列类型。如果不指定列类型,它会从属性类型推断出来。下面的示例会创建类型为int的 id,你必须在保存前手动赋值。
import { Entity, PrimaryColumn } from "typeorm"
@Entity()
export class User {
@PrimaryColumn()
id: number
}@PrimaryGeneratedColumn()创建一个主键列,其值会以自增方式自动生成。它会创建带auto-increment/serial/sequence/identity的int列(取决于数据库和所提供的配置)。你不必在保存前手动赋值——值会自动生成。
import { Entity, PrimaryGeneratedColumn } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
}@PrimaryGeneratedColumn("uuid")创建一个主键列,其值会以uuid自动生成。Uuid 是一个唯一的字符串 id。你不必在保存前手动赋值——值会自动生成。
import { Entity, PrimaryGeneratedColumn } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn("uuid")
id: string
}你也可以使用复合主键列:
import { Entity, PrimaryColumn } from "typeorm"
@Entity()
export class User {
@PrimaryColumn()
firstName: string
@PrimaryColumn()
lastName: string
}当你用 save 保存实体时,它总会尝试在数据库中查找具有给定实体 id(或多个 id)的实体。如果找到了 id/ids,就会更新数据库中的这一行。如果没有对应 id/ids 的行,则会插入新行。
要按 id 查找实体,可以使用 manager.findOneBy 或 repository.findOneBy。示例:
// 单主键时按 id 查找一条
const person = await dataSource.manager.findOneBy(Person, { id: 1 })
const person = await dataSource.getRepository(Person).findOneBy({ id: 1 })
// 复合主键时按 id 查找一条
const user = await dataSource.manager.findOneBy(User, {
firstName: "Timber",
lastName: "Saw",
})
const user = await dataSource.getRepository(User).findOneBy({
firstName: "Timber",
lastName: "Saw",
})特殊列
有几种带额外功能的特殊列类型可用:
@CreateDateColumn是一个特殊列,会被自动设置为实体的插入时间。你不需要设置这一列——它会被自动设置。@UpdateDateColumn是一个特殊列,每次你调用 entity manager 或 repository 的save,或在upsert操作中发生更新时,它都会被自动设置为实体的更新时间。你不需要设置这一列——它会被自动设置。@DeleteDateColumn是一个特殊列,每次你调用 entity manager 或 repository 的软删除时,它都会被自动设置为实体的删除时间。你不需要设置这一列——它会被自动设置。如果设置了 @DeleteDateColumn,默认作用域将是"未删除"。@VersionColumn是一个特殊列,每次你调用 entity manager 或 repository 的save,或在upsert操作中发生更新时,它都会被自动设置为实体的版本号(递增数字)。你不需要设置这一列——它会被自动设置。
列类型
TypeORM 支持所有最常用的、数据库所支持的列类型。列类型是数据库专属的——这让你能更灵活地控制数据库结构的呈现方式。
你可以把列类型作为 @Column 的第一个参数指定,也可以放在 @Column 的列选项中,例如:
@Column("int")或者
@Column({ type: "int" })如果你想指定额外的类型参数,可以通过列选项来做。例如:
@Column("varchar", { length: 200 })关于
bigint类型的说明:SQL 数据库中使用的bigint列类型无法放进常规的number类型,因此会把属性映射为string。
enum 列类型
enum 列类型受 postgres 和 mysql 支持。有多种可能的列定义方式:
使用 TypeScript 枚举:
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "enum",
enum: UserRole,
default: UserRole.GHOST,
})
role: UserRole
}注意:支持字符串枚举、数字枚举和异构枚举。
使用包含枚举值的数组:
export type UserRoleType = "admin" | "editor" | "ghost",
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
type: "enum",
enum: ["admin", "editor", "ghost"],
default: "ghost"
})
role: UserRoleType
}simple-array 列类型
有一种特殊列类型叫 simple-array,它可以把原始数组值存进单个字符串列中。所有值用逗号分隔。例如:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column("simple-array")
names: string[]
}const user = new User()
user.names = ["Alexander", "Alex", "Sasha", "Shurik"]它会以 Alexander,Alex,Sasha,Shurik 这个值存进单个数据库列中。当你从数据库加载数据时,names 会被还原成一个名字数组,就像你当初存进去的那样。
注意,你写入的值中 绝不能 包含逗号。
simple-json 列类型
有一种特殊列类型叫 simple-json,它可以存储任何能通过 JSON.stringify 存进数据库的值。当你的数据库没有 json 类型、但又想毫无麻烦地存取对象时,它非常有用。例如:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column("simple-json")
profile: { name: string; nickname: string }
}const user = new User()
user.profile = { name: "John", nickname: "Malkovich" }它会以 {"name":"John","nickname":"Malkovich"} 这个值存进单个数据库列中。当你从数据库加载数据时,会通过 JSON.parse 拿回你的对象 / 数组 / 原始值
simple-enum 列类型
有一种特殊列类型叫 simple-enum,它把枚举值存在单个列中。当同一个实体需要跨多个并非都支持原生枚举的数据库工作时,它很有用,因为 TypeORM 会把它映射成各驱动所支持的形式:有原生枚举类型就用原生枚举类型,否则就用带 CHECK 约束的字符串列。例如:
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "simple-enum",
enum: UserRole,
default: UserRole.GHOST,
})
role: UserRole
}允许的值也可以用数组给出:
export type UserRoleType = "admin" | "editor" | "ghost"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "simple-enum",
enum: ["admin", "editor", "ghost"],
default: "ghost",
})
role: UserRoleType
}注意:支持字符串枚举、数字枚举和异构枚举。加载时数字值会被转换回数字。
值的存储方式取决于驱动:
- MySQL、MariaDB 和 Aurora MySQL 使用原生
enum列类型 - PostgreSQL、CockroachDB 和 Aurora PostgreSQL 使用原生
enum数据库类型 - SQLite(包括
better-sqlite3、sql.js、Cordova、Expo、NativeScript、Capacitor 和 React Native)以及 SQL Server 把值存在字符串列中并加上CHECK约束 - SAP HANA 把值存在
nvarchar列中,不加CHECK约束
Oracle 和 Spanner 不支持 simple-enum。
在 PostgreSQL、CockroachDB 和 SQLite 上,你可以用 array: true 存储枚举值数组:
@Column({
type: "simple-enum",
enum: UserRole,
array: true,
default: [UserRole.EDITOR],
})
roles: UserRole[]在 SQLite 上数组会以逗号分隔列表的形式存储,因此枚举值不能包含逗号。在 SQLite 上不会为数组列创建 CHECK 约束。
带生成值的列
你可以用 @Generated 装饰器创建带生成值的列。例如:
@Entity()
export class User {
@PrimaryColumn()
id: number
@Column()
@Generated("uuid")
uuid: string
}uuid 值会被自动生成并存入数据库。
除了 "uuid" 之外,还有 "increment"、"identity"(仅 Postgres 10+)和 "rowid"(仅 CockroachDB)这几种生成类型,不过这种生成方式在某些数据库平台上存在一些限制(例如有些数据库只能有一个 increment 列,或者有些要求 increment 列必须是主键)。
向量列
向量列在 MariaDB/MySQL、Microsoft SQL Server、PostgreSQL(通过 pgvector 扩展)和 SAP HANA Cloud 上受支持,可用于存储和查询向量嵌入,服务于相似性搜索与机器学习应用。
TypeORM 在各数据库上同时支持 vector 和 halfvec 两种列类型:
vector- 以 4 字节浮点数(单精度)存储向量- MariaDB/MySQL:原生
vector类型 - Microsoft SQL Server:原生
vector类型 - PostgreSQL:
vector类型,通过pgvector扩展提供 - SAP HANA Cloud:
real_vector类型的别名
- MariaDB/MySQL:原生
halfvec- 以 2 字节浮点数(半精度)存储向量,更节省内存- PostgreSQL:
halfvec类型,通过pgvector扩展提供 - SAP HANA Cloud:
half_vector类型的别名
- PostgreSQL:
你可以用 length 选项指定向量维度数:
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
// 未指定维度的向量
@Column("vector")
embedding: number[] | Buffer
// 3 维向量:vector(3)
@Column("vector", { length: 3 })
embedding_3d: number[] | Buffer
// 4 维半精度向量:halfvec(4)(仅在 PostgreSQL 和 SAP HANA 上可用)
@Column("halfvec", { length: 4 })
halfvec_embedding: number[] | Buffer
}注意:
- MariaDB/MySQL:自 MariaDB 11.7 和 MySQL 9 起支持向量
- Microsoft SQL Server:向量类型支持需要 SQL Server 2025(17.x)或更高版本。
- PostgreSQL:向量列需要安装
pgvector扩展。该扩展提供向量数据类型和相似性操作符。- SAP HANA:向量列需要 SAP HANA Cloud(2024Q1+)以及受支持版本的
@sap/hana-client。
空间列
Microsoft SQLServer、MySQL/MariaDB、PostgreSQL/CockroachDB 和 SAP HANA 都支持空间列。TypeORM 对各数据库的支持略有差异,尤其是列名在不同数据库之间并不相同。
MS SQL、MySQL/MariaDB 和 SAP HANA 使用 well-known text (WKT) 格式的几何体,因此几何列应标记为 string 类型。
import { Entity, PrimaryColumn, Column } from "typeorm"
@Entity()
export class Thing {
@PrimaryColumn()
id: number
@Column("point")
point: string
@Column("linestring")
linestring: string
}
...
const thing = new Thing()
thing.point = "POINT(1 1)"
thing.linestring = "LINESTRING(0 0,1 1,2 2)"对于 Postgres/CockroachDB,请参阅 Postgis 数据类型
列选项
列选项为你的实体列定义额外选项。你可以在 @Column 上指定列选项:
@Column({
type: "varchar",
length: 150,
unique: true,
// ...
})
name: string;ColumnOptions 中可用的选项列表:
type: ColumnType- 列类型。上面列出的类型之一。name: string- 数据库表中的列名。默认情况下列名由属性名生成。你可以通过指定自己的名称来修改它。length: number- 列类型的长度。例如如果你想创建varchar(150)类型,就要指定列类型和 length 选项。onUpdate: string-ON UPDATE触发器。仅在 MySQL 中使用。nullable: boolean- 让列在数据库中为NULL或NOT NULL。默认情况下列是nullable: false。update: boolean- 表示列值是否会被 "save" 操作更新。如果为 false,你只能在首次插入对象时写入该值。默认值为true。insert: boolean- 表示列值是否在首次插入对象时被设置。默认值为true。select: boolean- 定义查询时是否默认隐藏该列。设为false时,标准查询不会返回该列数据。默认情况下列是select: truedefault: string- 添加数据库层面的列DEFAULT值。primary: boolean- 把列标记为主键。等同于使用@PrimaryColumn。unique: boolean- 把列标记为唯一列(创建唯一约束)。comment: string- 数据库的列注释。并非所有数据库类型都支持。precision: number- decimal(精确数值)列的精度(仅适用于 decimal 列),即存储数值时的最大位数。用于某些列类型。scale: number- decimal(精确数值)列的标度(仅适用于 decimal 列),表示小数点右侧的位数,且不能大于 precision。用于某些列类型。unsigned: boolean- 给数值列加上UNSIGNED属性。仅在 MySQL 中使用。charset: string- 定义列的字符集。并非所有数据库类型都支持。collation: string- 定义列的排序规则。enum: string[]|AnyEnum- 在enum列类型中用于指定允许的枚举值列表。你可以指定值数组,也可以指定一个枚举类。enumName: string- 定义所用枚举的名称。asExpression: string- 生成列表达式。受 PostgreSQL/CockroachDB、MySQL/MariaDB、Oracle、SAP HANA、Spanner、SQLite 和 SQL Server 支持。generatedType: "VIRTUAL"|"STORED"- 生成列类型。受 PostgreSQL(仅STORED)、CockroachDB、MySQL/MariaDB、Oracle(仅VIRTUAL)、Spanner(仅STORED)、SQLite 和 SQL Server(仅STORED,内部映射为PERSISTED)支持。hstoreType: "object"|"string"-HSTORE列的返回类型。以字符串或对象形式返回值。仅在 Postgres 中使用。array: boolean- 用于 postgres 和 cockroachdb 中可以为数组的列类型(例如 int[])transformer: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType }- 用于把任意类型EntityType的属性编组为数据库所支持的DatabaseType类型。也支持转换器数组,写入时按自然顺序应用,读取时按相反顺序应用。例如[lowercase, encrypt]在写入时会先把字符串转小写再加密,读取时会先解密然后不做处理。utc: boolean- 表示日期值是否应以 UTC 时区而非本地时区存储和读取。仅适用于date列类型。默认值为false(出于向后兼容使用本地时区)。
注意:这些列选项大多是 RDBMS 专属的,在 MongoDB 中不可用。
实体继承
你可以通过使用实体继承来减少代码重复。
例如,你有 Photo、Question、Post 这几个实体:
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
@Column()
size: string
}
@Entity()
export class Question {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
@Column()
answersCount: number
}
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
@Column()
viewCount: number
}如你所见,这些实体都有公共列:id、title、description。为了减少重复并得到更好的抽象,我们可以为它们创建一个名为 Content 的基类:
export abstract class Content {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
}
@Entity()
export class Photo extends Content {
@Column()
size: string
}
@Entity()
export class Question extends Content {
@Column()
answersCount: number
}
@Entity()
export class Post extends Content {
@Column()
viewCount: number
}父实体(父类也可以继续继承其他实体)的所有列(关系、嵌入等)都会被继承,并在最终实体中创建。
树形实体
TypeORM 支持邻接表(Adjacency list)和闭包表(Closure table)两种存储树形结构的模式。
邻接表
邻接表是一种带自引用的简单模型。这种方式的优点是简单,缺点是受连接限制,你无法一次性加载一棵大树。示例:
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
OneToMany,
} from "typeorm"
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column()
description: string
@ManyToOne((type) => Category, (category) => category.children)
parent: Category
@OneToMany((type) => Category, (category) => category.parent)
children: Category[]
}闭包表
闭包表以特殊方式把父子关系存在一张单独的表里。它在读和写两方面都很高效。要进一步了解闭包表,可以看看 Bill Karwin 的这份精彩演示。示例:
import {
Entity,
Tree,
Column,
PrimaryGeneratedColumn,
TreeChildren,
TreeParent,
TreeLevelColumn,
} from "typeorm"
@Entity()
@Tree("closure-table")
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column()
description: string
@TreeChildren()
children: Category[]
@TreeParent()
parent: Category
@TreeLevelColumn()
level: number
}What is an Entity?
Entity is a class that maps to a database table (or collection when using MongoDB). You can create an entity by defining a new class and mark it with @Entity():
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
isActive: boolean
}This will create following database table:
+-------------+--------------+----------------------------+
| user |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| firstName | varchar(255) | |
| lastName | varchar(255) | |
| isActive | boolean | |
+-------------+--------------+----------------------------+Basic entities consist of columns and relations. Each entity MUST have a primary column (or an ObjectId column if are using MongoDB).
Each entity must be registered in your data source options:
import { DataSource } from "typeorm"
import { User } from "./entities/User"
const myDataSource = new DataSource({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
entities: [User],
})Or you can specify the whole directory with all entities inside - and all of them will be loaded:
import { DataSource } from "typeorm"
const dataSource = new DataSource({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
entities: [__dirname + "/entities/**/*{.js,.ts}"],
})If you want to use an alternative table name for the User entity you can specify it in @Entity: @Entity("my_users"). If you want to set a base prefix for all database tables in your application you can specify entityPrefix in data source options.
When using an entity constructor its arguments must be optional. Since ORM creates instances of entity classes when loading from the database, therefore it is not aware of your constructor arguments.
Learn more about parameters @Entity in Decorators reference.
Entity columns
Since database tables consist of columns your entities must consist of columns too. Each entity class property you marked with @Column will be mapped to a database table column.
Primary columns
Each entity must have at least one primary column. There are several types of primary columns:
@PrimaryColumn()creates a primary column which takes any value of any type. You can specify the column type. If you don't specify a column type it will be inferred from the property type. The example below will create id withintas type which you must manually assign before save.
import { Entity, PrimaryColumn } from "typeorm"
@Entity()
export class User {
@PrimaryColumn()
id: number
}@PrimaryGeneratedColumn()creates a primary column which value will be automatically generated with an auto-increment value. It will createintcolumn withauto-increment/serial/sequence/identity(depend on the database and configuration provided). You don't have to manually assign its value before save - value will be automatically generated.
import { Entity, PrimaryGeneratedColumn } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
}@PrimaryGeneratedColumn("uuid")creates a primary column which value will be automatically generated withuuid. Uuid is a unique string id. You don't have to manually assign its value before save - value will be automatically generated.
import { Entity, PrimaryGeneratedColumn } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn("uuid")
id: string
}You can have composite primary columns as well:
import { Entity, PrimaryColumn } from "typeorm"
@Entity()
export class User {
@PrimaryColumn()
firstName: string
@PrimaryColumn()
lastName: string
}When you save entities using save it always tries to find an entity in the database with the given entity id (or ids). If id/ids are found then it will update this row in the database. If there is no row with the id/ids, a new row will be inserted.
To find an entity by id you can use manager.findOneBy or repository.findOneBy. Example:
// find one by id with single primary key
const person = await dataSource.manager.findOneBy(Person, { id: 1 })
const person = await dataSource.getRepository(Person).findOneBy({ id: 1 })
// find one by id with composite primary keys
const user = await dataSource.manager.findOneBy(User, {
firstName: "Timber",
lastName: "Saw",
})
const user = await dataSource.getRepository(User).findOneBy({
firstName: "Timber",
lastName: "Saw",
})Special columns
There are several special column types with additional functionality available:
@CreateDateColumnis a special column that is automatically set to the entity's insertion date. You don't need to set this column - it will be automatically set.@UpdateDateColumnis a special column that is automatically set to the entity's update time each time you callsaveof entity manager or repository, or duringupsertoperations when an update occurs. You don't need to set this column - it will be automatically set.@DeleteDateColumnis a special column that is automatically set to the entity's delete time each time you call soft-delete of entity manager or repository. You don't need to set this column - it will be automatically set. If the @DeleteDateColumn is set, the default scope will be "non-deleted".@VersionColumnis a special column that is automatically set to the version of the entity (incremental number) each time you callsaveof entity manager or repository, or duringupsertoperations when an update occurs. You don't need to set this column - it will be automatically set.
Column types
TypeORM supports all of the most commonly used database-supported column types. Column types are database-type specific - this provides more flexibility on how your database schema will look like.
You can specify column type as first parameter of @Column or in the column options of @Column, for example:
@Column("int")or
@Column({ type: "int" })If you want to specify additional type parameters you can do it via column options. For example:
@Column("varchar", { length: 200 })Note about
biginttype:bigintcolumn type, used in SQL databases, doesn't fit into the regularnumbertype and maps property to astringinstead.
enum column type
enum column type is supported by postgres and mysql. There are various possible column definitions:
Using typescript enums:
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "enum",
enum: UserRole,
default: UserRole.GHOST,
})
role: UserRole
}Note: String, numeric and heterogeneous enums are supported.
Using array with enum values:
export type UserRoleType = "admin" | "editor" | "ghost",
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
type: "enum",
enum: ["admin", "editor", "ghost"],
default: "ghost"
})
role: UserRoleType
}simple-array column type
There is a special column type called simple-array which can store primitive array values in a single string column. All values are separated by a comma. For example:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column("simple-array")
names: string[]
}const user = new User()
user.names = ["Alexander", "Alex", "Sasha", "Shurik"]Will be stored in a single database column as Alexander,Alex,Sasha,Shurik value. When you'll load data from the database, the names will be returned as an array of names, just like you stored them.
Note you MUST NOT have any comma in values you write.
simple-json column type
There is a special column type called simple-json which can store any values which can be stored in database via JSON.stringify. Very useful when you do not have json type in your database and you want to store and load object without any hassle. For example:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column("simple-json")
profile: { name: string; nickname: string }
}const user = new User()
user.profile = { name: "John", nickname: "Malkovich" }Will be stored in a single database column as {"name":"John","nickname":"Malkovich"} value. When you'll load data from the database, you will have your object/array/primitive back via JSON.parse
simple-enum column type
There is a special column type called simple-enum which stores enum values in a single column. It is useful when the same entity has to work across databases that do not all support native enums, because TypeORM maps it to whatever each driver supports: a native enum type where one exists, and a string column with a CHECK constraint elsewhere. For example:
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "simple-enum",
enum: UserRole,
default: UserRole.GHOST,
})
role: UserRole
}The allowed values can also be given as an array:
export type UserRoleType = "admin" | "editor" | "ghost"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "simple-enum",
enum: ["admin", "editor", "ghost"],
default: "ghost",
})
role: UserRoleType
}Note: String, numeric and heterogeneous enums are supported. Numeric values are converted back to numbers when loading.
How the values are stored depends on the driver:
- MySQL, MariaDB and Aurora MySQL use the native
enumcolumn type - PostgreSQL, CockroachDB and Aurora PostgreSQL use a native
enumdatabase type - SQLite (including
better-sqlite3,sql.js, Cordova, Expo, NativeScript, Capacitor and React Native) and SQL Server store the values in a string column and add aCHECKconstraint - SAP HANA stores the values in an
nvarcharcolumn without aCHECKconstraint
simple-enum is not supported by Oracle or Spanner.
On PostgreSQL, CockroachDB and SQLite you can store an array of enum values with array: true:
@Column({
type: "simple-enum",
enum: UserRole,
array: true,
default: [UserRole.EDITOR],
})
roles: UserRole[]Arrays are stored as a comma-separated list on SQLite, so enum values must not contain a comma. No CHECK constraint is created for array columns on SQLite.
Columns with generated values
You can create column with generated value using @Generated decorator. For example:
@Entity()
export class User {
@PrimaryColumn()
id: number
@Column()
@Generated("uuid")
uuid: string
}uuid value will be automatically generated and stored into the database.
Besides "uuid" there is also "increment", "identity" (Postgres 10+ only) and "rowid" (CockroachDB only) generated types, however there are some limitations on some database platforms with this type of generation (for example some databases can only have one increment column, or some of them require increment to be a primary key).
Vector columns
Vector columns are supported on MariaDB/MySQL, Microsoft SQL Server, PostgreSQL (via pgvector extension) and SAP HANA Cloud, enabling storing and querying vector embeddings for similarity search and machine learning applications.
TypeORM supports both vector and halfvec column types across databases:
vector- stores vectors as 4-byte floats (single precision)- MariaDB/MySQL: native
vectortype - Microsoft SQL Server: native
vectortype - PostgreSQL:
vectortype, available viapgvectorextension - SAP HANA Cloud: alias for
real_vectortype
- MariaDB/MySQL: native
halfvec- stores vectors as 2-byte floats (half precision) for memory efficiency- PostgreSQL:
halfvectype, available viapgvectorextension - SAP HANA Cloud: alias for
half_vectortype
- PostgreSQL:
You can specify the number of vector dimensions using the length option:
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
// Vector without specified dimensions
@Column("vector")
embedding: number[] | Buffer
// Vector with 3 dimensions: vector(3)
@Column("vector", { length: 3 })
embedding_3d: number[] | Buffer
// Half-precision vector with 4 dimensions: halfvec(4) (works on PostgreSQL and SAP HANA only)
@Column("halfvec", { length: 4 })
halfvec_embedding: number[] | Buffer
}Note:
- MariaDB/MySQL: Vectors are supported since MariaDB 11.7 and MySQL 9
- Microsoft SQL Server: Vector type support requires SQL Server 2025 (17.x) or newer.
- PostgreSQL: Vector columns require the
pgvectorextension to be installed. The extension provides the vector data types and similarity operators.- SAP HANA: Vector columns require SAP HANA Cloud (2024Q1+) and a supported version of
@sap/hana-client.
Spatial columns
Microsoft SQLServer, MySQL/MariaDB, PostgreSQL/CockroachDB and SAP HANA all support spatial columns. TypeORM's support for each varies slightly between databases, particularly as the column names vary between databases.
MS SQL, MySQL/MariaDB and SAP HANA use geometries in the well-known text (WKT) format, so geometry columns should be tagged with the string type.
import { Entity, PrimaryColumn, Column } from "typeorm"
@Entity()
export class Thing {
@PrimaryColumn()
id: number
@Column("point")
point: string
@Column("linestring")
linestring: string
}
...
const thing = new Thing()
thing.point = "POINT(1 1)"
thing.linestring = "LINESTRING(0 0,1 1,2 2)"For Postgres/CockroachDB, see Postgis Data Types
Column options
Column options defines additional options for your entity columns. You can specify column options on @Column:
@Column({
type: "varchar",
length: 150,
unique: true,
// ...
})
name: string;List of available options in ColumnOptions:
type: ColumnType- Column type. One of the type listed above.name: string- Column name in the database table. By default the column name is generated from the name of the property. You can change it by specifying your own name.length: number- Column type's length. For example if you want to createvarchar(150)type you specify column type and length options.onUpdate: string-ON UPDATEtrigger. Used only in MySQL.nullable: boolean- Makes columnNULLorNOT NULLin the database. By default column isnullable: false.update: boolean- Indicates if column value is updated by "save" operation. If false, you'll be able to write this value only when you first time insert the object. Default value istrue.insert: boolean- Indicates if column value is set the first time you insert the object. Default value istrue.select: boolean- Defines whether or not to hide this column by default when making queries. When set tofalse, the column data will not show with a standard query. By default column isselect: truedefault: string- Adds database-level column'sDEFAULTvalue.primary: boolean- Marks column as primary. Same if you use@PrimaryColumn.unique: boolean- Marks column as unique column (creates unique constraint).comment: string- Database's column comment. Not supported by all database types.precision: number- The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values. Used in some column types.scale: number- The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision. Used in some column types.unsigned: boolean- PutsUNSIGNEDattribute on to a numeric column. Used only in MySQL.charset: string- Defines a column character set. Not supported by all database types.collation: string- Defines a column collation.enum: string[]|AnyEnum- Used inenumcolumn type to specify list of allowed enum values. You can specify array of values or specify a enum class.enumName: string- Defines the name for the used enum.asExpression: string- Generated column expression. Supported by PostgreSQL/CockroachDB, MySQL/MariaDB, Oracle, SAP HANA, Spanner, SQLite, and SQL Server.generatedType: "VIRTUAL"|"STORED"- Generated column type. Supported by PostgreSQL (STOREDonly), CockroachDB, MySQL/MariaDB, Oracle (VIRTUALonly), Spanner (STOREDonly), SQLite, and SQL Server (STOREDonly, internally mapped toPERSISTED).hstoreType: "object"|"string"- Return type ofHSTOREcolumn. Returns value as string or as object. Used only in Postgres.array: boolean- Used for postgres and cockroachdb column types which can be array (for example int[])transformer: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType }- Used to marshal properties of arbitrary typeEntityTypeinto a typeDatabaseTypesupported by the database. Array of transformers are also supported and will be applied in natural order when writing, and in reverse order when reading. e.g.[lowercase, encrypt]will first lowercase the string then encrypt it when writing, and will decrypt then do nothing when reading.utc: boolean- Indicates if date values should be stored and retrieved in UTC timezone instead of local timezone. Only applies todatecolumn type. Default value isfalse(uses local timezone for backward compatibility).
Note: most of those column options are RDBMS-specific and aren't available in MongoDB.
Entity inheritance
You can reduce duplication in your code by using entity inheritance.
For example, you have Photo, Question, Post entities:
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
@Column()
size: string
}
@Entity()
export class Question {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
@Column()
answersCount: number
}
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
@Column()
viewCount: number
}As you can see all those entities have common columns: id, title, description. To reduce duplication and produce a better abstraction we can create a base class called Content for them:
export abstract class Content {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
}
@Entity()
export class Photo extends Content {
@Column()
size: string
}
@Entity()
export class Question extends Content {
@Column()
answersCount: number
}
@Entity()
export class Post extends Content {
@Column()
viewCount: number
}All columns (relations, embeds, etc.) from parent entities (parent can extend other entity as well) will be inherited and created in final entities.
Tree entities
TypeORM supports the Adjacency list and Closure table patterns of storing tree structures.
Adjacency list
Adjacency list is a simple model with self-referencing. Benefit of this approach is simplicity, drawback is you can't load a big tree at once because of join limitations. Example:
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
OneToMany,
} from "typeorm"
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column()
description: string
@ManyToOne((type) => Category, (category) => category.children)
parent: Category
@OneToMany((type) => Category, (category) => category.parent)
children: Category[]
}Closure table
A closure table stores relations between parent and child in a separate table in a special way. It's efficient in both reads and writes. To learn more about closure table take a look at this awesome presentation by Bill Karwin. Example:
import {
Entity,
Tree,
Column,
PrimaryGeneratedColumn,
TreeChildren,
TreeParent,
TreeLevelColumn,
} from "typeorm"
@Entity()
@Tree("closure-table")
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column()
description: string
@TreeChildren()
children: Category[]
@TreeParent()
parent: Category
@TreeLevelColumn()
level: number
}