TypeORM

What is TypeORM

TypeORM (object-relations-management ) is a tools and it is used with TypeScript.

I am going to use Ts.ED and database PostgreSQL So, this article will helpful who are going to useTs.ED.

In this post we’ll learn about using TypeORM.

How to Install and configure

npm install --save @tsed/typeorm
npm install --save typeorm
npm install pg --save

TypeScript configuration

Enable the following settings in tsconfig.json:

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

database connection configuration options are follows:

const rootDir = __dirname;

....
typeorm: [
    {
        name: "default",
        type: "postgres",
        port: 5432,
        host: "localhost",
        database: "yourDatabase",
        password: 'yourPassword',
        entities: [
            `${rootDir}/entities/*.ts`
        ],
        synchronize: true,
        logging: true
    }

 

Entity

import {
  Column,
  Entity,
  PrimaryGeneratedColumn
} from 'typeorm';

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

  @Column()
  firstName: string;

  @Column()
  lastName: string;

}
import {
  Column,
  Entity,
  PrimaryGeneratedColumn
} from 'typeorm';

@Entity('users')
export class User {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

}

Entity is a class that maps to a database table. You can create an entity by defining a new class and mark it with @Entity() see above example. 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.

Entity Column

Basic entities consist of columns and relations. Each entity class property you marked with @Column will be mapped to a database table column. Each entity MUST have a primary column. 

There are several types of primary columns:

  • @PrimaryColumn()
  • @PrimaryGeneratedColumn()
  • @PrimaryGeneratedColumn(“uuid”)
  • Composite primary columns
@Entity('users')
export class User {

  @PrimaryColumn()
  firstName: string;

  @PrimaryColumn()
  lastName: string;

  @Column()
  address: string;
}

Special columns

There are several special column types

  • @CreateDateColumn
  • @UpdateDateColumn
  • @VersionColumn

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

What is Repository

Repository is just like EntityManager but its operations are limited to a concrete entity.

You can access repository via getRepository(Entity)Connection#getRepository, or EntityManager#getRepository. Example:

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

const userRepository = getRepository(User); // you can also get it via getConnection().getRepository() or getManager().getRepository()
const user = await userRepository.findOne(1);
user.name = "Umed";
await userRepository.save(user);

There are 3 types of repositories:

  • Repository – Regular repository for any entity.
  • TreeRepository – Repository, extensions of Repository used for tree-entities (like entities marked with @Tree decorator). Has special methods to work with tree structures.
  • MongoRepository – Repository with special functions used only with MongoDB.

More detail about TypeORM click here

You May Also Like

About the Author: Md. Delwar Hossain

He has 11 years of experience in developing standalone software and web applications for multiple database platforms. He has been passionate about new tools and technologies. He is positive and trustworthy. He is capable to learn and adapt quickly to different situations. He is a great team player and enjoys leading and mentoring. He is specialized in architecting and building complex web and mobile application. He has strong skills to automate POS, inventory, supply chain, trading export/ import, human resource management, manufacturing and production, distribution management system and hospital management system.

Leave a Reply

Your email address will not be published. Required fields are marked *