An entity is a collection of fields and associated database operations. It is used to map database table and its fields with the entities and its attributes. This chapter explains about the TypeORM entities in detail.
Let us create a simple Entity class in our code. Move to your project root location and go inside src folder and move to entity folder. Now, create a TypeScript file, Student.ts and enter below code −
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column() Name: string; @Column() age: number; }
Here,
Now, Entity class Student is created. TypeORM will auto generate a table corresponding to the Student entity in our database and it will be named as student. Now, move to src/index.ts file and add the following code −
import "reflect-metadata"; import {createConnection} from "typeorm"; import {Student} from "./entity/Student"; //import Student entity createConnection().then(async connection => { console.log("Inserting a new record into the student database..."); //create student object const stud = new Student(); //Assign student name and age here stud.Name = "student1"; stud.age = 12; //save student object in connection await connection.manager.save(stud); console.log("Saved a new user with id: " + stud.id); console.log("Loading users from the database..."); //Display student saved records const students = await connection.manager.find(Student); console.log("Loaded users: ", students); console.log("Here you can setup and run express/koa/any other framework."); }).catch(error => console.log(error));
Here,
We have created Student entity and create connection in index.ts. Let us start both MySql server and your application.
npm start
This will return the following output on your screen −
Open mysql server following student table is added inside your database.
As learned earlier, Entity is actually a collection of attributes. As entity object refers the database table. Its attributes / member variables refer the corresponding database table’s fields / columns. TypeORM supports all type of database fields through Column class. Let us learn the different type of column supported by TypeORM in this chapter.
@Column() decorator class is used to represent the column and its type in the entity.
For example, age attribute of the student entity and the type of the age attribute can be defined as below −
@Column("int") age: integer; // OR @Column({ type: "int" }) age: integer;
Here,
TypeORM supports nearly all the types available in the popular database engine. Actually, TypeORM enables different set of types for each database engine. We can use any database type supported by our database engine without any issue.
For example, the type supported by TypeORM for postgresql database engine is as follows −
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
Similarly, TypeORM supports a different set of datatype for MySQL.
TypeORM provides an extensive set of options other than type to describe the column. For example, length option refers the length of the database field and it can be specified as below −
@Column("varchar", { length: 100 })
Some of the most common column options are as follows −
TypeORM provides additional decorator, @Generated to auto generate the column values. For example, Universally Unique Identifier (UUID) is quite common to use in database to store unique value in a column. The sample code to generate UUID is as follows −
@Entity() export class Student { @PrimaryColumn() id: number; @Column() @Generated("uuid") uuid: string; }
Here,
uuid is generated automatically and stored inside the database.
At least one primary column field is mandatory for any entity in database. It is classified into different types of decorators. We will discuss it one by one.
@PrimaryColumn()
@PrimaryColumn() decorator is used to create primary column for any type of data. Simple example is shown below,
import {Entity, PrimaryColumn} from "typeorm"; @Entity() export class Student { @PrimaryColumn() id: number; }
Here,
id is an integer, which doesn’t accept duplicate values, but we need to assign values.
We can assign primary column for one or more fields as well, if the situation demands.
import {Entity, PrimaryColumn} from "typeorm"; @Entity() export class Student { @PrimaryColumn() id: number; @PrimaryColumn() email: string; @PrimaryColumn() phone: number; }
@PrimaryGeneratedColumn() field is used to specify the primary column as well as to auto generate the column value in the database. It is shown below −
import {Entity, PrimaryGeneratedColumn} from "typeorm"; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; }
Here,
You don’t have to assign id value; it will be generated automatically by the TypeORM in the database table.
@PrimaryGeneratedColumn also accepts an argument to specify the type of generator. One of the main use is to generate unique id based on UUID.
import {Entity, PrimaryGeneratedColumn} from "typeorm"; @Entity() export class Student { @PrimaryGeneratedColumn("uuid") id: string; }
Advanced relational database supports array datatype. To support the array datatype, TypeORM provides a special column type, *simple-array" to store primitive array values. A sample code to use it is as follows −
@Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column("simple-array") names: string[]; }
Lot of modern database engine supports JSON database. To use JSON datatype, TypeORM provides a special type, single-json. The sample code to use it is as follows −
@Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column("simple-json") info: { firstName: string, middleName: string, lastName: string }; }
This value can be defined in index.ts as,
const stud = new Student(); stud.info = { firstName: "John", middleName: "peter", lastName: "Michael" };
TypeORM supports the following special columns
Entity inheritance is use to reduce duplication of entities. Consider the below entities −
@Entity() export class Result { @PrimaryGeneratedColumn() id: number; @Column() title: string; @Column() description: string; @Column() eligible: string }
The code for grade.ts is as follows −
@Entity() export class Grade { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() title: string; @Column() description: string; @Column() grading : string; }
Here,
The above two entities have columns id, title and description. Using entity inheritance, we create one base class Details and combine the above two entities as specified below.
export abstract class Details { @PrimaryGeneratedColumn() id: number; @Column() title: string; @Column() description: string; } @Entity() export class Result extends Details{ @Column() eligible: string } @Entity() export class Grade extends Details{ @Column() name : string; @Column() grading : string; }
Now start your server, you could see the below response,
Now open your mysql server and move to your database, you could see the following tables,