Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Hibernate will intelligently cache objects in the current Hibernate Session, allowing for optimized performance.  Each Hibernate Session opens a single database connection when it is created, and holds onto it until the session is closed.  A Session may consist of one or more Transactions.

In DSpace, the Hibernate Session (and its Transactions)  The Hibernate Session is managed by the HibernateDBConnection object. (NOTE: This object class is perhaps unfortunately named as it manages the process of obtaining a database connection from Hibernate, via a Session. It does not represent not represent a single database connection.)

The DSpace Context object has methods (like uncacheEntity() and reloadEntity()) which can manage this Hibernate Session Cache (via HibernateDBConnection).

Some care is needed to properly utilize the Hibernate cache.  Objects are loaded into the Session cache on access. Objects are not removed from the cache until one of the following occurs:

  • The Hibernate Session's Transaction is committed (e.g. via a call to Context.commit() or Context.complete())
  • The Hibernate Session's Transaction is rolled back (e.g. via a call to Context.abort())
  • The object is specifically "evicted" (i.e. uncached) from the Hibernate Session (e.g. via a call to Context.uncacheEntity())

Be aware, once an object is removed (detached) from the Session cache, it will need to be reloaded from the database before it can be used again!  This can be achieved via Context.reloadEntity() or by querying for the object again via its Service.

Development tips regarding Hibernate Session

A few tips on working with Hibernate Sessions (all gleaned from https://developer.atlassian.com/confdev/development-resources/confluence-architecture/hibernate-sessions-and-transaction-management-guidelines)

  • Hibernate sessions are not thread-safe
    • Therefore, any new DSpace code must ensure it is not attempting to share objects or Sessions between threads.
  • The more objects you load during the lifetime of a Session, the less efficient each query will be
    • So, be sure to use Context.commit() or Context.uncacheEntity() when you are done with an object
  • Because Hibernate has built-in Session caching, it is not recommended to cache objects elsewhere in your code.  If you must perform other caching, store UUIDs instead
    • Caching objects elsewhere is likely to result in a LazyInitializationException if the object (cached elsewhere) outlives its Session. See "Common Hibernate Error Messages" below.

Context Configurations

The DSpace Context Object can be constructed as a read-only context or a batch context.  This mode determines how hibernate will flush changes to the database.

...