Java Reference
In-Depth Information
@Target({ TYPE })
@Retention(RUNTIME)
public @interface SecondaryTable {
String name();
String catalog() default "";
String schema() default "";
PrimaryKeyJoinColumn[] pkJoinColumns() default {};
UniqueConstraint[] uniqueConstraints() default {};
}
Notice that other than the pkJoinColumns element, the definition of the annotation is
identical to the definition of the @Table annotation. This pkJoinColumns element is
the key to how the annotation works. As an example, examine the following code imple-
menting the User entity mapped to these two tables:
@Entity
@Table(name="USERS")
@SecondaryTable(name="USER_PICTURES",
pkJoinColumns=@PrimaryKeyJoinColumn(name="USER_ID"))
public class User
The pkJoinColumns=@PrimaryKeyJoinColumn(name="USER_ID") config-
uration tells JPA that the primary key of the USERS table (how JPA determines the primary
key of the USERS table is discussed in the next section when we look at the @Id an-
notation) is the same as the foreign key USER_PICTURES.USER_ID in the secondary
table. JPA performs a join between the two tables to fetch the data for the User entity.
This example involves only two tables. If more than two tables were involved, you'd use
@Secondary-Tables (plural) to specify all of the secondary tables.
Something you may be asking yourself about using @SecondaryTable is how JPA
knows to map the columns from different tables to the correct Java object properties. After
all, if you look at the User entity in listing 9.2 , there's nothing to tell JPA the byte array
picture property's data comes from the secondary table. To answer this question, we'll
need to look at how JPA maps table columns.
9.3.3. Mapping the columns
Having learned how to map the database tables in the previous sections, it's now time to
look at how to map the table columns. The @Column annotation maps a persisted object
property to a table column. First, we're going to look at the basics of using the @Column
Search WWH ::




Custom Search