Reputation: 15
This is just an insert to db at the end of a transaction. Is there any point in using 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;
}
Upvotes: 1
Views: 4517
Reputation: 24492
Since you are in a @Transactional
scope, the changes are sent to the database but are not actually committed until Spring's transaction interceptor commits the local transaction. In that scenario you could remove it.
The following entry explains the uses of 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.
Upvotes: 4