Skip to content

Instantly share code, notes, and snippets.

@denilsonpy
Last active October 19, 2022 15:57
Show Gist options
  • Save denilsonpy/18d41afa755489b404d6969dab880c08 to your computer and use it in GitHub Desktop.
Save denilsonpy/18d41afa755489b404d6969dab880c08 to your computer and use it in GitHub Desktop.
Active Record vs Data Mapper

Active Record vs Data Mapper

Both patterns solve the problem of connecting applications with data storage, the both follow different philosophies.

Active Record

We define all the query methods for acessing the data within the model class itself (create, update, delete...).

// entity
import { Entity, Column, BaseEntity, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class Flight extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: string;
    
    @Column()
    source: string
    
    @Column()
    destination: string
}

// method
const flight = new Flight();


flight.source = "LAX";
flight.destination = "BRA";

await flight.save();

const flights = await Flight.find();
await flight.remove();

Advantages

  • Simple
  • Intuitive

Disadvantages

  • No single responsibility
  • Hight coupling
  • Object relation implicance

Data mapper

Also know as repository pattern, the query methods are kept is a separate class known as repositories basically in the data mapper pattern entities have no logic, dealing with the data is within the repository classes.

// entity
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class Flight {
    @PrimaryGeneratedColumn()
    id: string;
    
    @Column()
    source: string
    
    @Column()
    destination: string
}

// method
const flightRepository = AppDataSource.getRepository(Flight);

await flightRepository.save(flight);

Advantages

  • sep of concern
  • more flexible

Disadvantages

  • tough to understand

Which one use?

Depends of:

  • Type of application
  • Business complexity

More complex use Data Mapper. More simple use Active Record.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment