Ashok Kumar
Ashok Kumar

Reputation: 334

What is EntityManager, EntityRepository in mikro-orm and difference between that?

Please explain in very simple language with proper example, I have already followed official document but I did not understand clearly.

Upvotes: 1

Views: 961

Answers (1)

Rasool Khan
Rasool Khan

Reputation: 531

EntityRepository is a convenient way of accessing entities from a database since it handles a single entity, it carries the entity name so we don't have to pass it in find(), findAll() calls.

Example:

import { EntityRepository } from '@mikro-orm/postgresql';
import { User } from './entities/user.entity';

@Injectable()
export class UserService {
    constructor(
      @InjectRepository(User)
      private readonly userRepository: EntityRepository<User>,
    ) {}

    async getUserByPhone(phone: string) {
      return await this.userRepository.findOne({ phone }); //we are not passing any entity here while making a database call.
    }
}

Whereas, EntityManager handles all entities. That's why when using find() and findAll() calls we need to mention which entity we want to access.

Example:

return await orm.em.findOne(User, { phone: phoneNumber }); //we have to pass User entity here while making a database call.

Upvotes: 4

Related Questions