首页 > 解决方案 > entityManager.flush 没有立即插入数据库,为什么?

问题描述

这只是事务结束时对 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;
}

标签: javaspringhibernatejpaentitymanager

解决方案


由于您在@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.

推荐阅读