Decorators reference

Entity decorators

@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:

  1. @Entity("users")
  2. export class User {

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 with false are skipped from schema updates.
  • orderBy - specifies default ordering for entities when using find operations and QueryBuilder.

Example:

  1. @Entity({
  2. name: "users",
  3. engine: "MyISAM",
  4. database: 'example_dev',
  5. schema: 'schema_with_best_tables',
  6. synchronize: false,
  7. orderBy: {
  8. name: "ASC",
  9. id: "DESC"
  10. }
  11. })
  12. export class User {

Learn more about Entities.

@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):

  1. @ViewEntity({
  2. expression: `
  3. SELECT "post"."id" "id", "post"."name" AS "name", "category"."name" AS "categoryName"
  4. FROM "post" "post"
  5. LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
  6. `
  7. })
  8. export class PostCategory {

or an instance of QueryBuilder

  1. @ViewEntity({
  2. expression: (connection: Connection) => connection.createQueryBuilder()
  3. .select("post.id", "id")
  4. .addSelect("post.name", "name")
  5. .addSelect("category.name", "categoryName")
  6. .from(Post, "post")
  7. .leftJoin(Category, "category", "category.id = post.categoryId")
  8. })
  9. export class PostCategory {

Note: parameter binding is not supported due to drivers limitations. Use the literal parameters instead.

  1. @ViewEntity({
  2. expression: (connection: Connection) => connection.createQueryBuilder()
  3. .select("post.id", "id")
  4. .addSelect("post.name", "name")
  5. .addSelect("category.name", "categoryName")
  6. .from(Post, "post")
  7. .leftJoin(Category, "category", "category.id = post.categoryId")
  8. .where("category.name = :name", { name: "Cars" }) // <-- this is wrong
  9. .where("category.name = 'Cars'") // <-- and this is right
  10. })
  11. export class PostCategory {

Learn more about View Entities.

Column decorators

@Column

Marks a property in your entity as a table column.Example:

  1. @Entity("users")
  2. export class User {
  3. @Column({ primary: true })
  4. id: number;
  5. @Column({ type: "varchar", length: 200, unique: true })
  6. firstName: string;
  7. @Column({ nullable: true })
  8. lastName: string;
  9. @Column({ default: false })
  10. isActive: boolean;
  11. }

@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 create varchar(150) typeyou specify column type and length options.
  • width: number - column type’s display width. Used only for MySQL integer types
  • onUpdate: string - ON UPDATE trigger. Used only in MySQL.
  • nullable: boolean - Makes column NULL or NOT NULL in the database.By default column is nullable: 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 is true.
  • insert: boolean - Indicates if column value is set the first time you insert the object. Default value is true.
  • select: boolean - Defines whether or not to hide this column by default when making queries. When set to false, the column data will not show with a standard query. By default column is select: true
  • default: string - Adds database-level column’s DEFAULT value.
  • primary: boolean - Marks column as primary. Same as using @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 maximumnumber 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 - Puts ZEROFILL attribute on to a numeric column. Used only in MySQL.If true, MySQL automatically adds the UNSIGNED attribute to this column.
  • unsigned: boolean - Puts UNSIGNED 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 in enum column type to specify list of allowed enum values.You can specify array of values or specify a enum class.
  • asExpression: string - Generated column expression. Used only in MySQL.
  • generatedType: "VIRTUAL"|"STORED" - Generated column type. Used only in MySQL.
  • hstoreType: "object"|"string" - Return type of HSTORE 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 though Geometry was provided. Used only in PostgreSQL.
  • srid: number - Optional Spatial Reference ID used as a constraint on a spatial column. If not specified, it will default to 0. Standard geographic coordinates (latitude/longitude in the WGS84 datum) correspond to EPSG 4326. Used only in PostgreSQL.

Learn more about entity columns.

@PrimaryColumn

Marks a property in your entity as a table primary column.Same as @Column decorator but sets its primary option to true.Example:

  1. @Entity()
  2. export class User {
  3. @PrimaryColumn()
  4. id: number;
  5. }

Learn more about entity columns.

@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:

  1. @Entity()
  2. export class User {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. }

There are two generation strategies:

  • increment - uses AUTO_INCREMENT / SERIAL / SEQUENCE (depend on database type) to generate incremental number.
  • uuid - generates unique uuid string.
  • rowid - only for CockroachDB. Value is automatically generated using the unique_rowid()function. This produces a 64-bit integer from the current timestamp and ID of the node executing the INSERT or UPSERT operation.

    Note: property with a rowid generation strategy must be a string data type

Default generation strategy is increment, to change it to another strategy, simply pass it as the first argument to decorator:

  1. @Entity()
  2. export class User {
  3. @PrimaryGeneratedColumn("uuid")
  4. id: number;
  5. }

Learn more about entity columns.

@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:

  1. @Entity()
  2. export class User {
  3. @ObjectIdColumn()
  4. id: ObjectID;
  5. }

Learn more about MongoDB.

@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:

  1. @Entity()
  2. export class User {
  3. @CreateDateColumn()
  4. createdDate: Date;
  5. }

@UpdateDateColumn

Special column that is automatically set to the entity’s update timeeach 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.

  1. @Entity()
  2. export class User {
  3. @UpdateDateColumn()
  4. updatedDate: Date;
  5. }

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

  1. @Entity()
  2. export class User {
  3. @VersionColumn()
  4. version: number;
  5. }

@Generated

Marks column to be a generated value. For example:

  1. @Entity()
  2. export class User {
  3. @Column()
  4. @Generated("uuid")
  5. uuid: string;
  6. }

Value will be generated only once, before inserting the entity into the database.

Relation decorators

@OneToOne

One-to-one is a relation where A contains only once 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:

  1. import {Entity, OneToOne, JoinColumn} from "typeorm";
  2. import {Profile} from "./Profile";
  3. @Entity()
  4. export class User {
  5. @OneToOne(type => Profile, profile => profile.user)
  6. @JoinColumn()
  7. profile: Profile;
  8. }

Learn more about one-to-one relations.

@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:

  1. import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "typeorm";
  2. import {User} from "./User";
  3. @Entity()
  4. export class Photo {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. url: string;
  9. @ManyToOne(type => User, user => user.photos)
  10. user: User;
  11. }

Learn more about many-to-one / one-to-many relations.

@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:

  1. import {Entity, PrimaryGeneratedColumn, Column, OneToMany} from "typeorm";
  2. import {Photo} from "./Photo";
  3. @Entity()
  4. export class User {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string;
  9. @OneToMany(type => Photo, photo => photo.user)
  10. photos: Photo[];
  11. }

Learn more about many-to-one / one-to-many relations.

@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:

  1. import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from "typeorm";
  2. import {Category} from "./Category";
  3. @Entity()
  4. export class Question {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. title: string;
  9. @Column()
  10. text: string;
  11. @ManyToMany(type => Category)
  12. @JoinTable()
  13. categories: Category[];
  14. }

Learn more about many-to-many relations.

@JoinColumn

Defines which side of the relation contains the join column with a foreign key andallows you to customize the join column name and referenced column name.Example:

  1. @Entity()
  2. export class Post {
  3. @ManyToOne(type => Category)
  4. @JoinColumn({
  5. name: "cat_id",
  6. referencedColumnName: "name"
  7. })
  8. category: Category;
  9. }

@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 column names inside the junction table and their referenced columns with the @JoinColumn decorator. You can also change the name of the generated “junction” table.Example:

  1. @Entity()
  2. export class Post {
  3. @ManyToMany(type => Category)
  4. @JoinTable({
  5. name: "question_categories",
  6. joinColumn: {
  7. name: "question",
  8. referencedColumnName: "id"
  9. },
  10. inverseJoinColumn: {
  11. name: "category",
  12. referencedColumnName: "id"
  13. }
  14. })
  15. categories: Category[];
  16. }

If the destination table has composite primary keys,then an array of properties must be sent to the @JoinTable decorator.

@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:

  1. @Entity()
  2. export class Post {
  3. @ManyToOne(type => Category)
  4. category: Category;
  5. @RelationId((post: Post) => post.category) // you need to specify target relation
  6. categoryId: number;
  7. }

This functionality works for all kind of relations, including many-to-many:

  1. @Entity()
  2. export class Post {
  3. @ManyToMany(type => Category)
  4. categories: Category[];
  5. @RelationId((post: Post) => post.categories)
  6. categoryIds: number[];
  7. }

Relation id is used only for representation.The underlying relation is not added/removed/changed when chaining the value.

Subscriber and listener decorators

@AfterLoad

You can define a method with any name in entity and mark it with @AfterLoadand TypeORM will call it each time the entityis loaded using QueryBuilder or repository/manager find methods.Example:

  1. @Entity()
  2. export class Post {
  3. @AfterLoad()
  4. updateCounters() {
  5. if (this.likesCount === undefined)
  6. this.likesCount = 0;
  7. }
  8. }

Learn more about listeners.

@BeforeInsert

You can define a method with any name in entity and mark it with @BeforeInsertand TypeORM will call it before the entity is inserted using repository/manager save.Example:

  1. @Entity()
  2. export class Post {
  3. @BeforeInsert()
  4. updateDates() {
  5. this.createdDate = new Date();
  6. }
  7. }

Learn more about listeners.

@AfterInsert

You can define a method with any name in entity and mark it with @AfterInsertand TypeORM will call it after the entity is inserted using repository/manager save.Example:

  1. @Entity()
  2. export class Post {
  3. @AfterInsert()
  4. resetCounters() {
  5. this.counters = 0;
  6. }
  7. }

Learn more about listeners.

@BeforeUpdate

You can define a method with any name in the entity and mark it with @BeforeUpdateand TypeORM will call it before an existing entity is updated using repository/manager save.Example:

  1. @Entity()
  2. export class Post {
  3. @BeforeUpdate()
  4. updateDates() {
  5. this.updatedDate = new Date();
  6. }
  7. }

Learn more about listeners.

@AfterUpdate

You can define a method with any name in the entity and mark it with @AfterUpdateand TypeORM will call it after an existing entity is updated using repository/manager save.Example:

  1. @Entity()
  2. export class Post {
  3. @AfterUpdate()
  4. updateCounters() {
  5. this.counter = 0;
  6. }
  7. }

Learn more about listeners.

@BeforeRemove

You can define a method with any name in the entity and mark it with @BeforeRemoveand TypeORM will call it before a entity is removed using repository/manager remove.Example:

  1. @Entity()
  2. export class Post {
  3. @BeforeRemove()
  4. updateStatus() {
  5. this.status = "removed";
  6. }
  7. }

Learn more about listeners.

@AfterRemove

You can define a method with any name in the entity and mark it with @AfterRemoveand TypeORM will call it after the entity is removed using repository/manager remove.Example:

  1. @Entity()
  2. export class Post {
  3. @AfterRemove()
  4. updateStatus() {
  5. this.status = "removed";
  6. }
  7. }

Learn more about listeners.

@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:

  1. @EventSubscriber()
  2. export class PostSubscriber implements EntitySubscriberInterface<Post> {
  3. /**
  4. * Indicates that this subscriber only listen to Post events.
  5. */
  6. listenTo() {
  7. return Post;
  8. }
  9. /**
  10. * Called before post insertion.
  11. */
  12. beforeInsert(event: InsertEvent<Post>) {
  13. console.log(`BEFORE POST INSERTED: `, event.entity);
  14. }
  15. }

You can implement any method from EntitySubscriberInterface.To listen to any entity, you just omit the listenTo method and use any:

  1. @EventSubscriber()
  2. export class PostSubscriber implements EntitySubscriberInterface {
  3. /**
  4. * Called before entity insertion.
  5. */
  6. beforeInsert(event: InsertEvent<any>) {
  7. console.log(`BEFORE ENTITY INSERTED: `, event.entity);
  8. }
  9. }

Learn more about subscribers.

Other decorators

@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 neededand use it on the entity when a single index on multiple columns is required.Examples:

  1. @Entity()
  2. export class User {
  3. @Index()
  4. @Column()
  5. firstName: string;
  6. @Index({ unique: true })
  7. @Column()
  8. lastName: string;
  9. }
  1. @Entity()
  2. @Index(["firstName", "lastName"])
  3. @Index(["lastName", "middleName"])
  4. @Index(["firstName", "lastName", "middleName"], { unique: true })
  5. export class User {
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. @Column()
  11. middleName: string;
  12. }

Learn more about indices.

@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:

  1. @Entity()
  2. @Unique(["firstName"])
  3. @Unique(["lastName", "middleName"])
  4. @Unique("UQ_NAMES", ["firstName", "lastName", "middleName"])
  5. export class User {
  6. @Column({ name: 'first_name' })
  7. firstName: string;
  8. @Column({ name: 'last_name' })
  9. lastName: string;
  10. @Column({ name: 'middle_name' })
  11. middleName: string;
  12. }

Note: MySQL stores unique constraints as unique indices

@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:

  1. @Entity()
  2. @Check(`"firstName" <> 'John' AND "lastName" <> 'Doe'`)
  3. @Check(`"age" > 18`)
  4. export class User {
  5. @Column()
  6. firstName: string;
  7. @Column()
  8. lastName: string;
  9. @Column()
  10. age: number;
  11. }

Note: MySQL does not support check constraints.

@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:

  1. @Entity()
  2. @Exclusion(`USING gist ("room" WITH =, tsrange("from", "to") WITH &&)`)
  3. export class RoomBooking {
  4. @Column()
  5. room: string;
  6. @Column()
  7. from: Date;
  8. @Column()
  9. to: Date;
  10. }

Note: Only PostgreSQL supports exclusion constraints.

@Transaction, @TransactionManager and @TransactionRepository

@Transaction is used on a method and wraps all its execution into a single database transaction.All database queries must be performed using the @TransactionManager provided manageror with the transaction repositories injected with @TransactionRepository.Examples:

  1. @Transaction()
  2. save(@TransactionManager() manager: EntityManager, user: User) {
  3. return manager.save(user);
  4. }
  1. @Transaction()
  2. save(user: User, @TransactionRepository(User) userRepository: Repository<User>) {
  3. return userRepository.save(user);
  4. }
  1. @Transaction()
  2. save(@QueryParam("name") name: string, @TransactionRepository() userRepository: UserRepository) {
  3. return userRepository.findByName(name);
  4. }

Note: all operations inside a transaction MUST ONLY use the provided instance of EntityManager or injected repositories.Using any other source of queries (global manager, global repositories, etc.) will lead to bugs and errors.

Learn more about transactions.

@EntityRepository

Marks a custom class as an entity repository.Example:

  1. @EntityRepository()
  2. export class UserRepository {
  3. /// ... custom repository methods ...
  4. }

You can obtain any custom created repository using connection.getCustomRepositoryor entityManager.getCustomRepository methods.

Learn more about custom entity repositories.


Note: some decorators (like @Tree, @ChildEntity, etc.) aren’tdocumented in this reference because they are treated as experimental at the moment.Expect to see their documentation in the future.