Decorator reference
Entity decorators
@Entity
@Entity
Marks your model as an entity. Entity is a class which is transformed into a database table. You can specify the table name in the entity:
This code will create a database table named "users".
You can also specify some additional entity options:
name
- table name. If not specified, then table name is generated from entity class name.database
- database name in selected DB server.schema
- schema name.engine
- database engine to be set during table creation (works only in some databases).synchronize
- entities marked withfalse
are skipped from schema updates.orderBy
- specifies default ordering for entities when usingfind
operations andQueryBuilder
.
Example:
Learn more about Entities.
@ViewEntity
@ViewEntity
View entity is a class that maps to a database view.
@ViewEntity()
accepts following options:
name
- view name. If not specified, then view name is generated from entity class name.database
- database name in selected DB server.schema
- schema name.expression
- view definition. Required parameter.
expression
can be string with properly escaped columns and tables, depend on database used (postgres in example):
or an instance of QueryBuilder
Note: parameter binding is not supported due to drivers limitations. Use the literal parameters instead.
Learn more about View Entities.
Column decorators
@Column
@Column
Marks a property in your entity as a table column. Example:
@Column
accept several options you can use:
type: ColumnType
- Column type. One of the supported column types.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: string|number
- Column type's length. For example, if you want to createvarchar(150)
type you specify column type and length options.width: number
- column type's display width. Used only for MySQL integer typesonUpdate: string
-ON UPDATE
trigger. Used only in MySQL.nullable: boolean
- determines whether the column can becomeNULL
or always has to beNOT NULL
. 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: true
default: string
- Adds database-level column'sDEFAULT
value.primary: boolean
- Marks column as primary. Same as using@PrimaryColumn
.unique: boolean
- Marks column as unique column (creates unique constraint). Default value is false.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.zerofill: boolean
- PutsZEROFILL
attribute on to a numeric column. Used only in MySQL. Iftrue
, MySQL automatically adds theUNSIGNED
attribute to this column.unsigned: boolean
- PutsUNSIGNED
attribute 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 inenum
column type to specify list of allowed enum values. You can specify array of values or specify a enum class.enumName: string
- A name for generated enum type. If not specified, TypeORM will generate a enum type from entity and column names - so it's necessary if you intend to use the same enum type in different tables.primaryKeyConstraintName: string
- A name for the primary key constraint. If not specified, then constraint name is generated from the table name and the names of the involved columns.generatedType: "VIRTUAL"|"STORED"
- Generated column type. Used only in MySQL and Postgres (Only "STORED").hstoreType: "object"|"string"
- Return type ofHSTORE
column. 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: ValueTransformer|ValueTransformer[]
- Specifies a value transformer (or array of value transformers) that is to be used to (un)marshal this column when reading or writing to the database. In case of an array, the value transformers will be applied in the natural order from entityValue to databaseValue, and in reverse order from databaseValue to entityValue.spatialFeatureType: string
- Optional feature type (Point
,Polygon
,LineString
,Geometry
) used as a constraint on a spatial column. If not specified, it will behave as thoughGeometry
was provided. Used only in PostgreSQL and CockroachDB.srid: number
- Optional Spatial Reference ID used as a constraint on a spatial column. If not specified, it will default to0
. Standard geographic coordinates (latitude/longitude in the WGS84 datum) correspond to EPSG 4326. Used only in PostgreSQL and CockroachDB.
Learn more about entity columns.
@PrimaryColumn
@PrimaryColumn
Marks a property in your entity as a table primary column. Same as @Column
decorator but sets its primary
option to true.
Example:
@PrimaryColumn()
supports custom primary key constraint name:
Note: when using
primaryKeyConstraintName
with multiple primary keys, the constraint name must be the same for all primary columns.
Learn more about entity columns.
@PrimaryGeneratedColumn
@PrimaryGeneratedColumn
Marks a property in your entity as a table-generated primary column. Column it creates is primary and its value is auto-generated. Example:
@PrimaryGeneratedColumn()
supports custom primary key constraint name:
There are four generation strategies:
increment
- uses AUTO_INCREMENT / SERIAL / SEQUENCE (depend on database type) to generate incremental number.identity
- only for PostgreSQL 10+. Postgres versions above 10 support the SQL-Compliant IDENTITY column. When marking the generation strategy asidentity
the column will be produced usingGENERATED [ALWAYS|BY DEFAULT] AS IDENTITY
uuid
- generates uniqueuuid
string.rowid
- only for CockroachDB. Value is automatically generated using theunique_rowid()
function. This produces a 64-bit integer from the current timestamp and ID of the node executing theINSERT
orUPSERT
operation.Note: property with a
rowid
generation strategy must be astring
data type
Default generation strategy is increment
, to change it to another strategy, simply pass it as the first argument to decorator:
Learn more about entity columns.
@ObjectIdColumn
@ObjectIdColumn
Marks a property in your entity as ObjectId. This decorator is only used in MongoDB. Every entity in MongoDB must have a ObjectId column. Example:
Learn more about MongoDB.
@CreateDateColumn
@CreateDateColumn
Special column that is automatically set to the entity's insertion time. You don't need to write a value into this column - it will be automatically set. Example:
@UpdateDateColumn
@UpdateDateColumn
Special column that is automatically set to the entity's update time each time you call save
from entity manager or repository. You don't need to write a value into this column - it will be automatically set.
@DeleteDateColumn
@DeleteDateColumn
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.
TypeORM's own soft delete functionality utilizes global scopes to only pull "non-deleted" entities from the database.
If the @DeleteDateColumn is set, the default scope will be "non-deleted".
@VersionColumn
@VersionColumn
Special column that is automatically set to the entity's version (incremental number) each time you call save
from entity manager or repository. You don't need to write a value into this column - it will be automatically set.
@Generated
@Generated
Marks column to be a generated value. For example:
Value will be generated only once, before inserting the entity into the database.
@VirtualColumn
@VirtualColumn
Special column that is never saved to the database and thus acts as a readonly property. Each time you call find
or findOne
from the entity manager, the value is recalculated based on the query function that was provided in the VirtualColumn Decorator. The alias argument passed to the query references the exact entity alias of the generated query behind the scenes.
Relation decorators
@OneToOne
@OneToOne
One-to-one is a relation where A contains only one instance of B, and B contains only one instance of A. Let's take for example User
and Profile
entities. User can have only a single profile, and a single profile is owned by only a single user. Example:
Learn more about one-to-one relations.
@ManyToOne
@ManyToOne
Many-to-one / one-to-many is a relation where A contains multiple instances of B, but B contains only one instance of A. Let's take for example User
and Photo
entities. User can have multiple photos, but each photo is owned by only one single user. Example:
Learn more about many-to-one / one-to-many relations.
@OneToMany
@OneToMany
Many-to-one / one-to-many is a relation where A contains multiple instances of B, but B contains only one instance of A. Let's take for example User
and Photo
entities. User can have multiple photos, but each photo is owned by only a single user. Example:
Learn more about many-to-one / one-to-many relations.
@ManyToMany
@ManyToMany
Many-to-many is a relation where A contains multiple instances of B, and B contain multiple instances of A. Let's take for example Question
and Category
entities. Question can have multiple categories, and each category can have multiple questions. Example:
Learn more about many-to-many relations.
@JoinColumn
@JoinColumn
Defines which side of the relation contains the join column with a foreign key and allows you to customize the join column name, referenced column name and foreign key name. Example:
@JoinTable
@JoinTable
Used for many-to-many
relations and describes join columns of the "junction" table. Junction table is a special, separate table created automatically by TypeORM with columns referenced to the related entities. You can change the name of the generated "junction" table, the column names inside the junction table, their referenced columns with the joinColumn
- and inverseJoinColumn
attributes, and the created foreign keys names. You can also set parameter synchronize
to false to skip schema update(same way as in @Entity)
Example:
If the destination table has composite primary keys, then an array of properties must be sent to the @JoinTable
decorator.
@RelationId
@RelationId
Loads id (or ids) of specific relations into properties. For example, if you have a many-to-one category
in your Post
entity, you can have a new category id by marking a new property with @RelationId
. Example:
This functionality works for all kind of relations, including many-to-many
:
Relation id is used only for representation. The underlying relation is not added/removed/changed when chaining the value.
Subscriber and listener decorators
@AfterLoad
@AfterLoad
You can define a method with any name in entity and mark it with @AfterLoad
and TypeORM will call it each time the entity is loaded using QueryBuilder
or repository/manager find methods. Example:
Learn more about listeners.
@BeforeInsert
@BeforeInsert
You can define a method with any name in entity and mark it with @BeforeInsert
and TypeORM will call it before the entity is inserted using repository/manager save
. Example:
Learn more about listeners.
@AfterInsert
@AfterInsert
You can define a method with any name in entity and mark it with @AfterInsert
and TypeORM will call it after the entity is inserted using repository/manager save
. Example:
Learn more about listeners.
@BeforeUpdate
@BeforeUpdate
You can define a method with any name in the entity and mark it with @BeforeUpdate
and TypeORM will call it before an existing entity is updated using repository/manager save
. Example:
Learn more about listeners.
@AfterUpdate
@AfterUpdate
You can define a method with any name in the entity and mark it with @AfterUpdate
and TypeORM will call it after an existing entity is updated using repository/manager save
. Example:
Learn more about listeners.
@BeforeRemove
@BeforeRemove
You can define a method with any name in the entity and mark it with @BeforeRemove
and TypeORM will call it before a entity is removed using repository/manager remove
. Example:
Learn more about listeners.
@AfterRemove
@AfterRemove
You can define a method with any name in the entity and mark it with @AfterRemove
and TypeORM will call it after the entity is removed using repository/manager remove
. Example:
Learn more about listeners.
@BeforeSoftRemove
@BeforeSoftRemove
You can define a method with any name in the entity and mark it with @BeforeSoftRemove
and TypeORM will call it before a entity is soft removed using repository/manager softRemove
. Example:
Learn more about listeners.
@AfterSoftRemove
@AfterSoftRemove
You can define a method with any name in the entity and mark it with @AfterSoftRemove
and TypeORM will call it after the entity is soft removed using repository/manager softRemove
. Example:
Learn more about listeners.
@BeforeRecover
@BeforeRecover
You can define a method with any name in the entity and mark it with @BeforeRecover
and TypeORM will call it before a entity is recovered using repository/manager recover
. Example:
Learn more about listeners.
@AfterRecover
@AfterRecover
You can define a method with any name in the entity and mark it with @AfterRecover
and TypeORM will call it after the entity is recovered using repository/manager recover
. Example:
Learn more about listeners.
@EventSubscriber
@EventSubscriber
Marks a class as an event subscriber which can listen to specific entity events or any entity's events. Events are fired using QueryBuilder
and repository/manager methods. Example:
You can implement any method from EntitySubscriberInterface
. To listen to any entity, you just omit the listenTo
method and use any
:
Learn more about subscribers.
Other decorators
@Index
@Index
This decorator allows you to create a database index for a specific column or columns. It also allows you to mark column or columns to be unique. This decorator can be applied to columns or an entity itself. Use it on a column when an index on a single column is needed and use it on the entity when a single index on multiple columns is required. Examples:
Learn more about indices.
@Unique
@Unique
This decorator allows you to create a database unique constraint for a specific column or columns. This decorator can be applied only to an entity itself. You must specify the entity field names (not database column names) as arguments.
Examples:
Note: MySQL stores unique constraints as unique indices
@Check
@Check
This decorator allows you to create a database check constraint for a specific column or columns. This decorator can be applied only to an entity itself.
Examples:
Note: MySQL does not support check constraints.
@Exclusion
@Exclusion
This decorator allows you to create a database exclusion constraint for a specific column or columns. This decorator can be applied only to an entity itself.
Examples:
Note: Only PostgreSQL supports exclusion constraints.
Last updated