Introduction to HibernateÂ
Hibernate is the most popular ORM tool in the market. To summarize, it provides the following key features:
- Support its own object query language HQL
- Transparent persistence - keep track of all loaded objects and automatic change detection through snapshot comparison. To do that, it uses CGLIB to create runtime proxies for persistent objects through dynamic bytecode generation. So, it is better in performance and no need to modify persistent objects for marking it dirty.
- Deal with different SQL dialects and in turn provides us a single abstraction layer.
- Support pluggable cache strategies - 2 levels of caches: Session vs Session Factory.
- Control how the dependent objects be loaded (eg. lazy loading). However, Hibernate Session that originally loaded the affected persistent objects needs to still be open to make lazy loading work. It is recommended to execute such operations within transactions, which will keep the same Hibernate Session open for the lifetime of the entire transaction. If you need lazy loading beyond the scope of your transactions - for example in web views - you need to resort to the Open Session in View pattern.
How Spring helps us to work with Hibernate?
Spring provides us HibernateTemplate that can save us from biolerplate code like dealing with JDBC. Below are the benefits we obtain from this:
- Hibernate Session will automatically be synchronized with Spring transaction.
- Leverage the normalized exception model
Open Session in View
If you want to do lazy loading during view rendering, you might face a problem that the original transaction has already ended in the service layer and thus closed the Hibernate Session that loaded the given persistent object. One solution for the problem would be to process the entire HTTP request, including view rendering within a single transaction. However, it is not an ideal solution because it would hold database lock until view rendering has been completed. The common solution is the Open Session in View pattern. Transactions end in service layer, but the associated Hibernate Session remains open until view rendering has been completed. This releases database locks early but still alows for lazy loading in the view. NOTE: you can only do that while web and service layer are co-located b/c your Hibernate Session cannot pass via ThreadLocal in remote setting.






































(4.75 out of 5)
1 Comment Received
Pingback & Trackback
Sorry the comment area are closed for non registered users