11.3.2. Extended session and automatic versioning
Sessioninstance and its persistent instances that are used for the whole conversation are known as session-per-conversation. Hibernate checks instance versions at flush time, throwing an exception if concurrent modification is detected. It is up to the developer to catch and handle this exception. Common options are the opportunity for the user to merge changes or to restart the business conversation with non-stale data.
Sessionis disconnected from any underlying JDBC connection when waiting for user interaction. This approach is the most efficient in terms of database access. The application does not version check or reattach detached instances, nor does it have to reload instances in every database transaction.
// foo is an instance loaded earlier by the old session Transaction t = session.beginTransaction(); // Obtain a new JDBC connection, start transaction foo.setProperty("bar"); session.flush(); // Only for last transaction in conversation t.commit(); // Also return JDBC connection session.close(); // Only for last transaction in conversation
fooobject knows which
Sessionit was loaded in. Beginning a new database transaction on an old session obtains a new connection and resumes the session. Committing a database transaction disconnects a session from the JDBC connection and returns the connection to the pool. After reconnection, to force a version check on data you are not updating, you can call
LockMode.READon any objects that might have been updated by another transaction. You do not need to lock any data that you are updating. Usually you would set
FlushMode.MANUALon an extended
Session, so that only the last database transaction cycle is allowed to actually persist all modifications made in this conversation. Only this last database transaction will include the
flush()operation, and then
close()the session to end the conversation.
Sessionis too big to be stored during user think time (for example, an
HttpSessionshould be kept as small as possible). As the
Sessionis also the first-level cache and contains all loaded objects, we can probably use this strategy only for a few request/response cycles. Use a
Sessiononly for a single conversation as it will soon have stale data.
Session. These methods are deprecated, as beginning and ending a transaction has the same effect.
Sessionclose to the persistence layer. Use an EJB stateful session bean to hold the
Sessionin a three-tier environment. Do not transfer it to the web layer, or even serialize it to a separate tier, to store it in the
CurrentSessionContextfor this. See the Hibernate Wiki for examples.