Java Reference
In-Depth Information
If Hibernate could not uniquely identify an object with a primary key, then the following
code could have several possible outcomes in the underlying table.
String customer = getCustomerFromHibernate("dcminter");
customer.setAge(10);
saveCustomerToHibernate(customer);
For example, let's say the table originally contained the data shown in Table 5-3.
Table 5-3. Updating an Ambiguous Table
User
Age
dcminter
30
dcminter
42
Which of the following should be contained in the resulting table?
A single row for the user dcminter , with the age set to 10
Two rows for the user, with both ages set to 10
Two rows for the user, with one age set to 10 and the other to 42
Two rows for the user, with one age set to 10 and the other to 30
Three rows for the user, with one age set to 10 and the others to 30 and 42
In short, the Hibernate developers made a decision to enforce the use of primary keys
when creating mappings so that this problem does not arise. Hibernate does provide facilities
that will allow you to work around this if it is absolutely necessary (you can create views or
stored procedures to “fake” the appropriate key, or you can use conventional JDBC to access
the table data), but when using Hibernate, it is always more desirable to work with tables that
have correctly specified primary keys if at all possible.
Lazy Loading
When you load classes into memory from the database, you don't necessarily want all the
information to actually be loaded. To take an extreme example, loading a list of e-mails should
not cause the full body text and attachments of every e-mail to be loaded into memory. First,
they might demand more memory than is actually available. Second, even if they fit, it could
take a long time for all of this information to be obtained.
If you were to tackle this problem in SQL, you would probably select a subset of the appro-
priate fields for the query to obtain the list; for example:
SELECT from, to, date, subject FROM email WHERE username = 'dcminter';
Hibernate will allow you to fashion queries that are rather similar to this, but it also offers
a more flexible approach, known as lazy loading . Certain relationships can be marked as being
“lazy,” and they will not be loaded from disk until they are actually required.
Search WWH ::




Custom Search