Entities

What is 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():

  1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. @Column()
  11. isActive: boolean;
  12. }

This will create following database table:

  1. +-------------+--------------+----------------------------+
  2. | user |
  3. +-------------+--------------+----------------------------+
  4. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  5. | firstName | varchar(255) | |
  6. | lastName | varchar(255) | |
  7. | isActive | boolean | |
  8. +-------------+--------------+----------------------------+

Basic entities consist of columns and relations.Each entity MUST have a primary column (or ObjectId column if are using MongoDB).

Each entity must be registered in your connection options:

  1. import {createConnection, Connection} from "typeorm";
  2. import {User} from "./entity/User";
  3. const connection: Connection = await createConnection({
  4. type: "mysql",
  5. host: "localhost",
  6. port: 3306,
  7. username: "test",
  8. password: "test",
  9. database: "test",
  10. entities: [User]
  11. });

Or you can specify the whole directory with all entities inside - and all of them will be loaded:

  1. import {createConnection, Connection} from "typeorm";
  2. const connection: Connection = await createConnection({
  3. type: "mysql",
  4. host: "localhost",
  5. port: 3306,
  6. username: "test",
  7. password: "test",
  8. database: "test",
  9. entities: ["entity/*.js"]
  10. });

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 connection 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 table 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 with int as type which you must manually assign before save.
  1. import {Entity, PrimaryColumn} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryColumn()
  5. id: number;
  6. }
  • @PrimaryGeneratedColumn() creates a primary column which value will be automatically generated with an auto-increment value. It will create int column with auto-increment/serial/sequence (depend on the database). You don’t have to manually assign its value before save - value will be automatically generated.
  1. import {Entity, PrimaryGeneratedColumn} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. }
  • @PrimaryGeneratedColumn("uuid") creates a primary column which value will be automatically generated with uuid. Uuid is a unique string id. You don’t have to manually assign its value before save - value will be automatically generated.
  1. import {Entity, PrimaryGeneratedColumn} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn("uuid")
  5. id: string;
  6. }

You can have composite primary columns as well:

  1. import {Entity, PrimaryColumn} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryColumn()
  5. firstName: string;
  6. @PrimaryColumn()
  7. lastName: string;
  8. }

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.findOne or repository.findOne. Example:

  1. // find one by id with single primary key
  2. const person = await connection.manager.findOne(Person, 1);
  3. const person = await connection.getRepository(Person).findOne(1);
  4. // find one by id with composite primary keys
  5. const user = await connection.manager.findOne(User, { firstName: "Timber", lastName: "Saw" });
  6. const user = await connection.getRepository(User).findOne({ firstName: "Timber", lastName: "Saw" });

Special columns

There are several special column types with additional functionality available:

  • @CreateDateColumn is 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.

  • @UpdateDateColumn is a special column that is automatically set to the entity’s update timeeach time you call save of entity manager or repository.You don’t need to set this column - it will be automatically set.

  • @VersionColumn is a special column that is automatically set to the version of the entity (incremental number)each time you call save of entity manager or repository.You don’t need to set this column - it will be automatically set.

Spatial columns

MS SQL, MySQL / MariaDB, and PostgreSQL all support spatial columns. TypeORM’ssupport for each varies slightly between databases, particularly as the columnnames vary between databases.

MS SQL and MySQL / MariaDB’s TypeORM support exposes (and expects) geometries tobe provided as well-known text(WKT), so geometry columnsshould be tagged with the string type.

TypeORM’s PostgreSQL support uses GeoJSON as aninterchange format, so geometry columns should be tagged either as object orGeometry (or subclasses, e.g. Point) after importing geojsontypes.

TypeORM tries to do the right thing, but it’s not always possible to determinewhen a value being inserted or the result of a PostGIS function should betreated as a geometry. As a result, you may find yourself writing code similarto the following, where values are converted into PostGIS geometrys fromGeoJSON and into GeoJSON as json:

  1. const origin = {
  2. type: "Point",
  3. coordinates: [0, 0]
  4. };
  5. await getManager()
  6. .createQueryBuilder(Thing, "thing")
  7. // convert stringified GeoJSON into a geometry with an SRID that matches the
  8. // table specification
  9. .where("ST_Distance(geom, ST_SetSRID(ST_GeomFromGeoJSON(:origin), ST_SRID(geom))) > 0")
  10. .orderBy({
  11. "ST_Distance(geom, ST_SetSRID(ST_GeomFromGeoJSON(:origin), ST_SRID(geom)))": {
  12. order: "ASC"
  13. }
  14. })
  15. .setParameters({
  16. // stringify GeoJSON
  17. origin: JSON.stringify(origin)
  18. })
  19. .getMany();
  20. await getManager()
  21. .createQueryBuilder(Thing, "thing")
  22. // convert geometry result into GeoJSON, treated as JSON (so that TypeORM
  23. // will know to deserialize it)
  24. .select("ST_AsGeoJSON(ST_Buffer(geom, 0.1))::json geom")
  25. .from("thing")
  26. .getMany();

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 @Columnor in the column options of @Column, for example:

  1. @Column("int")

or

  1. @Column({ type: "int" })

If you want to specify additional type parameters you can do it via column options.For example:

  1. @Column("varchar", { length: 200 })

or

  1. @Column({ type: "int", width: 200 })

Column types for mysql / mariadb

bit, int, integer, tinyint, smallint, mediumint, bigint, float, double,double precision, dec, decimal, numeric, fixed, bool, boolean, date, datetime,timestamp, time, year, char, nchar, national char, varchar, nvarchar, national varchar,text, tinytext, mediumtext, blob, longtext, tinyblob, mediumblob, longblob, enum, set,json, binary, varbinary, geometry, point, linestring, polygon, multipoint, multilinestring,multipolygon, geometrycollection

Column types for postgres

int, int2, int4, int8, smallint, integer, bigint, decimal, numeric, real,float, float4, float8, double precision, money, character varying, varchar,character, char, text, citext, hstore, bytea, bit, varbit, bit varying,timetz, timestamptz, timestamp, timestamp without time zone, timestamp with time zone,date, time, time without time zone, time with time zone, interval, bool, boolean,enum, point, line, lseg, box, path, polygon, circle, cidr, inet, macaddr,tsvector, tsquery, uuid, xml, json, jsonb, int4range, int8range, numrange,tsrange, tstzrange, daterange, geometry, geography, cube

Column types for cockroachdb

array, bool, boolean, bytes, bytea, blob, date, numeric, decimal, dec, float,float4, float8, double precision, real, inet, int, integer, int2, int8, int64,smallint, bigint, interval, string, character varying, character, char, char varying,varchar, text, time, time without time zone, timestamp, timestamptz, timestamp without time zone,timestamp with time zone, json, jsonb, uuid

Note: CockroachDB returns all numeric data types as string. However if you omit column type and define your property as number ORM will parseInt string into number.

Column types for sqlite / cordova / react-native / expo

int, int2, int8, integer, tinyint, smallint, mediumint, bigint, decimal,numeric, float, double, real, double precision, datetime, varying character,character, native character, varchar, nchar, nvarchar2, unsigned big int, boolean,blob, text, clob, date

Column types for mssql

int, bigint, bit, decimal, money, numeric, smallint, smallmoney, tinyint, float,real, date, datetime2, datetime, datetimeoffset, smalldatetime, time, char, varchar,text, nchar, nvarchar, ntext, binary, image, varbinary, hierarchyid, sql_variant,timestamp, uniqueidentifier, xml, geometry, geography, rowversion

Column types for oracle

char, nchar, nvarchar2, varchar2, long, raw, long raw, number, numeric, float, dec,decimal, integer, int, smallint, real, double precision, date, timestamp, timestamp with time zone,timestamp with local time zone, interval year to month, interval day to second, bfile, blob, clob,nclob, rowid, urowid

enum column type

enum column type is supported by postgres and mysql. There are various possible column definitions:

Using typescript enums:

  1. export enum UserRole {
  2. ADMIN = "admin",
  3. EDITOR = "editor",
  4. GHOST = "ghost"
  5. }
  6. @Entity()
  7. export class User {
  8. @PrimaryGeneratedColumn()
  9. id: number;
  10. @Column({
  11. type: "enum",
  12. enum: UserRole,
  13. default: UserRole.GHOST
  14. })
  15. role: UserRole
  16. }

Note: String, numeric and heterogeneous enums are supported.

Using array with enum values:

  1. export type UserRoleType = "admin" | "editor" | "ghost",
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column({
  7. type: "enum",
  8. enum: ["admin", "editor", "ghost"],
  9. default: "ghost"
  10. })
  11. role: UserRoleType
  12. }

set column type

set column type is supported by mariadb and mysql. There are various possible column definitions:

Using typescript enums:

  1. export enum UserRole {
  2. ADMIN = "admin",
  3. EDITOR = "editor",
  4. GHOST = "ghost"
  5. }
  6. @Entity()
  7. export class User {
  8. @PrimaryGeneratedColumn()
  9. id: number;
  10. @Column({
  11. type: "set",
  12. enum: UserRole,
  13. default: [UserRole.GHOST, UserRole.EDITOR]
  14. })
  15. roles: UserRole[]
  16. }

Using array with set values:

  1. export type UserRoleType = "admin" | "editor" | "ghost",
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column({
  7. type: "set",
  8. enum: ["admin", "editor", "ghost"],
  9. default: ["ghost", "editor"]
  10. })
  11. roles: UserRoleType[]
  12. }

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:

  1. @Entity()
  2. export class User {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column("simple-array")
  6. names: string[];
  7. }
  1. const user = new User();
  2. user.names = [
  3. "Alexander",
  4. "Alex",
  5. "Sasha",
  6. "Shurik"
  7. ];

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 databasevia JSON.stringify.Very useful when you do not have json type in your database and you want to store and load objectwithout any hustle.For example:

  1. @Entity()
  2. export class User {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column("simple-json")
  6. profile: { name: string, nickname: string };
  7. }
  1. const user = new User();
  2. 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

Columns with generated values

You can create column with generated value using @Generated decorator. For example:

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

uuid value will be automatically generated and stored into the database.

Besides “uuid” there is also “increment” and “rowid” (CockroachDB only) generated types, however there are some limitationson 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).

Column options

Column options defines additional options for your entity columns.You can specify column options on @Column:

  1. @Column({
  2. type: "varchar",
  3. length: 150,
  4. unique: true,
  5. // ...
  6. })
  7. 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 create varchar(150) type you 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 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 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: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType } - Used to marshal properties of arbitrary type EntityType into a type DatabaseType supported 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.

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:

  1. @Entity()
  2. export class Photo {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column()
  6. title: string;
  7. @Column()
  8. description: string;
  9. @Column()
  10. size: string;
  11. }
  12. @Entity()
  13. export class Question {
  14. @PrimaryGeneratedColumn()
  15. id: number;
  16. @Column()
  17. title: string;
  18. @Column()
  19. description: string;
  20. @Column()
  21. answersCount: number;
  22. }
  23. @Entity()
  24. export class Post {
  25. @PrimaryGeneratedColumn()
  26. id: number;
  27. @Column()
  28. title: string;
  29. @Column()
  30. description: string;
  31. @Column()
  32. viewCount: number;
  33. }

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:

  1. export abstract class Content {
  2. @PrimaryGeneratedColumn()
  3. id: number;
  4. @Column()
  5. title: string;
  6. @Column()
  7. description: string;
  8. }
  9. @Entity()
  10. export class Photo extends Content {
  11. @Column()
  12. size: string;
  13. }
  14. @Entity()
  15. export class Question extends Content {
  16. @Column()
  17. answersCount: number;
  18. }
  19. @Entity()
  20. export class Post extends Content {
  21. @Column()
  22. viewCount: number;
  23. }

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:

  1. import {Entity, Column, PrimaryGeneratedColumn, ManyToOne, OneToMany} from "typeorm";
  2. @Entity()
  3. export class Category {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. name: string;
  8. @Column()
  9. description: string;
  10. @OneToMany(type => Category, category => category.children)
  11. parent: Category;
  12. @ManyToOne(type => Category, category => category.parent)
  13. children: Category;
  14. }

Closure table

A closure table stores relations between parent and child in a separate table in a special way.Its efficient in both reads and writes.To learn more about closure table take a look at this awesome presentation by Bill Karwin.Example:

  1. import {Entity, Tree, Column, PrimaryGeneratedColumn, TreeChildren, TreeParent, TreeLevelColumn} from "typeorm";
  2. @Entity()
  3. @Tree("closure-table")
  4. export class Category {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string;
  9. @Column()
  10. description: string;
  11. @TreeChildren()
  12. children: Category[];
  13. @TreeParent()
  14. parent: Category;
  15. @TreeLevelColumn()
  16. level: number;
  17. }