TypeORM with Express

TypeORM with Express ”; Previous Next Express is one of the popular JavaScript framework to create web application. Let us learn how to use TypeORM along with express framework in this chapter. Creating a simple application TypeORM CLI provides an easy option to create a complete working express web application (Restful API application) integrated with TypeORM. The CLI command to create the application is as follows − cd /path/to/workspace typeorm init –express –name typeorm-express-sample –database mysql Above command will create a new web application under typeorm-express-sample folder. The structure of the application is as follows − │ .gitignore │ ormconfig.json │ package.json │ README.md │ tsconfig.json │ └───src │ index.ts │ routes.ts │ ├───controller │ UserController.ts │ ├───entity │ User.ts │ └───migration Here, As we know, ormconfig.json is the TypeORM configuration file. The code is as follows, { “type”: “mysql”, “host”: “localhost”, “port”: 3306, “username”: “test”, “password”: “test”, “database”: “test”, “synchronize”: true, “logging”: false, “entities”: [ “src/entity/**/*.ts” ], “migrations”: [ “src/migration/**/*.ts” ], “subscribers”: [ “src/subscriber/**/*.ts” ], “cli”: { “entitiesDir”: “src/entity”, “migrationsDir”: “src/migration”, “subscribersDir”: “src/subscriber” } } Here, change the database setting to match your local database setting. package.json file is the main configuration of the application. tsconfig.json file contains the configuration related to TypeScript. entity folder contains the TypeORM models. A default User model will be created by CLI and it is as follows − import {Entity, PrimaryGeneratedColumn, Column} from “typeorm”; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() firstName: string; @Column() lastName: string; @Column() age: number; } controller folder contains the express controllers. CLI create a default user API controller with add / list / delete user details. The code is as follows − import {getRepository} from “typeorm”; import {NextFunction, Request, Response} from “express”; import {User} from “../entity/User”; export class UserController { private userRepository = getRepository(User); async all(request: Request, response: Response, next: NextFunction) { return this.userRepository.find(); } async one(request: Request, response: Response, next: NextFunction) { return this.userRepository.findOne(request.params.id); } async save(request: Request, response: Response, next: NextFunction) { return this.userRepository.save(request.body); } async remove(request: Request, response: Response, next: NextFunction) { let userToRemove = await this.userRepository.findOne(request.params.id); await this.userRepository.remove(userToRemove); } } Here, all method is used to fetch all users from the database. one method is used to fetch a single user from the database using user id save method is used to save the user information into the database. delete method is used to delete the user from the database using user id routes.ts file maps the user controller methods to proper URL and the code is as follows − import {UserController} from “./controller/UserController”; export const Routes = [{ method: “get”, route: “/users”, controller: UserController, action: “all” }, { method: “get”, route: “/users/:id”, controller: UserController, action: “one” }, { method: “post”, route: “/users”, controller: UserController, action: “save” }, { method: “delete”, route: “/users/:id”, controller: UserController, action: “remove” }]; Here, /users url is mapped to user controller. Each verb post, get and delete are mapped to different methods. Finally, index.ts is our main web application entry point. The source code is as follows − import “reflect-metadata”; import {createConnection} from “typeorm”; import * as express from “express”; import * as bodyParser from “body-parser”; import {Request, Response} from “express”; import {Routes} from “./routes”; import {User} from “./entity/User”; createConnection().then(async connection => { // create express app const app = express(); app.use(bodyParser.json()); // register express routes from defined application routes Routes.forEach(route => { (app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => { const result = (new (route.controller as any))[route.action](req, res, next); if (result instanceof Promise) { result.then(result => result !== null && result !== undefined ? res.send(result) : undefined); } else if (result !== null && result !== undefined) { .json(result); } }); }); // setup express app here // … // start express server app.listen(3000); // insert new users for test await connection.manager.save(connection.manager.create(User, { firstName: “Timber”, lastName: “Saw”, age: 27 })); await connection.manager.save(connection.manager.create(User, { firstName: “Phantom”, lastName: “Assassin”, age: 24 })); console.log(“Express server has started on port 3000. Open http://localhost:3000/users to see results”); }).catch(error => console.log(error)); Here, the application configures the routes, insert two users and then start the web application at port 3000. We can access the application at http://localhost:3000 To run the application, follow below steps − Let us install the necessary packages using below command − npm install Output npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN [email protected] No repository field. npm WARN [email protected] No license field. added 176 packages from 472 contributors and audited 351 packages in 11.965s 3 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Run the below command to start the application. npm start Output > [email protected] start /path/to/workspace/typeorm-express-sample > ts-node src/index.ts Express server has started on port 3000. Open http://localhost:3000/users to see results Let us access our web application API using curl command as below − curl http://localhost:3000/users Here, curl is a command line

TypeORM – Entity

TypeORM – Entity ”; Previous Next 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. Introduction 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 − Student.ts import {Entity, PrimaryGeneratedColumn, Column} from “typeorm”; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column() Name: string; @Column() age: number; } Here, Entity() decorator class is used to represent that the Student class is an entity. PrimaryGeneratedColumn() decorator class is used to represent that the id column is the primary key column of the Student entity. Column() decorator class is used to represent other columns such as Name and Age of the Student entity. 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 − index.ts 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, Line 1 – 3 imports the relevant classes, createConnection and Student Line 5 creates a new connection to the database using createConnection and if connection is established, it executes the code inside the then block. Line 10 create new Student object, stud. Line 13-14 set the attributes of our newly created stud object. Line 17 saves the entity to the database using save method available in connection.manager object. Line 23 fetches the student details from the database using find method available in connection.manager object. Start Mysql server and run your application 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 − Output Open mysql server following student table is added inside your database. Columns 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, age is the attribute of the entity. In other word, age is a field / column in the student table in the database. int represent the type of the age column in the database. 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. Column Options 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 − name − Name of the database field / column. length − Length of the database field / column. nullable − Specify whether the database field / column allows null or not. default − Default value of the database field / column. primary − Specify whether the database field / column is primary key of the table. unique − Specify whether the database field / column is unique *precision** − Precision of the database field / column scale − Scale of the database field / column comment − Comment or description of the database field / column @Generated decorator 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 {

TypeORM – Connection API

TypeORM – Connection API ”; Previous Next To interact with database, we need a connection object to the database. We need to create a connection object before doing the database operation and has to terminate it once thee database operations are done. Let us learn about Connection API provided by TypeORM in this section. Creating a new connection Before creating a new connection, we need to configure database connection details in the ormconfig.json configuration file. A sample connection details is shown below − ormconfig.json { name: “firstconnection”, type: “mysql”, host: “localhost”, port: 3306, username: “root”, password: “root”, database: “firstDB” } Here, name − Name of the database connection. type − Database type. host − Hostname of the database server. port − Database server port. username − Account name having access to the database. password − Password of the above mentioned account. database − Name of the database to connect. createConnection CreateConnection method is provided by TypeORM to create a new connection. It is defined as below, import { createConnection, Connection } from “typeorm”; const connection = await createConnection({ }); Here, createConnection will use the configuration details specified in the ormconfig.json file. Alternatively, you can define the connection URL as arguments to the createConnection method as specified follows − const connection = createConnection({ type: ”mysql”, url: ”localhost:8888/firstDB” }) Here, createConnection returns an object, which can be used to open / close the connection to the database. Multiple connections TypeORM provides an option to create multiple database connection as well. First, the configuration file ormconfig.json can be used to specify the details of the multiple database connection. Let us configure multiple databases in ormconfig.json as specified follows, ormconfig.json { name: “firstconnection”, type: “mysql”, host: “localhost”, port: 3306, username: “root”, password: “root”, database: “firstDB” }, { name: “secondconnection”, type: “mysql”, host: “localhost”, port: 3306, username: “root”, password: “root”, database: “secondDB” }, { name: “thirdconnection”, type: “mysql”, host: “localhost”, port: 3306, username: “root”, password: “root”, database: “thirdDB” } Now, we can use the argument provided by the createConnection method to specify the name of the connection to create connection object as mentioned below − const firstconnection: Connection = await createConnection(“firstconnection”); Here, createConnection will use the configuration details of the firstconnection specified in the ormconfig.json file to create the connection object. TypeORM also provides yet another API, createConnections to create multiple connection as once and then, use it whenever necessary as specified below − import { createConnections, Connection } from “typeorm”; const connections: Connection[] = await createConnections([ ]); Here, connections hold all the connection objects as an array. ConnectionManager TypeORM also provides an another API, connectionManager to create connection. It is defined below − import {getConnectionManager, ConnectionManager, Connection} from “typeorm”; const connectionManager = getConnectionManager(); const connection = connectionManager.create({ }); await connection.connect(); TypeORM prefers the usage of createConnection over ConnectionManager to create connection objects. Print Page Previous Next Advertisements ”;

TypeORM – Working with MongoDB

TypeORM – Working with MongoDB ”; Previous Next This chapter explains the extensive MongoDB database support provided by TypeORM. Hopefully, we have installed mongodb using npm. If it is not installed, use the below command to install MongoDB driver, npm install mongodb –save Creating a project Let’s create a new project using MongoDB as follows − typeorm init –name MyProject –database mongodb Configure ormconfig.json Let’s configure MongoDB host, port and database options in ormconfig.json file as specified below − ormconfig.json { “type”: “mongodb”, “host”: “localhost”, “port”: 27017, “database”: “test”, “synchronize”: true, “logging”: false, “entities”: [ “src/entity/**/*.ts” ], “migrations”: [ “src/migration/**/*.ts” ], “subscribers”: [ “src/subscriber/**/*.ts” ], “cli”: { “entitiesDir”: “src/entity”, “migrationsDir”: “src/migration”, “subscribersDir”: “src/subscriber” } } Define entities and columns Let us create a new entity named Student inside your src directory. Entities and columns are same. To generate primary key column, we use @PrimaryColumn or @PrimaryGeneratedColumn. This can be defined as @ObjectIdColumn. Simple example is shown below − Student.ts import {Entity, ObjectID, ObjectIdColumn, Column} from “typeorm”; @Entity() export class Student { @ObjectIdColumn() id: ObjectID; @Column() Name: string; @Column() Country: string; } To save this entity, open index.ts file and add the following changes − index.ts import “reflect-metadata”; import {createConnection} from “typeorm”; import {Student} from “./entity/Student”; createConnection().then(async connection => { console.log(“Inserting a new Student into the database…”); const std = new Student(); std.Name = “Student1”; std.Country = “India”; await connection.manager.save(std); console.log(“Saved a new user with id: ” + std.id); console.log(“Loading users from the database…”); const stds = await connection.manager.find(Student); console.log(“Loaded users: “, stds); console.log(“TypeORM with MongoDB”); }).catch(error => console.log(error)); Now, start your server and you will get the following response − npm start MongoDB EntityManager We can also use EntityManager to fetch data. Simple example is shown below − import {getManager} from “typeorm”; const manager = getManager(); const result = await manager.findOne(Student, { id:1 }); Similarly, we can also use repository to access data. import {getMongoRepository} from “typeorm”; const studentRepository = getMongoRepository(Student); const result = await studentRepository.findOne({ id:1 }); If you want to filter the data using equal option as follows − import {getMongoRepository} from “typeorm”; const studentRepository = getMongoRepository(Student); const result = await studentRepository.find({ where: { Name: {$eq: “Student1″}, } }); As we seen in this chapter, TypeORM makes it easy to work with MongoDB database engine. Print Page Previous Next Advertisements ”;

TypeORM – Relations

TypeORM – Relations ”; Previous Next Relations are used to refer the relationship between table in database. In general, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table. This feature makes relational database more powerful and efficiently store information. TypeORM allows the entities to be related to each other and subsequently database tables. In general, relationship can be classified into four broader categories. They are as follows, one-to-one − One object of the given entity relates to only one object of the target entity and vice versa. For example, a country will have only one capital city and similarly a city will be capital of only one country. many-to-one − Multiple object of the given entity relates to one object of the target entity. For example, city comes under only one country but country can have multiple cities. one-to-many − Same as many-to-one except the relationship is reversed. many-to-many − Multiple object of the given entity relates to multiple object of the target entity. For example, an article may be tagged under multiple topic like programming language, finance, etc., and at the same time a particular tag may have multiple articles as well. TypeORM also provides options to enhance the relationship of the entities. They are as follows − eager − Source entity object loads the target entity objects as well. cascade − Target entity object gets inserted or updated while the source entity object is inserted or updated. onDelete − Target entity objects get deleted as well while the source entity object is deleted. primary − Used to specify that the relation column is primary key or not. nullable − Used to specify that the relation column is nullable or not. Let us go through different types of relation mapping in detail. One-to-One As we learned earlier, it is referred by the instance of one table field contains the instance of another table field and vice versa. Let us create a Details table − Details.ts import {Entity, PrimaryGeneratedColumn, Column} from “typeorm”; @Entity() export class Details { @PrimaryGeneratedColumn() id: number; @Column() gender: string; @Column() country: string; } Let’s create an another entity Customer as follows − Customer.ts import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from “typeorm”; import {Details} from “./Details”; @Entity() export class Customer { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToOne(type => Details) @JoinColumn() details: Details; } Here, We have added mapping OneToOne to Details table. @JoinColumn() contain a “relation id” and foreign key to Customer table. We can save the relation in index.ts as follows − const details = new Details(); details.gender = “female”; details.country = “india” await connection.manager.save(details); const customer = new Customer(); customer.name = ”customer1”; customer.details = Details; await connection.manager.save(Customer); One-to-Many and Many-to-One As we learned earlier, it is referred by the instance of first table field contains the multiple instances of second table field called One-to-Many mapping and multiple instances of first table contains only one instance of second table called Many-to-One mapping. Consider an example of Student and project entities whereas, student can work on more than one project but each project is handled by only one student. Let’s create a Project entity as follows − Project import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from “typeorm”; import {Student} from “./Student”; @Entity() export class Project { @PrimaryGeneratedColumn() id: number; @Column() projects: string; @ManyToOne(type => Student, student => student.projects) student: Student; } Now, we create Student entity as below − import {Entity, PrimaryGeneratedColumn, Column, OneToMany} from “typeorm”; import {Project} from “./Project”; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToMany(type => Project, project => project.student) projects: Project[]; } Here, @OneToMany property mapped Project and @ManyToOne property mapped to Student. However, @OneToMany cannot exist without @ManyToOne and @ManyToOne property contain “relation id” and foreign key. We can save the connection in index.ts as follows − const proj1 = new Project(); proj1.projects = “database management”; await connection.manager.save(proj1); const proj2 = new Project(); proj2.projects = “web application”; await connection.manager.save(proj2); const stud = new Student(); stud.name = “Student1”; stud.projects = [proj1, proj2]; await connection.manager.save(stud); Many-to-Many As we learned earlier, it is referred by multiple records in one table are related to multiple records in another table. Consider an example, University student can be enrolled in multiple classes at a time which means student may have four or five classes per semester and a class can have many students. We can simply conclude, a student has many classes, and a class has many students. Let’s create an entity for Classes as follows − import {Entity, PrimaryGeneratedColumn, Column} from “typeorm”; @Entity() export class Classes { @PrimaryGeneratedColumn() id: number; @Column() name: string; } Now, we create Student entity as below − import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from “typeorm”; import {Classes} from “./Classes”; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() subjects: string; @ManyToMany(type => Classes) @JoinTable() classes: Classes[]; } Print Page Previous Next Advertisements ”;

TypeORM – Working with CLI

TypeORM – Working with CLI ”; Previous Next This section explains about TypeORM CLI commands in detail. Create TypeORM project typeorm init is the easiest and fastest way to setup a TypeORM project. You can create a new project as, typeorm init –name Demoproject –database mysql After executing the command, you will get the following output on your screen − Project created inside /Users/workspace/TypeORM/Demoproject directory. Create an entity To create a new entity using CLI as, typeorm entity:create -n Person Now, Person entity is created inside your project src directory. Entity /Users/workspace/TypeORM/Demoproject/src/entity/Person.ts has been created successfully. If you have a multi-module project structure with multiple entities in different directories, you can use the below command, typeorm entity:create -n Person -d src/Person/entity Create a new subscriber To create a new subscriber using CLI as follows − typeorm subscriber:create -n PersonSubscriber You could see the following response − Subscriber /path/to/TypeORM/Demoproject/src/subscriber/PersonSubscriber.ts has been created successfully. Create migrations You can create a new migration using CLI as mentioned below − typeorm migration:create -n PersonMigration The above command created a migration directory inside your project src. Migration files are stored inside it. Migration /path/to/TypeORM/Demoproject/src/migration/1587395030750-PersonMigration.ts has been generated successfully. Database schema To synchronize a database schema, use the below command − typeorm schema:sync To completely drop a database schema, use the below command − typeorm schema:drop Sql queries If you want to execute any sql queries, we can execute directly from here. For example, to display all the records of customers, use the below query − typeorm query “select * from customers” If you want to clear everything stored in the cache. You can do it using the following command − typeorm cache:clear Conclusion TypeORM is an excellent open source ORM framework to create high quality and scalable applications from small scale applications to large scale enterprise applications with multiple databases. Print Page Previous Next Advertisements ”;

TypeORM – Migrations

TypeORM – Migrations ”; Previous Next Migrations are like version control for your database. It is used to modify and share application’s database schema. This section explains about how migrations works in TypeORM. Creating new migration To create a new migration, first we need to setup connection in ormconfig.json. It is defined below − ormconfig.json “type”: “mysql”, “host”: “localhost”, “port”: 8889, “username”: “root”, “password”: “root”, “database”: “Library”, “entities”: [“entity/*.js”], “migrationsTableName”: “student_migration_table”, “migrations”: [“migration/*.js”], “cli”: { “migrationsDir”: “migration” } Here, migrationsTableName − it refers the migration table name. migrations − TypeORM loads migrations from given directory. cli − indicates migration will create inside the specific directory. Create Book entity Let’s create an entity named Book entity inside src/entity/Book.ts as follows − import { Entity, Column, PrimaryGeneratedColumn } from ”typeorm”; @Entity() export class Book { @PrimaryGeneratedColumn() id: number; @Column() title: string; @Column() text: string; } Execute CLI to create new migration Now, we can execute new migration using CLI as follows − Syntax typeorm migration:create -n <migration-name> Example typeorm migration:create -n myMigration After executing the above command, you could see the below response − Migration /path/to/project/src/migration/1587101104904-myMigration.ts has been generated successfully. Now, move inside src/migration/1587101104904-myMigration.ts file looks similar to this. import {MigrationInterface, QueryRunner} from “typeorm”; export class myMigration1587101104904 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { } public async down(queryRunner: QueryRunner): Promise<any> { } } Here, We have two methods up and down. up method is used to add changes to the migration and down method is used to revert changes in your migration. Let us add up method inside myMigration.ts file as specified below − import {MigrationInterface, QueryRunner} from “typeorm”; export class Book1587131893261 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { await queryRunner.query(`ALTER TABLE book ADD COLUMN price int`); } public async down(queryRunner: QueryRunner): Promise<any> { } } Here, We have added a new column price inside book table. Now, execute the CLI to add the above changes. ts-node ./node_modules/typeorm/cli.js migration:run The above command executes migrations and run them in a sequence. Now, you could see the below changes in your screen − Output Now open your mysql server, new column is added. It is shown below − Similarly, We can modify column title datatype to varchar(30) as follows, import {MigrationInterface, QueryRunner} from “typeorm”; export class Book1587131893261 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { await queryRunner.query(`ALTER TABLE book MODIFY COLUMN title varchar(30)`); } public async down(queryRunner: QueryRunner): Promise<any> { } } Now, execute the same command and you could the below changes − ts-node ./node_modules/typeorm/cli.js migration:run Output Book table is modified as, Revert migration Let’s add the below code inside down method to revert migration − import {MigrationInterface, QueryRunner} from “typeorm”; export class Book1587131893261 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { } public async down(queryRunner: QueryRunner): Promise<any> { await queryRunner.query(`ALTER TABLE book drop column price`); // reverts things made in “up” method } } Now, execute the below command to revert all the changes − ts-node ./node_modules/typeorm/cli.js migration:revert You could see the following response − Output Book table is modified as, Output As we seen in this chapter, TypeORM makes it easy to write database migration script. Print Page Previous Next Advertisements ”;

TypeORM – Query Operations

TypeORM – Query Operations ”; Previous Next Data manipulation is used to manage and view data. This section explains about how to access database queries like insert, update, select and delete queries using QueryBuilder. Let’s go through one by one in detail. Build insert query Let us create a Customer entity as follows − Customer.ts import {Entity, PrimaryGeneratedColumn, Column} from “typeorm”; @Entity() export class Customer { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() age: number; } Let’s add the following changes in index.ts as follows − index.ts import “reflect-metadata”; import {createConnection} from “typeorm”; import {Customer} from “./entity/Customer”; import {getConnection} from “typeorm”; createConnection().then(async connection => { await getConnection().createQueryBuilder() .insert() .into(Customer) .values([ { name: “Adam”,age:11}, { name: “David”,age:12} ]) .execute(); }).catch(error => console.log(error)); Now, start your application using the below command − npm start Output You could see the following output on your screen − Now open your mysql server, table inserted with two fields as shown below − Build update query Last section, we have inserted two rows of data. Let’s check how update query works. Add the following changes in index.ts as follows − import “reflect-metadata”; import {createConnection} from “typeorm”; import {Customer} from “./entity/Customer”; import {getConnection} from “typeorm”; createConnection().then(async connection => { await getConnection() .createQueryBuilder() .update(Customer) .set({ name: “Michael” }) .where(“id = :id”, { id: 1 }) .execute(); console.log(“data updated”); }).catch(error => console.log(error)); Now, start your application using the below command − npm start You could see the following output on your screen − Mysql table is modified as shown below − Build select query select query is used to display the records from the table. Let’s add the following code in index.ts as follows − index.ts import “reflect-metadata”; import {createConnection} from “typeorm”; import {Customer} from “./entity/Customer”; createConnection().then(async connection => { console.log(“Display records from Customer table…”); const cus = new Customer(); console.log(“Loading customers from the database…”); const customers = await connection.manager.find(Customer); console.log(“Loaded users: “, customers); }).catch(error => console.log(error)); You could see the following output on your screen − where expression Let us add where expression in the query to filter the customers. The sample code is as follows − import “reflect-metadata”; import {createConnection} from “typeorm”; import {Customer} from “./entity/Customer”; import {getConnection} from “typeorm”; createConnection().then(async connection => { const customer = await getConnection() .createQueryBuilder() .select(“cus”) .from(Customer, “cus”) .where(“cus.id = :id”, { id: 1 }) .getOne(); console.log(customer); }) .catch(error => console.log(error)); The above program will return first id records. You could see the following output on your screen, Similarly, you can try other expressions as well. Build delete query Last section, we have inserted, updated and select data. Let’s check how delete query works. Add the following changes in index.ts as follows − import “reflect-metadata”; import {createConnection} from “typeorm”; import {Customer} from “./entity/Customer”; import {getConnection} from “typeorm”; createConnection().then(async connection => { await getConnection() .createQueryBuilder() .delete() .from(Customer) .where(“id = :id”, { id: 1 }) .execute(); console.log(“data deleted”); }).catch(error => console.log(error)); You could see the following output on your screen − And your mysql table is modified as follows − Print Page Previous Next Advertisements ”;

TypeORM – Working with Entity Manager

TypeORM – Working with Entity Manager ”; Previous Next EntityManager is similar to Repository and used to manage database operations such as insert, update, delete and load data. While Repository handles single entity, EntityManager is common to all entities and able to do operations on all entities. Entity Manager API We can access EntityManager using getManager() method as specified below − import { getManager } from “typeorm”; const entityManager = getManager(); Let us learn most important method of the EntityManager in this chapter. connection connection method returns database ORM connection to specific databases. The sample code is as follows − const connection = manager.connection; QueryRunner queryRunner method returns custom query runner object and it is used for database operations by entity manager. The sample code is as follows − const queryRunner = manager.queryRunner; transaction If multiple database requests are called, transaction will execute in a single database transaction. The sample code to get the transaction is as follows − await manager.transaction(async manager => { }); query query method executes sql queries. Simple insert query as shown below − const qur = await manager.query(`insert into student(name,age) values(”stud2”,13)`); insert insert method is used to insert a new entity or array of entities to the database. The sample code is as follows − await manager.insert(Student, { Name: “Student3”, Age: 14 }); update update is used to update the existing records in the database. await manager.update(User, 1, { Name: “Adam” }); This query works similar to the below SQL query, UPDATE student SET Name = “Adam” WHERE id = 1 delete delete method will delete the specified record from the table, await manager.delete(Student, 1); This will delete with id 1 of student record. save save is used to save the given entity into the database. Simple Student entity can be save as shown below − import {Student} from “./entity/Student”; createConnection().then(async connection => { console.log(“Inserting a new record into the student database…”); const stud = new Student(); stud.Name = “student1”; stud.age = 12; await connection.manager.save(stud); } This will add new student record into the database. save method will insert the student, if the given student does not exist in the database. Otherwise, save will update existing student record in the database. remove remove is used to delete the given entity from the database. Simple Student entity can be deleted as shown below − await manager.remove(stud); count count method will return the number of records available in the table and you can use it pagination purposes. The sample code is as follows − const cnt = await manager.count(Student, { age: 12 }); find find method is used for searching purposes. It fetches all the record from database as shown below − console.log(“Loading users from the database…”); const students = await connection.manager.find(Student); console.log(“Loaded users: “, students); findOne Similar to find method, but returns the first matched record. The sample code is as follows − const stud = await manager.findOne(Student, 1); clear clear method clears all the data from the table. The sample code is as follows − await manager.clear(Student); Print Page Previous Next Advertisements ”;

TypeORM – Home

TypeORM Tutorial PDF Version Quick Guide Resources Job Search Discussion TypeORM is an object-relational mapper library for TypeScript and JavaScript. TypeORM is a tool in the Micro-frameworks category of the tech stack. This tutorial walks through the basics of TypeORM framework, how to set up entity objects, how to configure relationship between objects, how to store/retrieve data from/to the database, how to customize the repository instance to manipulate the given database and finally conclude with different database operations. Audience This tutorial is prepared for professionals who are aspiring to make a career in the field of back-end database development using object relation mapping. This tutorial is intended to make you comfortable in getting started with the TypeORM concepts. Prerequisites Before proceeding with the various types of concepts given in this tutorial, we assume that the readers have the basic understanding of database and objects in programming languages. In addition to this, it will be very helpful, if the readers have a sound knowledge on TypeScript and JavaScript. Print Page Previous Next Advertisements ”;