Search code examples
entitymanagermikro-orm

When to and why use em.clear() in MikroOrm


I am a little bit confuse about what em.clear() does in MikroOrm or any similar entity Manager. https://mikro-orm.io/docs/entity-manager the link for clear() method.

I had seems some of stackoverflow answers regarding general EntityManager said I need to call clear() after every persist/remove and flush to avoid any memory issue.

To make this question more specific for my case, supposedly I build up a Graphql endpoint in my application. There are some general CRUD functions for users to call, each function will create a MikroOrm entity by utilizing some of MikroOrm function like findOne(), etc. to do some general CRUD operation on the database.

Does it mean I need to call clear() every time after persist/remove and flush (if there are some CUD operation) and even reading data only? And what happen if I don't call this method?


Solution

  • em.clear() is for testing purposes, so you can simulate multiple independent requests with single EM instance:

    const book1 = await em.findOne(Book, 1); // now book 1 will be loaded
    const book2 = await em.findOne(Book, 1); // as book 1 is already loaded, this won't query the db
    expect(book1).toBe(book2); // and we will get identity here
    em.clear(); // but when we clear the identity map
    const book3 = await em.findOne(Book, 1); // this will query the db as the state is now gone
    expect(book1).not.toBe(book3); // and identity is gone
    

    You could achieve the same by using em.fork(), having multiple EMs instead of using one.

    The memory should be freed automatically during garbage collection, you should not need the em.clear() method in regular (app) code. Your application code should be using either RequestContext helper or manual forking (see https://mikro-orm.io/docs/identity-map). After the request finishes, there should be no reference to this old context and it should be garbage collected (but keep in mind this happens indeterministically, e.g. when JS engine feels like it :]).