Active Record vs Data Mapper

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:

  1. import {BaseEntity, Entity, PrimaryGeneratedColumn, Column} from "typeorm";
  2. @Entity()
  3. export class User extends BaseEntity {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. @Column()
  11. isActive: boolean;
  12. }

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:

  1. // example how to save AR entity
  2. const user = new User();
  3. user.firstName = "Timber";
  4. user.lastName = "Saw";
  5. user.isActive = true;
  6. await user.save();
  7. // example how to remove AR entity
  8. await user.remove();
  9. // example how to load AR entities
  10. const users = await User.find({ skip: 2, take: 5 });
  11. const newUsers = await User.find({ isActive: true });
  12. const timber = await User.findOne({ 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:

  1. import {BaseEntity, Entity, PrimaryGeneratedColumn, Column} from "typeorm";
  2. @Entity()
  3. export class User extends BaseEntity {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. @Column()
  11. isActive: boolean;
  12. static findByName(firstName: string, lastName: string) {
  13. return this.createQueryBuilder("user")
  14. .where("user.firstName = :firstName", { firstName })
  15. .andWhere("user.lastName = :lastName", { lastName })
  16. .getMany();
  17. }
  18. }

And use it just like other methods:

  1. 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:

  1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. @Column()
  11. isActive: boolean;
  12. }

Example of how to work with such entity:

  1. const userRepository = connection.getRepository(User);
  2. // example how to save DM entity
  3. const user = new User();
  4. user.firstName = "Timber";
  5. user.lastName = "Saw";
  6. user.isActive = true;
  7. await userRepository.save(user);
  8. // example how to remove DM entity
  9. await userRepository.remove(user);
  10. // example how to load DM entities
  11. const users = await userRepository.find({ skip: 2, take: 5 });
  12. const newUsers = await userRepository.find({ isActive: true });
  13. const timber = await userRepository.findOne({ firstName: "Timber", lastName: "Saw" });

Now let’s say we want to create a function that returns users by first and last name.We can create such a function in a “custom repository”.

  1. import {EntityRepository, Repository} from "typeorm";
  2. import {User} from "../entity/User";
  3. @EntityRepository()
  4. export class UserRepository extends Repository<User> {
  5. findByName(firstName: string, lastName: string) {
  6. return this.createQueryBuilder("user")
  7. .where("user.firstName = :firstName", { firstName })
  8. .andWhere("user.lastName = :lastName", { lastName })
  9. .getMany();
  10. }
  11. }

And use it this way:

  1. const userRepository = connection.getCustomRepository(UserRepository);
  2. const timber = await userRepository.findByName("Timber", "Saw");

Learn more about custom repositories.

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 in with software development is how we are going to maintain our applications.The Data Mapper approach helps with maintainability, which is more effective in bigger apps.The Active record approach helps keep things simple which works well in smaller apps. And simplicity is always a key to better maintainability.