此内容没有您所选择的语言版本。
11.2.5. Common Issues
Do not use the anti-patterns session-per-user-session or session-per-application (there are, however, rare exceptions to this rule). Some of the following issues might also arise within the recommended patterns, so ensure that you understand the implications before making a design decision:
- A
Session
is not thread-safe. Things that work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if aSession
instance is shared. If you keep your HibernateSession
in yourHttpSession
(this is discussed later in the chapter), you should consider synchronizing access to your Http session. Otherwise, a user that clicks reload fast enough can use the sameSession
in two concurrently running threads. - An exception thrown by Hibernate means you have to rollback your database transaction and close the
Session
immediately (this is discussed in more detail later in the chapter). If yourSession
is bound to the application, you have to stop the application. Rolling back the database transaction does not put your business objects back into the state they were at the start of the transaction. This means that the database state and the business objects will be out of sync. Usually this is not a problem, because exceptions are not recoverable and you will have to start over after rollback anyway. - The
Session
caches every object that is in a persistent state (watched and checked for dirty state by Hibernate). If you keep it open for a long time or simply load too much data, it will grow endlessly until you get an OutOfMemoryException. One solution is to callclear()
andevict()
to manage theSession
cache, but you should consider a Stored Procedure if you need mass data operations. Some solutions are shown in the "Batch Processing" chapter. Keeping aSession
open for the duration of a user session also means a higher probability of stale data.