Java Reference
In-Depth Information
loaded from the database before control is ceded to the parent entity's implementation.
Where the association is represented as a collection class, a wrapper (essentially a proxy for
the collection, rather than for the entities that it contains) is created and substituted for the
original collection.
Hibernate can only access the database via a session. If an entity is detached from the ses-
sion when we try to access an association (via a proxy or collection wrapper) that has not yet
been loaded, Hibernate throws an exception: the infamous LazyInitializationException . The
cure is to either ensure that the entity is made persistent again, or ensure that all of the fields
that will be required are accessed before the entity is detached from the session.
If you need to determine whether a proxy, a persistence collection, or an attribute has
been lazy loaded or not, you can call the isInitialized() and isPropertyInitialized()
methods on the org.hibernate.Hibernate class. You can also force a proxy or collection to
become fully populated by calling the initialize() method on this class.
Querying Objects
Hibernate provides several different ways to query for objects stored in the database. The
Criteria Query API is a Java API for constructing a query as an object. HQL is an object-ori-
ented query language, similar to SQL, that you may use to retrieve objects that match the
query. Hibernate provides a way to execute SQL directly against the database to retrieve
objects—if you have legacy applications that use SQL or if you need to use SQL features that
are not supported through HQL and the Criteria Query API (discussed in Chapter 11).
Summary
Hibernate provides a simple API for creating, retrieving, updating, and deleting objects from
a relational database through the Session interface. Understanding the difference between
transient, persistent, and detached objects in Hibernate will allow you to understand how
changes to the objects update database tables.
We have touched upon the need to create mappings to correlate the database tables with
the fields and properties of the Java objects that you want to persist. The next chapter covers
these in detail, and discusses why they are required and what they can contain.
Search WWH ::




Custom Search