Java Reference
In-Depth Information
byte[] picture;
// ...
}
@Entity
public class Seller extends User { /**/ }
@Entity
public class Bidder extends User { /**/ }
All the
User
class fields (
userId
,
username
,
email
) are persisted when either the
Seller
or
Bidder
entity is saved. This wouldn't be the case if the
User
class weren't
an entity itself. Rather, the value of the inherited properties would be discarded when either
Seller
or
Bidder
was persisted. This listing also demonstrates an interesting weak-
ness—the
User
class could be persisted on its own, which isn't necessarily desirable or ap-
propriate application behavior. One way to avoid this problem is to declare the
User
class
abstract, because abstract entities are allowed but can't be directly instantiated or saved.
The ultimate goal of persistence is to save the properties of the entity into the database. The
@Entity
annotation is the beginning. Given the Java EE preference for convention over
configuration, this may be all you need. But JPA has many more annotations to help spe-
cify how the data gets to the database. The next thing we'll look at is how JPA determines
which table in your database holds the data for your entity.
9.3.2. Specifying the table
Data for the domain model will come from multiple tables in the database. For some entit-
ies, the mapping may be simple and all of the data for the entity will come from a single
table. For more complicated entities, the data may be scattered across two or more tables.
It's important to understand when working with multiple tables
in this context
that we're
discussing data for a single entity being stored across multiple tables. Consider user data
as an example. One table may store most of the user data, but a separate table may store
the user's picture. This is an example of user data being scattered across two tables. This is
what we'll be discussing in this section.
What we won't be discussing in this section is working with multiple tables in the context
of entity relationships. Consider user and address data as an example. A relationship exists
between a single user and multiple addresses. We'll cover this starting in
section 9.4
on en-
tity relationships.