Java Reference
In-Depth Information
The last possible cascading type is delete-orphan . Use delete-orphan to remove a child
object from the database when you remove the child from the parent's collection. This cascad-
ing type only works on one-to-many associations. The all cascading type does not include
delete-orphan —you will have to use "all,delete-orphan" , as in the following excerpt from
a Hibernate mapping file:
<bag name="products" inverse="true" cascade="all,delete-orphan">
<key column="supplierId"/>
<one-to-many class="Product"/>
</bag>
Simply remove a child object from a parent object's collection after you have added the
delete-orphan cascading type. Hibernate will remove the child object from the database itself,
without any additional calls. The following example removes a child object from the collection:
supplier.getProducts().remove(product);
Lazy Loading, Proxies, and Collection Wrappers
Consider the stereotypical Internet web application: the online store. The store maintains
a catalog of products. At the crudest level, this can be modeled as a catalog entity managing a
series of product entities. In a large store, there may be tens of thousands of products grouped
into various overlapping categories.
When a customer visits the store, the catalog must be loaded from the database. We prob-
ably don't want the implementation to load every single one of the entities representing the
tens of thousands of products to be loaded into memory. For a sufficiently large retailer, this
might not even be possible given the amount of physical memory available on the machine.
Even if this were possible, it would probably cripple the performance of the site.
Instead, we want only the catalog to load, possibly with the categories as well. Only when
the user drills down into the categories should a subset of the products in that category be
loaded from the database.
To manage this problem, Hibernate provides a facility called lazy loading. When enabled
(this is the default using XML mappings, but not when using annotations), an entity's associ-
ated entities will only be loaded when they are directly requested. For example, the following
code loads only a single entity from the database:
Email email = (Email)session.get(Email.class,new Integer(42));
whereas if an association of the class is accessed, and lazy loading is in effect, the associations
are pulled from the database as needed. For instance, in the following snippet, the associated
Message object will be loaded since it is explicitly referenced.
Email email = (Email)session.get(Email.class,new Integer(42));
String text = email.getMessage().getContent();
The simplest way that Hibernate can force this behavior upon our entities is by providing
a proxy implementation of them. Hibernate intercepts calls to the entity by substituting for it a
proxy derived from the entity's class. Where the requested information is missing, it will be
Search WWH ::




Custom Search