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

entityManager.flush does not insert to database immediately, why?

这只是在事务结束时插入数据库。使用 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

Flush

The EntityManager.flush() operation can be used to write all changes to the database before the transaction is committed. By default JPA does not normally write changes to the database until the transaction is committed. This is normally desirable as it avoids database access, resources and locks until required. It also allows database writes to be ordered, and batched for optimal database access, and to maintain integrity constraints and avoid deadlocks. This means that when you call persist, merge, or remove the database DML INSERT, UPDATE, DELETE is not executed, until commit, or until a flush is triggered.

The flush() does not execute the actual commit: the commit still happens when an explicit commit() is requested in case of resource local transactions, or when a container managed (JTA) transaction completes.

Flush has several usages:

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.