entityManager.flush没有立即插入数据库,为什么?

问题描述 投票:0回答:1

这只是在事务结束时插入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个回答
0
投票

由于您处于@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.
© www.soinside.com 2019 - 2024. All rights reserved.