Java Reference
In-Depth Information
The following mapping illustrates the creation of a simple many-to-one association
between a User class and an Email class: each user can have only one e-mail address—but
an e-mail address can belong to more than one user.
<many-to-one
name="email"
class="com.hibernatebook.xmlmapping.Email"
column="email"
cascade="all" unique="true"/>
The simplest approach to creating a many-to-one relationship, as shown in the previous
example, requires two tables and a foreign key dependency. An alternative is to use a link table
to combine the two entities. The link table contains the appropriate foreign keys referencing
the two tables associated with both of the entities in the association. The following code shows
the mapping of a many-to-one relationship via a link table.
<join table="link_email_user" inverse="true" optional="false">
<key column="user_id"/>
<many-to-one name="email" column="email_id" not-null="true"/>
</join>
The disadvantage of the link table approach is its slightly poorer performance (it requires
a join of three tables to retrieve the associations, rather than one). Its benefit is that it requires
less extreme changes to the schema if the relationship is modified—typically, changes would
be made to the link table, rather than to one of the entity tables.
The Collection Elements
These are the elements that are required for you to include an attribute in your class that rep-
resents any of the collection classes. For example, if you have an attribute of type Set , then you
will need to use a <bag> or <set> element to represent its relationship with the database.
Because of the simplicity of the object-oriented relationship involved, where one object
has an attribute capable of containing many objects, it is a common fallacy to assume that the
relationship must be expressed as a one-to-many. In practice, however, this will almost always
be easiest to express as a many-to-many relationship, where an additional link table closely
corresponds with the role of the collection itself. See the “Mapping Collections” section later
in this chapter for a more detailed illustration of this.
All the collection mapping elements share the attributes shown in Table 7-10.
Table 7-10. The Attributes Common to the Collection Elements
Attribute
Values
Default
Description
access
Specifies how the class member should be
accessed: field for direct field access or
attribute for access via the get and set methods.
batch-size
Specifies the number of items that can be
batched together when retrieving instances of
the class by identifier.
Continued
Search WWH ::




Custom Search