There are 2 methods we should first describe to understand how persisting works in MikroORM: em.persist()
and em.flush()
.
em.persist(entity, flush?: boolean)
is used to mark new entities for future persisting. It will make the entity managed by given EntityManager
and once flush is called, it will be written to the database. The second boolean parameter can be used to invoke the flush immediately. Its default value is configurable via autoFlush
option.
To understand flush
, lets first define what managed entity is: an entity is managed if it’s fetched from the database (via em.find()
, em.findOne()
or via another managed entity) or registered as new through em.persist()
.
em.flush()
will go through all managed entities, compute appropriate change sets and perform according database queries. As an entity loaded from the database becomes managed automatically, you do not have to call persist
on those, and flush
is enough to update them.
const book = await orm.em.findOne(Book, 1);
book.title = 'How to persist things...';
// no need to persist `book` as its already managed by the EM
await orm.em.flush();