【问题标题】:When to and why use em.clear() in MikroOrm何时以及为何在 MikroOrm 中使用 em.clear()
【发布时间】:2020-09-08 05:43:22
【问题描述】:

我对@9​​87654322@ 在 MikroOrm 或任何类似实体管理器中的作用有点困惑。 https://mikro-orm.io/docs/entity-manager clear() 方法的链接。

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

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

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

【问题讨论】:

    标签: entitymanager mikro-orm


    【解决方案1】:

    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 而不是使用一个。

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

    【讨论】:

    • 非常感谢,您的链接也帮助我理解了为什么在设置过程中需要RequestContext。虽然我知道你是 lib 创建者:p
    【解决方案2】:

    我们应该首先描述两种方法来了解 MikroORM 中持久化的工作原理:em.persist()em.flush()

    em.persist(entity, flush?: boolean) 用于标记新实体以供将来持久化。它将使实体由给定的EntityManager 管理,并且一旦调用刷新,它将被写入数据库。第二个布尔参数可用于立即调用刷新。其默认值可通过autoFlush 选项进行配置。

    要了解flush,我们首先定义什么是托管实体:如果一个实体是从数据库中获取的(通过em.find()em.findOne() 或通过另一个托管实体),或者通过em.persist() 注册为新实体,那么它就是托管实体.

    em.flush() 将遍历所有托管实体,计算适当的更改集并执行相应的数据库查询。由于从数据库加载的实体会自动管理,因此您不必在这些实体上调用 persistflush 足以更新它们。

    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();
    

    【讨论】:

    • 这似乎与我的问题无关,但感谢您提供有关持久和刷新的一些信息。
    猜你喜欢
    • 2015-10-13
    • 2020-07-22
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    相关资源
    最近更新 更多