Both patterns solve the problem of connecting applications with data storage, the both follow different philosophies.
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();
- Simple
- Intuitive
- No single responsibility
- Hight coupling
- Object relation implicance
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);
- sep of concern
- more flexible
- tough to understand
Depends of:
- Type of application
- Business complexity
More complex use Data Mapper. More simple use Active Record.