Java Reference
In-Depth Information
6.2 Other Hibernate issues
In addition to these
O/R
mapping issues, there are other issues with Hibernate
that can make writing applications difficult.
6.2.1
Exception handling
One potential problem with how Hibernate handles errors is that when it encoun-
ters an error, it throws a
HibernateException
and leaves the
Session
in a poten-
tially inconsistent state. According to the Hibernate documentation, the
application must close the
Session
immediately, which can sometimes make
recovering from exceptions unnecessarily complicated if the application wants to
continue using the
Session
. For more information, see chapter 8, which describes
how to recover from errors in an application that uses an exposed domain model.
Fortunately, this isn't a problem when using a
POJO
façade because the applica-
tion uses a new
Session
each time the façade is called.
6.2.2
Lazy loading and inheritance hierarchies
As we saw in chapter 4, lazy loading is an important feature of an
ORM
frame-
work. Hibernate provides a couple of ways to do lazy loading. The simpler
approach is to use Hibernate's proxy-based mechanism, which is enabled by
default in Hibernate 3. When using proxies, a reference to a lazily loaded object
is actually a reference to a proxy that will load the real object the first time one of
its methods is called. The trouble with proxies is that, as we describe a bit later,
they break code that uses
instanceof
or downcasting, which are two important
features of the Java language.
Alternatively, if your application needs objects to use
instanceof
and down-
casting, then you can use lazy property loading. This mechanism works by loading
objects only when the property that references them is first accessed. The draw-
back of lazy property loading is that it is less convenient because you must run a
bytecode enhancer that modifies the classes to intercept references to properties.
In addition, Hibernate can generate suboptimal
SQL
to load an object referenced
by a lazily loaded property. Let's look at the details of these two mechanisms.
Using proxies with instanceof and downcasting
Let's imagine that you are writing some presentation tier code to display a pend-
ing order and that how you display a coupon depends on its actual class. You will
probably write some code similar to this:
Search WWH ::
Custom Search