Friday, August 2, 2013

Learn Hibernate By Example

Hey, I should say I'm a very big fan of learning by example. The thing is, once you have a solid background you don't need words to be said: the code tells everything. So I've added a couple of projects which are dedicated to Hibernate and related stuff. And as always github: hibernate-samples and hibernate-ehcache. All the examples are implemented as JUnit tests.

So, let me give a couple of words what these projects are all about.

Hibernate Samples.

Hibernate samples demonstrates some general techniques of Hibernate 4.x. It covers the following areas:

  • Schema: Embedding of another object
  • Schema: Embedding of a collection of objects and types of fetching (lazy, eager)
  • Schema: Inheritance through different types (single table, joined, table per class)
  • Schema: Different relationships: one-to-one, many-to-one, many-to-many covering cascading. 
  • State: Some operations demonstrating how the object can change it's state (Persistent, Transient, Detached)
  • Hql: A lot of examples on how to use Hql queries including Named and Native queries.

Note, that there is almost now Criteria-related examples. Sorry about that. :)

Hibernate Ehcache

This project is about hibernate caching. There are 3 levels of caching in hibernate:
  1. Session cache
  2. 2-nd level cache
  3. Query cache

The session cache is all about caching the information available to current session-object only. For all the methods save(), update(), saveOrUpdate(), load(), get(), list(), iterate(), scroll() hibernate always tries to use 1st-level (session level) cache.

The second level cache is bound to SessionFactory object. You can you any caching provider you want from a list of compatible cache implementations: Ehcache, OSCache, SwarmCache. Thus there is a list to choose from Ehcache is a pretty popular framework to be used as a second-level cache.
You can configure cache settings per class using @Cache annotation. Read more about that in hibernate developer guide.

The third level cache (query level) only caches the parameters of the query not the result itself. So it's better be used in couple with 2nd level cache.

To debug your hibernate application it's possible to calculate usage statistics for a given SessionFactory.

<property name="hibernate.generate_statistics">true</property>

and then access it with


I hope you'll find these sample useful just check tests. 
I would also recommend you to read an article on how to build your Soap Web Service with CXF, Spring and JBoss

No comments:

Post a Comment