When we are updating a record, we can use session.flush()
with Hibernate. What\'s the need for flush()
?
You might use flush
to force validation constraints to be realised and detected in a known place rather than when the transaction is committed. It may be that commit
gets called implicitly by some framework logic, through declarative logic, the container, or by a template. In this case, any exception thrown may be difficult to catch and handle (it could be too high in the code).
For example, if you save()
a new EmailAddress object, which has a unique constraint on the address, you won't get an error until you commit.
Calling flush()
forces the row to be inserted, throwing an Exception if there is a duplicate.
However, you will have to roll back the session after the exception.