Active Record 与 Data Mapper
什么是 Active Record 模式?
在 TypeORM 中你既可以使用 Active Record 模式,也可以使用 Data Mapper 模式。
使用 Active Record 方式时,你把所有查询方法都定义在模型本身内部,并通过模型方法来保存、移除和加载对象。
简单来说,Active Record 模式是一种在模型内部访问数据库的方式。你可以在 Wikipedia 上阅读更多关于 Active Record 模式的内容。
示例:
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
}所有 active-record 实体都必须继承 BaseEntity 类,它提供了操作该实体的方法。操作这类实体的示例:
// 保存 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" })BaseEntity 拥有标准 Repository 的大部分方法。大多数时候,你不需要对 active record 实体使用 Repository 或 EntityManager。
现在假设我们想创建一个按名和姓返回用户的函数。我们可以在 User 类中把这类函数创建为静态方法:
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()
}
}然后像其他方法一样使用它:
const timber = await User.findByName("Timber", "Saw")什么是 Data Mapper 模式?
在 TypeORM 中你既可以使用 Active Record 模式,也可以使用 Data Mapper 模式。
使用 Data Mapper 方式时,你把所有查询方法定义在称为"repository"的独立类中,并通过 repository 来保存、移除和加载对象。在 data mapper 中你的实体非常"笨"——它们只定义自己的属性,可能带一些"哑"方法。
简单来说,data mapper 是一种在 repository 而非模型内部访问数据库的方式。你可以在 Wikipedia 上阅读更多关于 data mapper 的内容。
示例:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
isActive: boolean
}操作这类实体的示例:
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",
})要用自定义方法扩展标准 repository,请使用自定义仓储模式。
我该选哪一个?
决定权在你。两种策略各有优缺点。
做软件开发时我们始终应该记住的一件事是:我们要如何维护自己的应用。Data Mapper 方式有助于可维护性,在较大的应用中更有效。Active Record 方式则让事情保持简单,在较小的应用中表现良好。
What is the Active Record pattern?
In TypeORM you can use both the Active Record and the Data Mapper patterns.
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.
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.
Example:
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
}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:
// 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" })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.
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:
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()
}
}And use it just like other methods:
const timber = await User.findByName("Timber", "Saw")What is the Data Mapper pattern?
In TypeORM you can use both the Active Record and Data Mapper patterns.
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.
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.
Example:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
isActive: boolean
}Example of how to work with such entity:
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",
})In order to extend standard repository with custom methods, use custom repository pattern.
Which one should I choose?
The decision is up to you. Both strategies have their own cons and pros.
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.