Java Reference
In-Depth Information
Listing 9.6. Mapping a collection of telephone numbers
The @ElementCollection annotation works with a collection table in the database,
and you use it in your entity to tell JPA this property is going to be a collection, not just
a single value . This collection table is nothing more than another table in the data-
base that holds the data you want. The default name for this collection table is a combin-
ation of the entity name and the property name. In the listing the default collection table
name is USER_TELEPHONENUMBER , but you use the @CollectionTable annotation
to override the default and use "PHONE_NUMBERS" instead . The default name for
the column in the collection table is the property name, which in this example would be
TELEPHONENUMBER . But you use the @Column annotation to override the column name
to be "NUMBER" instead . And finally, you use the joinColumns attribute to tell JPA
that the PHONE_NUMBERS.USER_ID column is the foreign key back to the primary key
of the USERS table.
This listing shows an example using a Collection of String objects. But keep in
mind that the @ElementCollection annotation can work with embeddable objects as
well. We'll discuss embeddable objects more in section 9.3.7 , but as a sneak peek, let's
look at the classic embeddable object: the Address . An Address object may look like
this:
@Embeddable
public class Address {
@Column(name="HOME_STREET")
private String street;
@Column(name="HOME_CITY")
private String city;
@Column(name="HOME_STATE")
private String state;
@Column(name="HOME_ZIP")
Search WWH ::




Custom Search