What are the core concepts of TypeORM? Detailed explanation of Entity, Repository, DataSource and other main components
TypeORM is an ORM framework based on TypeScript and JavaScript that uses both Active Record and Data Mapper design patterns, allowing developers to operate relational databases using an object-oriented approach.
Core Concepts
1. Entity
Entity is the core concept of TypeORM, corresponding to tables in the database. Each Entity class is marked with the @Entity() decorator and maps to a database table.
typescript@Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column({ unique: true }) email: string; @CreateDateColumn() createdAt: Date; @UpdateDateColumn() updatedAt: Date; }
2. Column
The Column decorator defines how entity properties map to database columns:
@Column(): Basic column definition@PrimaryGeneratedColumn(): Auto-increment primary key@CreateDateColumn(): Auto-create timestamp@UpdateDateColumn(): Auto-update timestamp@Generated(): Auto-generated value
3. Repository
Repository is the main interface for operating on entities, providing CRUD operations:
typescriptconst userRepository = dataSource.getRepository(User); // Create const user = userRepository.create({ name: 'John', email: 'john@example.com' }); await userRepository.save(user); // Query const users = await userRepository.find(); const user = await userRepository.findOne({ where: { id: 1 } }); // Update await userRepository.update(1, { name: 'John Updated' }); // Delete await userRepository.delete(1);
4. DataSource
DataSource is the configuration and management center for database connections:
typescriptconst dataSource = new DataSource({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'password', database: 'test', entities: [User], synchronize: true, });
5. Relation
TypeORM supports four main relationship types:
- One-to-One: Using
@OneToOne()decorator - One-to-Many: Using
@OneToMany()decorator - Many-to-One: Using
@ManyToOne()decorator - Many-to-Many: Using
@ManyToMany()decorator
typescript@Entity() export class Profile { @OneToOne(() => User, user => user.profile) user: User; } @Entity() export class User { @OneToOne(() => Profile, profile => profile.user) profile: Profile; @OneToMany(() => Post, post => post.author) posts: Post[]; }
Design Patterns
Active Record Pattern
In the Active Record pattern, entities themselves contain business logic and data access methods:
typescript@Entity() export class User extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column() name: string; static async findByName(name: string) { return this.find({ where: { name } }); } } // Usage const users = await User.findByName('John');
Data Mapper Pattern
In the Data Mapper pattern, data access logic is separated from entities, operating through Repository:
typescript@Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; } // Use Repository const userRepository = dataSource.getRepository(User); const users = await userRepository.find({ where: { name: 'John' } });
Key Features
- Type Safety: Full TypeScript support with compile-time type checking
- Decorator-Driven: Simplifies configuration using decorators
- Migration System: Supports database migration and version control
- Query Builder: Provides flexible query building API
- Transaction Support: Complete transaction management
- Caching Support: Built-in query caching mechanism
- Multi-Database Support: MySQL, PostgreSQL, SQLite, SQL Server, Oracle, etc.
These core concepts make TypeORM one of the most popular ORM frameworks in the Node.js ecosystem, particularly suitable for projects requiring type safety and object-oriented programming styles.