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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 3 ■ OBJECT-RELATIONAL MAPPINGListing 3-23. Mapping an Enumerated Type <strong>with</strong> String@Entity@Table(name = "credit_card")public class CreditCard {@Idprivate String number;private String expiryDate;private Integer controlNumber;@Enumerated(EnumType.STRING)private CreditCardType creditCardType;// Constructors, getters, setters}Now the CreditCardType database column will be of type VARCHAR and a Visa card will be stored <strong>with</strong>the string "VISA".Access TypeUntil now I have shown you annotated classes (@Entity or @Table) and attributes (@Basic, @Column,@Temporal, etc.), but the annotations applied on an attribute (or field access) can also be set on thecorresponding getter method (or property access). For example, the annotation @Id can be set on the idattribute or on the getId() method. As this is largely a matter of personal preference, I tend to useproperty access (annotate the getters), as I find the code more readable. This allows me to quickly readthe attributes of an entity <strong>with</strong>out drowning in annotations. In this book, for easy readability, I’vedecided to annotate the attributes. But in some cases, for example, <strong>with</strong> inheritance, it is not simply amatter of personal taste, as it can have an impact upon your mapping.■ Note <strong>Java</strong> defines a field as an instance attribute. A property is any field <strong>with</strong> accessor (getter and setter)methods that follow the <strong>Java</strong> bean pattern (starts <strong>with</strong> getXXX, setXXX, or isXXX for a Boolean).When choosing between field access (attributes) or property access (getters), you are specifyingaccess type. By default, a single access type applies to an entity: it is either field access or property access,but not both (i.e., the persistence provider accesses persistent state either via attributes or via the gettermethods). The specification states that the behavior of an application that mixes the placement ofannotations on fields and properties <strong>with</strong>out explicitly specifying the access type is undefined.When field-based access is used (see Listing 3-24), the persistence provider maps the attributes. Allnontransient instance variables that are not annotated <strong>with</strong> the @Transient annotation are persistent.78

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

Saved successfully!

Ooh no, something went wrong!