Table of contents
1.
Introduction
2.
What is TypeORM?
3.
Installation and Basic Configuration
3.1.
Installing TypeORM
3.2.
Setting Up a Project
3.3.
Configuring TypeORM
4.
Understanding the Core Concepts
4.1.
Entities
4.2.
Repositories
5.
Performing CRUD Operations
5.1.
Creating Data:
5.2.
Reading Data:
5.3.
Updating Data:
5.4.
Deleting Data:
6.
Advanced Features of TypeORM
6.1.
Relations
6.2.
Query Builder
6.3.
Migrations
7.
Advantages of TypeORM
8.
Frequently Asked Questions
8.1.
What is TypeORM used for?
8.2.
What is TypeORM in NestJS?
8.3.
Is TypeORM a framework?
8.4.
What is the difference between Sequelize and TypeORM?
8.5.
Can TypeORM be used with SQL databases only?
8.6.
Is TypeORM suitable for large-scale applications?
9.
Conclusion
Last Updated: Aug 12, 2024
Medium

TypeORM

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

TypeORM is a highly influential Object-Relational Mapping (ORM) library for TypeScript and JavaScript, which allows developers to manage database interactions in a more intuitive, object-oriented way. This article will provide an in-depth exploration of TypeORM, offering insights into its installation, configuration, and use, with a focus on TypeScript.

TYPEORM

We'll delve into key concepts, practical examples, and common FAQs to ensure a comprehensive understanding of TypeORM's capabilities and applications.

What is TypeORM?

TypeORM is an Object-Relational Mapper (ORM) for TypeScript and JavaScript that simplifies database interaction. It supports various databases like MySQL, PostgreSQL, and MongoDB, allowing developers to define entities and manage database operations using TypeScript classes. It enhances productivity by bridging the gap between databases and code.

Installation and Basic Configuration

Installing TypeORM

To get started with TypeORM, you need to have Node.js installed. Then, install TypeORM and a database driver like PostgreSQL, MySQL, or SQLite. For this guide, we'll use PostgreSQL.

npm install typeorm pg

Setting Up a Project

Initialize a new Node.js project if you haven't already:

npm init -y


Then, create a tsconfig.json file for TypeScript configuration:

tsc --init

Configuring TypeORM

Create an ormconfig.json file in your project root. This file will hold your database connection settings:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "your_username",
  "password": "your_password",
  "database": "your_database"
}

Understanding the Core Concepts

Entities

Entities in TypeORM represent tables in your database. They are classes decorated with @Entity, and their properties are decorated with column decorators, representing the columns in the table.

Example:

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}

Repositories

Repositories are abstractions that allow you to manage entity instances. They provide methods like find, findOne, save, etc., to interact with the database.

Working with Data

Creating a Connection

Before performing any database operations, establish a connection:

import { createConnection } from 'typeorm';

createConnection().then(connection => {
  // you can now use the connection
}).catch(error => console.log(error));

Performing CRUD Operations

Creating Data:

To create a new record, use the repository's save method:

import { getRepository } from 'typeorm';
import { User } from './entity/User';

async function createUser() {
  const userRepository = getRepository(User);
  const newUser = userRepository.create({ name: 'John Doe', email: 'john@example.com' });
  await userRepository.save(newUser);
}

Reading Data:

You can read data using various methods like find, findOne, or custom query builders:

async function getUsers() {
  const users = await getRepository(User).find();
  console.log(users);
}

Updating Data:

Update records using the save method or query builder:

async function updateUser(userId: number, updatedData: Partial<User>) {
  const userRepository = getRepository(User);
  await userRepository.update(userId, updatedData);
}

Deleting Data:

Delete records using the remove or delete methods:

async function deleteUser(userId: number) {
  await getRepository(User).delete(userId);
}

Advanced Features of TypeORM

Relations

TypeORM allows defining relationships between tables/entities, like One-to-One, One-to-Many, and Many-to-Many.

Example:

@Entity()
export class Profile {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  bio: string;
  @OneToOne(() => User)
  @JoinColumn()
  user: User;
}

Query Builder

For complex queries, use the query builder:

const users = await getRepository(User)
  .createQueryBuilder("user")
  .where("user.name = :name", { name: "John" })
  .getMany();

Migrations

Migrations are a way to manage database schema changes. TypeORM provides commands to generate and run migrations.

Advantages of TypeORM

  • TypeScript Support: TypeORM is built with TypeScript, providing type safety and autocompletion, which helps catch errors during development.
  • Database Agnostic: It supports multiple databases like MySQL, PostgreSQL, SQLite, and MongoDB, allowing flexibility in choosing or switching databases.
  • Seamless Integration: TypeORM integrates easily with frameworks like NestJS and Express, making it a popular choice for building server-side applications.
  • Active Record and Data Mapper Patterns: TypeORM supports both Active Record and Data Mapper patterns, giving developers flexibility in how they interact with the database.
  • Migrations: It offers built-in support for database migrations, helping manage schema changes over time.
  • Relationships: TypeORM simplifies managing complex relationships between entities (e.g., one-to-many, many-to-many).
  • Query Builder: The query builder allows developers to construct complex queries programmatically, offering more control and flexibility.
  • Community and Documentation: TypeORM has a strong community and extensive documentation, making it easier to get support and find resources.

Frequently Asked Questions

What is TypeORM used for?

TypeORM is used to manage database operations in TypeScript and JavaScript applications. It simplifies tasks like creating, reading, updating, and deleting records, handling relationships, and managing schema migrations by mapping database tables to TypeScript classes.

What is TypeORM in NestJS?

In NestJS, TypeORM is the primary ORM used to handle database interactions. It seamlessly integrates with NestJS's modular structure, enabling developers to easily manage database entities, perform CRUD operations, and implement database migrations within the framework.

Is TypeORM a framework?

No, TypeORM is not a framework; it is an Object-Relational Mapper (ORM). It serves as a tool that simplifies database interactions by mapping database tables to TypeScript classes, but it is often used within frameworks like NestJS.

What is the difference between Sequelize and TypeORM?

The difference between Sequelize and TypeORM lies in language and usage; Sequelize is written in JavaScript and is more popular in Node.js, while TypeORM is TypeScript-first, providing type safety and better integration with TypeScript-based frameworks like NestJS.

Can TypeORM be used with SQL databases only?

No, TypeORM supports both SQL and NoSQL databases, although its functionality with NoSQL databases like MongoDB is more limited compared to SQL databases.

Is TypeORM suitable for large-scale applications?

Yes, TypeORM is suitable for both small and large-scale applications. Its ability to handle complex queries, relations, and migrations makes it a robust choice for enterprise-level applications.

Conclusion

TypeORM offers a powerful, efficient, and elegant way to interact with databases in TypeScript. By abstracting database interactions into familiar, object-oriented code, it significantly simplifies database management tasks. Whether you're building a small application or an enterprise-level system, TypeORM stands out as an essential tool in your development arsenal. This guide has provided a comprehensive overview of TypeORM, from setup and configuration to advanced features and best practices. By mastering TypeORM, developers can significantly enhance their productivity and the reliability of their applications.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass