# Active Record 与 Data Mapper

> 英文标题：Active Record vs Data Mapper
> 官网原文：https://typeorm.io/docs/guides/active-record-data-mapper
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 26 块

---

<!-- EN -->
# Active Record vs Data Mapper

<!-- ZH -->
# Active Record 与 Data Mapper

<!-- EN -->
## What is the Active Record pattern?

<!-- ZH -->
## 什么是 Active Record 模式？

<!-- EN -->
In TypeORM you can use both the Active Record and the Data Mapper patterns.

<!-- ZH -->
在 TypeORM 中你既可以使用 Active Record 模式，也可以使用 Data Mapper 模式。

<!-- EN -->
Using the Active Record approach, you define all your query methods inside the model itself, and you save, remove, and load objects using model methods.

<!-- ZH -->
使用 Active Record 方式时，你把所有查询方法都定义在模型本身内部，并通过模型方法来保存、移除和加载对象。

<!-- EN -->
Simply said, the Active Record pattern is an approach to access your database within your models. You can read more about the Active Record pattern on [Wikipedia](https://en.wikipedia.org/wiki/Active_record_pattern).

<!-- ZH -->
简单来说，Active Record 模式是一种在模型内部访问数据库的方式。你可以在 [Wikipedia](https://en.wikipedia.org/wiki/Active_record_pattern) 上阅读更多关于 Active Record 模式的内容。

<!-- EN -->
Example:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean
}
```

<!-- ZH -->
```typescript
import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean
}
```

<!-- EN -->
All active-record entities must extend the `BaseEntity` class, which provides methods to work with the entity. Example of how to work with such entity:

<!-- ZH -->
所有 active-record 实体都必须继承 `BaseEntity` 类，它提供了操作该实体的方法。操作这类实体的示例：

<!-- EN -->
```typescript
// example how to save AR entity
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.isActive = true
await user.save()

// example how to remove AR entity
await user.remove()

// example how to load AR entities
const users = await User.find({ skip: 2, take: 5 })
const newUsers = await User.findBy({ isActive: true })
const timber = await User.findOneBy({ firstName: "Timber", lastName: "Saw" })
```

<!-- ZH -->
```typescript
// 保存 AR 实体的示例
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.isActive = true
await user.save()

// 移除 AR 实体的示例
await user.remove()

// 加载 AR 实体的示例
const users = await User.find({ skip: 2, take: 5 })
const newUsers = await User.findBy({ isActive: true })
const timber = await User.findOneBy({ firstName: "Timber", lastName: "Saw" })
```

<!-- EN -->
`BaseEntity` has most of the methods of the standard `Repository`. Most of the time you don't need to use `Repository` or `EntityManager` with active record entities.

<!-- ZH -->
`BaseEntity` 拥有标准 `Repository` 的大部分方法。大多数时候，你不需要对 active record 实体使用 `Repository` 或 `EntityManager`。

<!-- EN -->
Now let's say we want to create a function that returns users by first and last name. We can create such functions as a static method in a `User` class:

<!-- ZH -->
现在假设我们想创建一个按名和姓返回用户的函数。我们可以在 `User` 类中把这类函数创建为静态方法：

<!-- EN -->
```typescript
import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean

    static findByName(firstName: string, lastName: string) {
        return this.createQueryBuilder("user")
            .where("user.firstName = :firstName", { firstName })
            .andWhere("user.lastName = :lastName", { lastName })
            .getMany()
    }
}
```

<!-- ZH -->
```typescript
import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean

    static findByName(firstName: string, lastName: string) {
        return this.createQueryBuilder("user")
            .where("user.firstName = :firstName", { firstName })
            .andWhere("user.lastName = :lastName", { lastName })
            .getMany()
    }
}
```

<!-- EN -->
And use it just like other methods:

<!-- ZH -->
然后像其他方法一样使用它：

<!-- EN -->
```typescript
const timber = await User.findByName("Timber", "Saw")
```

<!-- ZH -->
```typescript
const timber = await User.findByName("Timber", "Saw")
```

<!-- EN -->
## What is the Data Mapper pattern?

<!-- ZH -->
## 什么是 Data Mapper 模式？

<!-- EN -->
In TypeORM you can use both the Active Record and Data Mapper patterns.

<!-- ZH -->
在 TypeORM 中你既可以使用 Active Record 模式，也可以使用 Data Mapper 模式。

<!-- EN -->
Using the Data Mapper approach, you define all your query methods in separate classes called "repositories", and you save, remove, and load objects using repositories. In data mapper your entities are very dumb - they just define their properties and may have some "dummy" methods.

<!-- ZH -->
使用 Data Mapper 方式时，你把所有查询方法定义在称为"repository"的独立类中，并通过 repository 来保存、移除和加载对象。在 data mapper 中你的实体非常"笨"——它们只定义自己的属性，可能带一些"哑"方法。

<!-- EN -->
Simply said, data mapper is an approach to access your database within repositories instead of models. You can read more about data mapper on [Wikipedia](https://en.wikipedia.org/wiki/Data_mapper_pattern).

<!-- ZH -->
简单来说，data mapper 是一种在 repository 而非模型内部访问数据库的方式。你可以在 [Wikipedia](https://en.wikipedia.org/wiki/Data_mapper_pattern) 上阅读更多关于 data mapper 的内容。

<!-- EN -->
Example:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

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

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

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

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean
}
```

<!-- EN -->
Example of how to work with such entity:

<!-- ZH -->
操作这类实体的示例：

<!-- EN -->
```typescript
const userRepository = dataSource.getRepository(User)

// example how to save DM entity
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.isActive = true
await userRepository.save(user)

// example how to remove DM entity
await userRepository.remove(user)

// example how to load DM entities
const users = await userRepository.find({ skip: 2, take: 5 })
const newUsers = await userRepository.findBy({ isActive: true })
const timber = await userRepository.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- ZH -->
```typescript
const userRepository = dataSource.getRepository(User)

// 保存 DM 实体的示例
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.isActive = true
await userRepository.save(user)

// 移除 DM 实体的示例
await userRepository.remove(user)

// 加载 DM 实体的示例
const users = await userRepository.find({ skip: 2, take: 5 })
const newUsers = await userRepository.findBy({ isActive: true })
const timber = await userRepository.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- EN -->
In order to extend standard repository with custom methods, use [custom repository pattern](https://typeorm.io/docs/working-with-entity-manager/custom-repository).

<!-- ZH -->
要用自定义方法扩展标准 repository，请使用[自定义仓储模式](https://typeorm.io/docs/working-with-entity-manager/custom-repository)。

<!-- EN -->
## Which one should I choose?

<!-- ZH -->
## 我该选哪一个？

<!-- EN -->
The decision is up to you. Both strategies have their own cons and pros.

<!-- ZH -->
决定权在你。两种策略各有优缺点。

<!-- EN -->
One thing we should always keep in mind with software development is how we are going to maintain our applications. The `Data Mapper` approach helps with maintainability, which is more effective in larger apps. The `Active Record` approach helps keep things simple which works well in smaller apps.

<!-- ZH -->
做软件开发时我们始终应该记住的一件事是：我们要如何维护自己的应用。`Data Mapper` 方式有助于可维护性，在较大的应用中更有效。`Active Record` 方式则让事情保持简单，在较小的应用中表现良好。
