advanced

Entity manager

Use the entity manager as the scoped persistence gateway for finding, persisting, flushing, and transaction orchestration.

The entity manager is the scoped gateway for `find`, `persist`, `remove`, `flush`, and transactions. In MikroORM it is tied to the identity map and request context—fork per request in web apps.

					const em = orm.em.fork();
await em.transactional(async (tx) => {
  const user = await tx.findOne(User, { id });
  tx.assign(user, { name: 'Ada' });
});
				

On interviews: forked entity managers, `RequestContext`, transactions, repositories as thin helpers, avoiding cross-request reuse.

Common pitfalls: global manager mixing identity maps between users; repository calls outside the active transaction fork.

The trade-off is ergonomic persistence API versus strict per-request isolation.

Checklist:

  • Fork or scope per request.
  • Coordinate transactions through the manager.
  • Keep repository helpers thin and explicit.
  • Pass transactional EM into services.