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 MAPPINGAs you can see in Figure 3-23, the ITEM table sums all the attributes of the Item, Book, and CD entities.But there’s an additional column that doesn’t relate to any of the entities’ attributes: it’s thediscriminator column, DTYPE.The ITEM table will be filled <strong>with</strong> items, books, and CD albums. When accessing the data, thepersistence provider needs to know which row belongs to which entity. This way, the provider willinstantiate the appropriate object type (Item, Book, or CD) when reading the ITEM table. That’s why adiscriminator column is used to explicitly type each row.Figure 3-24 shows a fragment of the ITEM table <strong>with</strong> some data. As you can see, the single-table-perclassstrategy has some holes; not every column is useful for each entity. The first row is the data storedfor an Item entity (the DTYPE column contains the name of the entity). Items only have a title, a price, anda description (see Listing 3-58 earlier); they don’t have a music company, an ISBN, and so on. So thesecolumns will always remain empty.Figure 3-24. Fragment of the ITEM table filled <strong>with</strong> dataThe discriminator column is called DTYPE by default, is of type String (mapped to a VARCHAR), andcontains the name of the entity. If the defaults don’t suit, the @DiscriminatorColumn annotation allowsyou to change the name and the data type. By default, the value of this column is the entity name towhich it refers, although an entity may override this value using the @DiscriminatorValue annotation.In Listing 3-61, I rename the discriminator column to DISC (instead of DTYPE) and change its datatype to Char instead of String; each entity should change its discriminator value to I for Item, B for Book(see Listing 3-62), and C for CD (see Listing 3-63).Listing 3-61. Item Redefines the Discriminator Column@Entity@Inheritance(strategy = InheritanceType.SINGLE_TABLE)@DiscriminatorColumn (name="disc", discriminatorType = DiscriminatorType.CHAR)@DiscriminatorValue("I")public class Item {@Id @GeneratedValueprotected Long id;protected String title;protected Float price;protected String description;}// Constructors, getters, setters113

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

Saved successfully!

Ooh no, something went wrong!