Using EntityRepository instead of EntityManager
More convenient way of fetching entities from database is by using EntityRepository
, that
carries the entity name so you do not have to pass it to every find
and findOne
calls:
Example:
#
Custom Repositoryinfo
Since v4, we need to make sure we are working with correctly typed EntityRepository
to have access to driver specific methods (like createQueryBuilder()
). Use the one
exported from your driver package.
To use custom repository, just extend EntityRepository<T>
class:
You can also omit the @Repository
decorator and register your repository in @Entity
decorator instead:
Note that we need to pass that repository reference inside a callback so we will not run into circular dependency issues when using entity references inside that repository.
Now you can access your custom repository via em.getRepository()
method.
#
Inferring custom repository typeTo have the em.getRepository()
method return correctly typed custom repository
instead of the generic EntityRepository<T>
, we can use EntityRepositoryType
symbol:
You can also register custom base repository (for all entities where you do not specify
customRepository
) globally, viaMikroORM.init({ entityRepository: CustomBaseRepository })
.
Note that you cannot use both
@Repository(Author)
on the repository and{ customRepository: () => AuthorRepository }
on the entity at the same time. This will cause a circular dependency and throws an error. Either one of options achieves the same goal.
For more examples, take a look at
tests/EntityManager.mongo.test.ts
or tests/EntityManager.mysql.test.ts
.