The Hibernate Session implements transparent write behind. Changes to the domain
model made in the scope of a Session aren’t immediately propagated to the database.
This allows Hibernate to coalesce many changes into a minimal number of
database requests, helping minimize the impact of network latency.
For example, if a single property of an object is changed twice in the same
Transaction, Hibernate only needs to execute one SQL UPDATE. Another example
of the usefulness of transparent write behind is that Hibernate can take
advantage of the JDBC batch API when executing multiple UPDATE, INSERT, or
DELETE statements.
Hibernate flushes occur only at the following times:
■ When a Transaction is committed
■ Sometimes before a query is executed
■ When the application calls Session.flush() explicitly
Flushing the Session state to the database at the end of a database transaction is
required in order to make the changes durable and is the common case. Hibernate
doesn’t flush before every query. However, if there are changes held in memory that
would affect the results of the query, Hibernate will, by default, synchronize first.
You can control this behavior by explicitly setting the Hibernate FlushMode via a
call to session.setFlushMode(). The flush modes are as follows:
■ FlushMode.AUTO—The default. Enables the behavior just described.
■ FlushMode.COMMIT—Specifies that the session won’t be flushed before query
execution (it will be flushed only at the end of the database transaction). Be
aware that this setting may expose you to stale data: modifications you made
to objects only in memory may conflict with the results of the query.
■ FlushMode.NEVER—Lets you specify that only explicit calls to flush() result
in synchronization of session state with the database.
We don’t recommend that you change this setting from the default.(OpenSessionInview需要仔细考虑) It’s provided
to allow performance optimization in rare cases. Likewise, most applications rarely
need to call flush() explicitly. This functionality is useful when you’re working
with triggers, mixing Hibernate with direct JDBC, or working with buggy JDBC drivers.
You should be aware of the option but not necessarily look out for use cases.
Now that you understand the basic usage of database transactions with the
Hibernate Transaction interface, let’s turn our attention more closely to the subject
of concurrent data access.
It seems as though you shouldn’t have to care about transaction isolation—the
term implies that something either is or is not isolated. This is misleading. Complete
isolation of concurrent transactions is extremely expensive in terms of application
scalability, so databases provide several degrees of isolation. For most applications,
incomplete transaction isolation is acceptable. It’s important to understand the
degree of isolation you should choose for an application that uses Hibernate and
how Hibernate integrates with the transaction capabilities of the database.