【问题标题】:entityManager.flush does not insert to database immediately, why?entityManager.flush 没有立即插入数据库,为什么?
【发布时间】:2020-07-13 01:58:37
【问题描述】:

这只是在事务结束时对 db 的插入。使用entityManager.flush() 有什么意义吗?

@Transactional
public long saveNewWallet(String name) {
    Wallet emptyWallet = new Wallet();
    emptyWallet.setAmount(new BigDecimal(2.00));
    entityManager.persist(emptyWallet);
    entityManager.flush();
    return 5;
}

【问题讨论】:

    标签: java spring hibernate jpa entitymanager


    【解决方案1】:

    由于您处于@Transactional 范围内,因此更改会发送到数据库,但在 Spring 的事务拦截器提交本地事务之前不会真正提交。在那种情况下,您可以将其删除。

    以下条目解释了EntityManager.flush()的用法:https://en.wikibooks.org/wiki/Java_Persistence/Persisting

    冲洗

    EntityManager.flush() 操作可用于写入所有更改 在事务提交之前到数据库。默认情况下 JPA 在事务处理之前通常不会将更改写入数据库 承诺。这通常是可取的,因为它避免了数据库访问, 资源和锁,直到需要为止。它还允许数据库写入 订购和批处理以获得最佳的数据库访问,并维护 完整性约束和避免死锁。这意味着当你 调用持久化、合并或删除数据库 DML INSERT、UPDATE、DELETE 不会执行,直到提交或触发刷新。

    flush() 不执行实际的提交:提交仍然 在资源的情况下请求显式 commit() 时发生 本地事务,或容器管理 (JTA) 事务 完成。

    Flush 有几种用法:

    Flush changes before a query execution to enable the query to return new objects and changes made in the persistence unit.
    Insert persisted objects to ensure their Ids are assigned and accessible to the application if using IDENTITY sequencing.
    Write all changes to the database to allow error handling of any database errors (useful when using JTA or SessionBeans).
    To flush and clear a batch for batch processing in a single transaction.
    Avoid constraint errors, or reincarnate an object.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多