java - 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;
}
解决方案
由于您在@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.
推荐阅读
- c++ - 在 c++ 的 SetWindowsHookEx 函数中
- css - 使用 CSS 动画触发第二个动画关键帧(或永久移动 div)?
- javascript - 为什么图像没有显示在我的 html 中?
- firebase - Firestore:有没有一种无需阅读即可遍历 document_ID 的方法?
- hyperledger-fabric - Fabric 通道创建/通道/应用程序错误:此策略需要满足 1 个“管理员”子策略
- r - 按组完成具有新值的data.frame
- asp.net-core - 如何在 asp.net core 启动中访问配置提供程序值
- android - 如何将两个值从 android 中的 bluetoothSPP 发送到 arduino?
- javascript - 在 javascript 中,“var”与任何名为“name”的对象的行为都不同,它将对象记录为 [object Object]。为什么会这样?
- python - 使用 OpenCV 时如何在 NN 中使用 keras Lambda