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 ?