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 MAPPINGPHONENUMBER VARCHAR(255),ADDRESS_ID BIGINT,primary key (ID),foreign key (ADDRESS_ID) references ADDRESS(ID));Listing 3-41. The ADDRESS Tablecreate table ADDRESS (ID BIGINT not null,STR<strong>EE</strong>T1 VARCHAR(255),STR<strong>EE</strong>T2 VARCHAR(255),CITY VARCHAR(255),STATE VARCHAR(255),ZIPCODE VARCHAR(255),COUNTRY VARCHAR(255),primary key (ID));As you now know, <strong>with</strong> JPA, if an attribute is not annotated, the default mapping rules are applied.So, by default, the foreign key column is named ADDRESS_ID (see Listing 3-40), which is the concatenationof the name of the relationship attribute (here address), the symbol _, and the name of the primary keycolumn of the destination table (here it will be the column ID of the ADDRESS table). Also notice that, inthe DDL, the ADDRESS_ID column is nullable by default, meaning that, by default, a one-to-oneassociation is mapped to a zero (null value) or one.To customize the mapping, you can use two annotations. The first one is @OneToOne (that’s becausethe cardinality of the relation is one), and it can modify some attributes of the association itself such asthe way is has to be fetched. The API of the @OneToOne annotation is defined in Listing 3-42.Listing 3-42. @OneToOne Annotation API@Target({METHOD, FIELD}) @Retention(RUNTIME)public @interface OneToOne {Class targetEntity() default void.class;CascadeType[] cascade() default {};FetchType fetch() default EAGER;boolean optional() default true;String mappedBy() default "";boolean orphanRemoval() default false;}The other is @JoinColumn (its API is very similar to @Column). It is used to customize the join column,meaning the foreign key, of the owning side. Listing 3-43 shows how you would use these twoannotations.99

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

Saved successfully!

Ooh no, something went wrong!