Friday, June 1, 2012

Hibernate Relationship Mapping

Hibernate relationship mapping allows related objects to be linked as e.g. collections. My view on this feature is that it is to be used with EXTREME CAUTION. Too many novice programmers link ORM objects without thought of what kinds of queries will be generated under the hood, sometimes with disastrous results.

The argument that it can help save the N+1 query problem is also a weak one, because most production environments will use caching, and when caching is used, N+1 queries (that hit the cache) is much better than 1 query that does a huge join across multiple large tables.

As such, I avoid using it, but there are times (especially when performance isn't an issue) where it can be handy, and save some work (though it's debatable because the configuration is so complex sometimes I find it easier to just write more Java code to handle the relationships).

It also doesn't help that the Hibernate documentation doesn't explain clearly what is minimally required by most people in most cases, which is a simple, uni-directional, one-to-many mapping situation.

In this case, it is enough to just add something like the following:
<list name="books" cascade="all" lazy="true">
    <key column="books_id" />
    <index column="sorting_order"/>
    <one-to-many class="xxx.xxx.xxx.xxx.Books" />
</list>

index refers to how the index of the resulting List is to be mapped.

No need for the other direction unless you really need it.

Hibernate manual: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/collections.html

No comments:

Post a Comment