Java Reference
In-Depth Information
The default in Hibernate 3 is that classes (including collections like
Set
and
Map
) should
be lazily loaded. For example, when an instance of the
User
class given in the next listing is
loaded from the database, the only fields initialized will be
userId
and
username
.
public class User {
int userId;
String username;
EmailAddress emailAddress;
Set roles;
}
However, as long as the object is still associated with Hibernate in the appropriate way
(see Chapter 9), the appropriate objects for
emailAddress
and
roles
will be loaded from the
database if they are accessed.
This is the default behavior only; the mapping file can be used to specify which classes
and fields should behave in this way.
Associations
When we looked at why the mapping process could not be automated, we discussed the fol-
lowing example classes:
public class Customer {
int customerId;
int customerReference;
String name;
Email email;
}
public class Email {
String address;
}
We also gave the following five questions that it raised:
•
Is a unique customer identified by their customer ID, or their customer reference?
•
Can a given e-mail address be used by more than one customer?
Should the relationship be represented in the
Customer
table?
•
Should the relationship be represented in the
Email
table?
•
•
Should the relationship be represented in some third (link) table?
The first question can be answered simply—it depends on what column you specify as
the primary key. The remaining four questions are related, and their answers depend upon the
object relationships. Furthermore, if your
Customer
class represents the relationship with the
EmailAddress
using a
Collection
class or an array, it would be possible for a user to have mul-
tiple e-mail addresses.
Search WWH ::
Custom Search