乐闻世界logo
搜索文章和话题

TypeORM 的核心概念是什么?包括 Entity、Repository、DataSource 等主要组件的详细说明

2月18日 22:19

TypeORM 是一个基于 TypeScript 和 JavaScript 的 ORM 框架,它采用 Active Record 和 Data Mapper 两种设计模式,让开发者能够使用面向对象的方式来操作关系型数据库。

核心概念

1. Entity (实体)

Entity 是 TypeORM 的核心概念,它对应数据库中的表。每个 Entity 类都使用 @Entity() 装饰器标记,并映射到数据库表。

typescript
@Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column({ unique: true }) email: string; @CreateDateColumn() createdAt: Date; @UpdateDateColumn() updatedAt: Date; }

2. Column (列)

Column 装饰器用于定义实体属性如何映射到数据库列:

  • @Column(): 基本列定义
  • @PrimaryGeneratedColumn(): 自增主键
  • @CreateDateColumn(): 自动创建时间
  • @UpdateDateColumn(): 自动更新时间
  • @Generated(): 自动生成值

3. Repository (仓储)

Repository 是用于操作实体的主要接口,提供了 CRUD 操作:

typescript
const userRepository = dataSource.getRepository(User); // 创建 const user = userRepository.create({ name: 'John', email: 'john@example.com' }); await userRepository.save(user); // 查询 const users = await userRepository.find(); const user = await userRepository.findOne({ where: { id: 1 } }); // 更新 await userRepository.update(1, { name: 'John Updated' }); // 删除 await userRepository.delete(1);

4. DataSource (数据源)

DataSource 是数据库连接的配置和管理中心:

typescript
const dataSource = new DataSource({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'password', database: 'test', entities: [User], synchronize: true, });

5. Relation (关系)

TypeORM 支持四种主要的关系类型:

  • One-to-One (一对一): 使用 @OneToOne() 装饰器
  • One-to-Many (一对多): 使用 @OneToMany() 装饰器
  • Many-to-One (多对一): 使用 @ManyToOne() 装饰器
  • Many-to-Many (多对多): 使用 @ManyToMany() 装饰器
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[]; }

设计模式

Active Record 模式

在 Active Record 模式中,实体本身包含业务逻辑和数据访问方法:

typescript
@Entity() export class User extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column() name: string; static async findByName(name: string) { return this.find({ where: { name } }); } } // 使用 const users = await User.findByName('John');

Data Mapper 模式

在 Data Mapper 模式中,数据访问逻辑与实体分离,通过 Repository 操作:

typescript
@Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; } // 使用 Repository const userRepository = dataSource.getRepository(User); const users = await userRepository.find({ where: { name: 'John' } });

关键特性

  1. 类型安全: 完全支持 TypeScript,提供编译时类型检查
  2. 装饰器驱动: 使用装饰器简化配置
  3. 迁移系统: 支持数据库迁移和版本控制
  4. 查询构建器: 提供灵活的查询构建 API
  5. 事务支持: 完整的事务管理
  6. 缓存支持: 内置查询缓存机制
  7. 多数据库支持: MySQL, PostgreSQL, SQLite, SQL Server, Oracle 等

TypeORM 的这些核心概念使其成为 Node.js 生态中最流行的 ORM 框架之一,特别适合需要类型安全和面向对象编程风格的项目。

标签:TypeORM