12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 3 ■ OBJECT-RELATIONAL MAPPING@<strong>Second</strong>aryTableUp to now, I have assumed that an entity gets mapped to a single table, also known as a primary table.But sometimes when you have an existing data model, you need to spread the data across multipletables, or secondary tables. To do this, you need to use the annotation @<strong>Second</strong>aryTable to associate asecondary table to an entity or @<strong>Second</strong>aryTables (<strong>with</strong> an “s”) for several secondary tables. You candistribute the data of an entity across columns in both the primary table and the secondary tables simplyby defining the secondary tables <strong>with</strong> annotations and then specifying for each attribute which table it isin (<strong>with</strong> the @Column annotation, which I’ll describe in the “Attributes” section in more detail). Listing 3-4shows an Address entity mapping its attributes in one primary table and two secondary tables.Listing 3-4. Attributes of the Address Entity Mapped in Three Different Tables@Entity@<strong>Second</strong>aryTables({@<strong>Second</strong>aryTable(name = "city"),@<strong>Second</strong>aryTable(name = "country")})public class Address {@Idprivate Long id;private String street1;private String street2;@Column(table = "city")private String city;@Column(table = "city")private String state;@Column(table = "city")private String zipcode;@Column(table = "country")private String country;}// Constructors, getters, settersBy default, the attributes of the Address entity are mapped to the primary table (which has thedefault name of the entity, so the table is called ADDRESS). The annotation @<strong>Second</strong>aryTables informs youthat there are two secondary tables: CITY and COUNTRY. You then need to specify which attribute is storedin which secondary table (using the annotation @Column(table="city") or @Column(table="country")).Figure 3-2 shows the tables structure to which the Address entity will be mapped. Each table containsdifferent attributes but they all have the same primary key (to join the tables together). Again, rememberthat Derby translates lowercase table names (city) into uppercase (CITY).66

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!