0

em.clear()我对 MikroOrm 或任何类似实体管理器中 的功能有点困惑。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 操作)甚至只读取数据?如果我不调用这个方法会发生什么?

4

2 回答 2

2

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

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

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

于 2020-09-08T06:27:26.530 回答
1

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();
于 2020-09-08T05:45:27.277 回答