何时以及为何在 MikroOrm 中使用 em.clear()

Yun*_*hai 2 entitymanager mikro-orm

我对 MikroOrm 或任何类似实体管理器中的功能有点困惑em.clear()https://mikro-orm.io/docs/entity-manager方法的链接clear()

我似乎有一些关于一般 EntityManager 的 stackoverflow 答案说我需要clear()在每次调用后调用persist/remove and flush以避免任何内存问题。

为了使这个问题更具体地适合我的情况,据说我在我的应用程序中建立了一个Graphql端点。有一些通用的 CRUD 函数供用户调用,每个函数都会MikroOrm entity利用一些 MikroOrm 函数(例如findOne()等)创建一个对数据库进行一些通用 CRUD 操作的函数。

这是否意味着我需要clear()每次调用persist/remove and flush(如果有一些 CUD 操作)甚至仅读取数据?如果我不调用这个方法会发生什么?

Mar*_*mek 5

em.clear()用于测试目的,因此您可以使用单个 EM 实例模拟多个独立请求:

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
Run Code Online (Sandbox Code Playgroud)

您可以通过使用 来实现相同的效果em.fork(),即使用多个 EM 而不是使用一个。

内存应该在垃圾收集期间自动释放,您不应该em.clear()在常规(应用程序)代码中需要该方法。您的应用程序代码应该使用RequestContext帮助程序或手动分叉(请参阅https://mikro-orm.io/docs/identity-map)。请求完成后,不应该再引用这个旧的上下文,并且应该对其进行垃圾收集(但请记住,这种情况的发生是不确定的,例如,当 JS 引擎感觉像这样时:])。