Java Code Geeks

Sunday, November 2, 2008

Hibernate - great tool - greater responsibility

I really like the movie "Spiderman" and the way Peter Parker was told - "With Great Power comes Great Responsibility". Similarly Hibernate is a great tool. It has awesome capabilities in transforming "Relational Database Tables" to "Set of related objects". But we, the developers need to be responsible of how to use this tool effectively. Performance of the application can become worse if we are not careful enough with different options available in Hibernate. Here are the list of items which I found are useful to know while developing complex database oriented applications.

1) The famous n+1 problem - Hibernate usually fetches the associations lazily (lazy = true is by default). For example, if one Node can generate any number of events. In this case, hibernate will load the events for the Node only if we need the events. This is a very nice feature otherwise if you ask to load all the nodes , hibernate would have loaded all nodes and its associated events (the complete db) in the memory which will lead to "out of memory" error if the events are really large in number. So lazy loading is really a nice feature. But if you have to traverse all the nodes and process all the events - it will fire n+1 (where n is the number of nodes) to the database leading it to inefficient.
More efficient approach could be to use "batch size" option of hibernate which will make the db round trips from n+1 to n/batch_size + 1.
Another option could be to use outer-join which will fetch all the associated data using an database outer join.
Or else probably better approach is to use FetchMode.EAGER at the runtime (not in the xml file) which will load all the associated objects at once.

2) the lazy fetching can cause another problem with MVC architecture. In our case, the events of the nodes will be loaded lazily, but if we are using one DAO layer which will open the hibernate session, load the node and send that node object to the JSP file, when JSP will try to access the events of the node, it will throw one lazyinitialization exception. There are many ways to solve it and one of the most useful way is to use - Filters or one can load the association eagerly.

No comments: