Hibernate Best Practices

Currently there are two school of thoughts when it comes to using Hibernate.

  1. Hibernate Sucks
  2. It is a life saver framework
People with bullet point 1 give the following explanation to support their argument.
  1. It is a very heavy framework.
  2. It will eat up lots of your valuable memory.
  3. It is buggy, etc.
I am not going to clarify their misunderstanding here, instead i will talk about the points which will let us use hibernate as it is supposed to be used.

Here are the points.

  • Prefer using “session.get(classZ, ID) instead of “session.load(classZ, ID).Load always returns the proxy to avoid getting LazyInitializationException.
  • Always set “lazy=true” for collection mappings and use “join fetch”  in HQL or “setFetchMode” in criteria to retrieve collections.
  • Use surrogate/dummy id in data model instead of composite keys and override equals / HashCode method using the business key to identify uniqueness.
  • As HibernateException is Runtime Exception never catch them at business layer and have them be propagated to UI Layer.There are several benefits doing this.
  • Write Custom UserType  for type/code values with corresponding Java Enum class. Prefer using Criteria API to build the SQL query instead of HQL.
  • Careful implementing toString() method for printing collections to avoid getting org.hibernate.LazyInitializationException
  • Many-One mapping should preferably have lazy=“false” and One-Many “lazy=true”. Avoid N+1 Query problem using eager fetching or “batch” setting.
  • Don’t retrieve to much data in one query and use paging, fetch strategy, and carefully using the join to get the data needed.
  • Use 2nd (JVM level) caching for mostly read only data’s.
  • Use query cache for read only data that is always queried the same way
  • print only atributes which are mapped through ‘property’ element
  • DO NOT print any collections  as all collections should be marked as ‘lazy=true’.
  • object (many-to-one) should ONLY be printed if marked as ‘lazy=false” and fetch=’join’
  • Avoid using <key-may-to-one> inside <composite-id> use <key-property> instead
  • Avoid using hsql  as much as possible, prefer detached Criteria or Criteria Instead.   Very Very Important
  • Do not ever perform bulk operations with Hibernate.

Any more points ?


5 thoughts on “Hibernate Best Practices

  1. Hi,

    As HibernateException is Runtime Exception never catch them at business layer and have them be propagated to UI Layer.There are several benefits doing this.

    what is the benifit of doing this, in fact it is considered as bad practice to expose database exception to UI due to security reasons?


    • It seems there are two questions

      1) Why not catch HibernateException at DAO or Business Layer ?
      ANS :- All exceptions thrown by hibernate are fatal, nothing can be done in these case.
      2) Why HibernateException is exposed to User ?
      ANS :- That’s true HibernateException should not be exposed to User, However it is good to have it propagated at the UI layer. UI layer should decide what should be displayed to user on RuntimeExceptions. And Webframeworks should let you do this seamlessly. For example In Apache wicket i can do the following on subclass of WebRequestCycle:

      public Page onRuntimeException(Page page, RuntimeException e) {
      if (e instanceof UnauthorizedInstantiationException) {
      return new AccessDeniedPage();
      } else {
      return new ExceptionErrorPage(e, page);

      ExceptionErrorPage, AccessDeniedPage have the logic what what should be displayed to the user.

      One last thing Hibernate 3.X did a great thing by making HibernateException a RuntimeException, since in my point of view Checked exception in a framework is really evil.

  2. Actually I agree with you in many points, but I cannot arrange with the way you present it:

    The most important point in Best Practices as well as in Design Patterns is to understand … only when someone knows why to use certain Practices, they can use them effectively.

    As I mentioned you have written a bunch of very intelligent points … but none is argued why to use the. too bad 😦

  3. I appreciated the way you presented your experience here, good items.

    It would be great if you give some more details on some of the points which is helpful for every body to judge/justify these best practice.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s