Tuesday, June 10, 2008

Tips on development with Hibernate

One of the common problems in query optimization using Hibernate is when one of your tables is associated with several other tables. This is a common problem and has a pretty straight forward solution. Consider a sample Hibernate mapping file of a table Student associated with other tables like Course, Professor



Now a simple query like

from Student where student_id := entered_id

will generate a sequence of selects from its associated tables, which will greatly effect the query performance time. To reduce this waterfall effect we have to load the associated objects in the initial query by using a "left join fetch" construction as shown below

from Student student
left join fetch student.course
left join fetch student.professor

However there are some limatations on usage of "fetch". It cannot be used on queries using iterate() or queries involving result row operations like setMaxResults(), setFirstResult() etc.

for further reading visit the detailed discussion on this site


For those of you starting up with Hibernate and would like to implement it using MyEclipse IDE, here is a good tutorial (though a slightly outdated with the versions)

No comments: