google Analytics

Sunday, August 22, 2010

Improve Hibernate Speed

Improve Hibernate Speed

Ehcache is an open source widely used java distributed cache for general purpose caching, Java EE and light-weight containers. It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter, RESTful and SOAP APIs and much more. Ehcache is available under an Apache open source license and is actively supported

Hibernate Second Level Cache
Setting Ehcache as the Hibernate Second Level Cache

Hibernate 3.0 - 3.2
Use:

<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.EhCacheProvider
</property>

for instance creation, or

<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.SingletonEhCacheProvider
</property>

to force Hibernate to use a singleton Ehcache CacheManager.


For example to enable cache entries for the domain object
com.somecompany.someproject.domain.Country there would be a mapping file
something like the following:

<hibernate-mapping>

<class
name="com.somecompany.someproject.domain.Country"
table="ut_Countries"
dynamic-update="false"
dynamic-insert="false"
>
...
</class>
</hibernate-mapping>

This can also be achieved using the @Cache annotation, e.g.

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country { ... }


To enable caching, add the following element.

<cache usage="read-write|nonstrict-read-write|read-only" />

Using Query Caches
For example, let's say we have a common query running against the Country Domain.

Code to use a query cache follows:

public List getStreetTypes(final Country country) throws HibernateException {
final Session session = createSession();
try {
final Query query = session.createQuery(

"select st.id, st.name"
+ " from StreetType st "
+ " where st.country.id = :countryId "
+ " order by st.sortOrder desc, st.name");
query.setLong("countryId", country.getId().longValue());
query.setCacheable(true);
query.setCacheRegion("query.StreetTypes");
return query.list();
} finally {
session.close();
}
}

The query.setCacheable(true) line caches the query.

The query.setCacheRegion("query.StreetTypes") line sets the name of the Query Cache.
=========================================================================

Introduction to Hibernate Caching
Hibernate Performance Tuning
Hibernate Second Level Cache
Searches related to hibernate 2nd level cache
hibernate 2nd level cache spring modules
manipulating hibernate 2nd level cache
hibernate ehcache
spring modules cache java
nhibernate 2nd level cache
hibernate cache use second level cache
hibernate clear second level cache
for more information on ehCache

http://ehcache.org/documentation/hibernate.html

No comments:

Post a Comment