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 MAPPINGhave no-arg constructor, getter, setter, equals(), and hashCode() implementations, i.e., it needs to usethe <strong>Java</strong>Bean conventions. The class itself doesn’t have an identity of its own (no @Id annotation). That’sa characteristic of an embeddable.Listing 3-7. The Primary Key Class Is Annotated <strong>with</strong> @Embeddable@Embeddablepublic class NewsId {private String title;private String language;}// Constructors, getters, setters, equals, and hashcodeThe News entity, shown in Listing 3-8, then has to embed the primary key class NewsId <strong>with</strong> the@EmbeddedId annotation. With this approach, there is no need to use @Id. Every @EmbeddedId must refer toan embeddable class marked <strong>with</strong> @Embeddable.Listing 3-8. The Entity Embeds the Primary Key Class <strong>with</strong> @EmbeddedId@Entitypublic class News {@EmbeddedIdprivate NewsId id;private String content;}// Constructors, getters, settersIn Chapter 4, I will describe how to find entities using their primary key. Just as a first glimpse, hereis how it works: the primary key is a class <strong>with</strong> a constructor. You have to instantiate this class <strong>with</strong> thevalues that form your unique key, and pass this object to the entity manager (the em attribute) as shownin Listing 3-9.Listing 3-9. Simplified Code to Find an Entity Through Its Composite Primary KeyNewsId pk = new NewsId("Richard Wright has died", "EN")News news = em.find(News.class, pk);@IdClassThe other method of declaring a composite key is through the @IdClass annotation. It’s a differentapproach whereby each attribute on the primary key class also needs to be declared on the entity classand annotated <strong>with</strong> @Id.The composite primary key in the example NewsId in Listing 3-10 is just a POJO that does not requireany annotation (in the previous example, the primary key class needs to be annotated <strong>with</strong> @EmbeddedId).70

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

Saved successfully!

Ooh no, something went wrong!