Hibernate Quick Start |
rate-7766418-97341
| Article Rating? |
|
|
|
Overview
This guide covers getting started with Hibernate and Terracotta. It assumes you already have an application written with Hibernate.
If you are looking to get started with Terracotta, please review the following guides:
Watch the Webcast
If you are already familiar with Terracotta, and would like to research how it can help you with a Hibernate enabled application, you can start by watching the Terracotta Hibernate Webcast.
To do so, visit the Online Training area, and select the Hibernate Webcast. In this webcast, you will learn:
- How Terracotta helps Hibernate Applications
- See a demonstration application in action
- Learn how to enable 2nd Level Object and Query Caching
- Learn how to enable detached mode with Terracotta for even better performance
After watching the Webcast, you may also browse the source code:
Requirements
Terracotta for Hibernate requires the following:
- Latest version of Terracotta
- [Supported Platform] such as Microsoft Windows, Linux, or Solaris
- [Supported JVM] such as Sun Hotspot 1.4, 1.5, or 1.6 and/or IBM JDK 1.5
- Hibernate
Version 3.1.2
- (Optional) EHCache
Version 1.2.4 (as a second level cache)
- (Optional) EHCache
Version 1.3 (as a second level cache)
First steps
To get started with Terracotta for Hibernate, you must download and install Terracotta.
Then you must decide what kind of integration you would like to add. There are two main integration points where Terracotta can help your Hibernate application.
These integration points are:
- Provide a high performance, replicated 2nd Level Cache
- Provide high availability and scale for detached mode objects
Installing Terracotta
To install Terracotta, follow these steps:
- Download Terracotta
- If you are on Windows, execute the installer
- For all other platforms, untar/unzip the downloaded file into the directory of your choosing
When you are done, Terracotta will be installed onto your machine. If you are on Windows, it will be installed, by default, into C:\Program Files\Terracotta[Terracotta Version]. From now on, we will refer to the Terracotta installation directory as $TC_HOME.
To aid in starting Terracotta, you may want to set an environment variable that points to the Terracotta installation directory called $TC_HOME.
For a more thorough guide on downloading, installing, and trying out Terracotta sample programs, read the Getting Started Using Terracotta Guide
Using either 2nd Level Cache or Detached Objects
Each of these modes is explained in further detail
2nd Level Cache
Hibernate offers a 2nd level cache option, which can improve the performance of your Hibernate application by eliminating the need to fetch often used data objects from the database, instead storing, or caching, that data in process with your application.
This strategy is explained in more detail on the Hibernate.org website: Performance Tuning
The problem with a 2nd level cache in a scaled-out application, where there are more than one node in the system using a 2nd level cache, is that of data freshness.
Without any mechanism to provide replication of the underlying cache, data written in one node can be stale on another node. Because the 2nd node has no way of knowing that the database data has changed due to the change made by node 1, then the data returned by node 2 can be stale, or out of date.
This problem is not solved by Hibernate, rather it is up to the underlying cache to provide a replication scheme to keep mutliple copies synchronized. Terracotta provides a consistent mechanism to keep any cache written in Java synchronized, and therefore provides this support for caches such as EHCache.
The advantages to use Terracotta, as opposed to the native clustering or replication mode provided by the the underlying 2nd level cache technology are the same as those that Terracotta provides in all distributed caching use cases.
In particular, these advantages are:
- Performance - reading and writing to replicated data with Terracotta can be 10x - 100x faster than other solutions
- Reliability - Terracotta provides a parallel path to disk, meaning the data is simultaneously durable and persistent
- Scalable - Because Terracotta does not use Serialization for data transfer, its use of the network and memory subsystem in Java is significantly more efficient, and therefore offers much more scalability than traditional solutions.
- Virtual Heap - Terracotta provides an automatic virtual heap, which allows the distributed cache to provide a significantly larger data size than can be provided by a single JVM. For large datasets, this is especially important as it allows the cache to adapt to the "hotset" of the data in the cache.
- Cluster wide load - replication of data eliminates the need for more than one node to load data from the database. In a scaled-out application, this can reduce database load b a significant factor due to the fact that only one node need request any piece of data for a cache miss and all subsequent requests on other nodes will result in cache hits.
Fore more details on these advantages and more, please read the Distributed Caches section of the Terracotta site.
Detached Instance Object Caching
Hibernate supports the notion of "detached instances"
- which are simply POJOs retreived from an active session that have been detached from the session - and thus can live past the lifetime of the session. As detached instances they behave just like normal POJOs - until reconnected to a new session. When reconnected to the new session, any changes to the POJO state made while disconnected are "merged" back into the session, and flushed to the database when the session is committed.
Using detached instances can provide a significant performance improvement. Instead of having to go to the database, you application has direct access to the data it needs, eliminating latency and improving throughput.
In essence, detached instances provide your application with memory speed read and writes. The Hibernate documentation states it this way, "[detached instances] enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e. a unit of work from the point of view of the user.
The drawback to using detached instances, of course, is that any changes written to the instance are by definition not persisted to the database, and in a scaled-out application, this means a failure of the system hosting the detached instance means a loss of data.
However, using Terracotta to replicate detached instances, it is possible to gain the speed and throughput of in memory read speed, nearly-in memory write speed, and ensure that instance data is highly available and not susceptible to loss in the event of a system failure.
Managing detached instances is really no more complicated than managing POJOs. Therefore, any design technique using Terracotta and POJOs will be applicable to Hibernate detached instances. Common methods of making Hibernate detached instances persistent are:
One more thing - the use of 2nd Level caching and detached instance caching are not mutually exclusive. It is certainly possible to mix the two depending on your application needs!
How to configure Terracotta for 2nd Level Caching
To enable Terracotta 2nd level cache integration, you must use EHCache as a second level cache for Hibernate, then you must configure Terracotta for Hibernate and for EHCache. These steps are:
- Step 1: Create an EHCache configuration
- Step 2: Configure Hibernate for 2nd Level Cache
- Step 3: Configure Terracotta for Hibernate and EHCache
Note: If you already have EHCache enabled as a 2nd level cache, you can skip Steps 1 and 2.
Step 1: Create an EHCache configuration
First, you must create an EHCache configuration. Details of this process are outside the scope of this document, for more information on this process, please visit the EHCache website
Here is a basic EHCache configuration file that should help you get started:
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="300"
timeToLiveSeconds="300"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<cache name="..." ... />
</ehcache>
 |
Note that you will have to specify your own cache name. |
Step 2: Configure Hibernate for 2nd Level Cache
Next, you must enable EHCache as a 2nd Level Cache for Hibernate. To do so, modify your hibernate.xml file. Details of this process are outside the scope of this documentation. For more information on this process, please visit the Hibernate webiste
.
A recommended set of configuration settings for the hibernate.xml follows:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
These settings enable 2nd level caching, and also query caching.
Step 3: Configure Terracotta for Hibernate and EHCache
Now, you must enable a number of Terracotta Integration Modules (TIMs for short) in your tc-config.xml.
The TIMs you must enable are:
<clients>
<modules>
<module name="tim-hibernate-3.1.2" version="1.1.2"/>
<module name="tim-ehcache-1.2.4" version="1.1.2"/>
</modules>
</clients>
 |
Note that if you are using EHCache version 1.3, then you must use the "tim-ehcache-1.3" TIM in place of "tim-ehcache-1.2.4". |
How to Configure Terracotta for Hibernate Detached Instances
To enable Terracotta for detached instances, simply add the Hibernate TIM to your tc-config.xml, select the storage mechanism to put detached instances into, and use the detached instances like any standard POJO.
- Step 1: Choose where to put your detached instances
- Step 2: Configure Terracotta for Hibernate
- Step 3: Refactor to use POJOs and merge when necessary
Step 1: Choose your detached instance storage mechanism
To ensure that detached Hibernate instances are clustered, you must attach them to a Terracotta managed object graph. You can do this in many different ways, depending on your needs. Most applications can use one of the following techniques:
- Store detached instances in the HTTP Session Context.
- Store detached instances in a hashmap or other managed root
- Store detached instances in a distributed cache such as EHCache or JBoss TreeCache
Step 2: Configure Terracotta for Hibernate
You must ensure that Hibernate detached instances are supported by Terracotta. To do this, you must enable the Hibernate TIM in your tc-config.xml:
<clients>
<modules>
<module name="tim-hibernate-3.1.2" version="1.1.2"/>
</modules>
</clients>
Step 3: Refactor to use POJOs and merge when necessary
Suppose you have an EHCache instance where you will be putting your detached instances. You must first get the detached instances:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
java.util.List<Person> result =
(java.util.List<Person>) session.createQuery("from Person").list();
Person person = result.get(0);
...
Next, you must store the detached instances (POJOs) in the cache:
cache.put(new Element("person key", person));
From this moment on your detached instances are replicated and safe from system failures until they are committed to the database in the next step.
In the last step, when your application is ready to commit the modified detached instances, it must re-attach them to a Hibernate session:
Person person = (Person) cache.get("person key").getValue();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(person);
session.close();
More help
The Terracotta Hibernate Webcast includes a sample application that you can learn from. If you are having trouble understanding this guide, you should
If you still need assistance, you can: