Java Reference
In-Depth Information
The JPA default is to save by ordinal value. So by default JPA will store User-
Type.ADMIN as the number 3, not the String "ADMIN" . It's also crucial to remember
that once the data is persisted to the database, there's a disconnect between the data and
your code. This means that if you change the enum in your code, there's no way for the
database to know about it. If you change your code, you run the risk of your code no longer
working with the data in the database. If JPA is persisting by ordinal and you change the
order of your enum values, then users will suddenly become the wrong type. If JPA is per-
sisting by String and you change the name of the enum value (from BIDDER to BUYER ,
for example), then you'll get a runtime exception because BIDDER exists in the database
but no longer exists in your code.
9.3.6. Collections
So far you've been learning how to map the major types of single values from out of the
database table columns to the Java domain object properties. But the domain model also
deals with collections of data. For example, users on ActionBazaar may have multiple tele-
phone numbers. The following listing shows an updated User entity that contains a Col-
lection of telephone numbers.
Listing 9.5. User with a list of telephone numbers
@Entity
@Table(name="USERS")
public class User {
private Collection<String> telephoneNumbers;
//...
}
In this listing there's a Collection of String objects intended to hold telephone num-
bers. But you've yet to configure JPA with what it needs to know to get that data out of
the database. This is where the @ElementCollection annotation comes in. To map
a collection of basic types ( java.lang.String , java.util.Integer , and so on)
or embeddable types (more about embeddable types when we discuss the @EmbeddedId
annotation in section 9.3.7 ) , JPA 2.0 introduced the @ElementCollection annotation.
Prior to JPA 2.0 it was still possible to map collections of objects, as you'll see in section
9.4 when we discuss entity relationships, but the addition of @ElementCollection has
made mapping collections much easier. The next listing shows an updated User entity that
maps the telephone numbers.
Search WWH ::




Custom Search