Java Reference
In-Depth Information
Despite that similarity, the direction of the association is effectively reversed. Given an
Email row, you can immediately determine which User row it belongs to in the database; this
relationship is mandated by a foreign key constraint. It is possible to reverse the relationship
in the database world through suitable use of SQL—another difference.
Given the differences between the two worlds, it is necessary to manually intervene to
determine how your Java classes should be represented in database tables.
Why Mapping Cannot Be Automated
It is not immediately obvious why you cannot create simple rules for storing your Java objects
in the database so that they can be easily retrieved. For example, the most immediately obvi-
ous rule would be that a Java class must correlate to a single table. For example, instances of
the User class defined in Listing 5-2 could surely be represented by a simple table like the one
for a user shown in Figure 5-1.
Listing 5-2. A Simple User Class with a Password Field
public class User {
String name;
String password;
}
And indeed it could, but some questions present themselves:
How many rows should you end up with if you save a user twice?
Are you allowed to save a user without a name?
Are you allowed to save a user without a password?
When you start to think about classes that refer to other classes, there are additional ques-
tions to consider. Have a look at the Customer and Email classes defined in Listing 5-3.
Listing 5-3. Customer and Email Classes
public class Customer {
int customerId;
int customerReference;
String name;
Email email;
}
public class Email {
String address;
}
Search WWH ::




Custom Search