Java Reference
In-Depth Information
structor must be provided so JPA can create an instance of CategoryKey . An over-
ridden equals() method is provided to perform the actual logic to compare the
name and createDate properties. Finally, an overridden hashCode() method
is
required.
You're almost finished. The last thing you need to do is let Category know to use Cat-
egoryKey . Referring back to listing 9.7 , you update the code for the Category class
and add in the @IdClass annotation like this:
@Entity
@IdClass(CategoryKey.class)
public class Category {
// ...
}
So how does this all fit together? When JPA retrieves data from the CATEGORY table and
creates a Category object, the name and createdDate properties are set with data
from their corresponding columns in the table. When the time comes for JPA to determine
if two Category objects are the same, JPA will create a new instance of CategoryKey
for each of the Category objects it's comparing. JPA will copy the name and cre-
atedDate property values from the Category objects into the CategoryKey objects.
Finally, JPA will use the equals() method on CategoryKey to see if the two Cat-
egoryKey objects are the same. If they're equal, JPA then assumes the two Category
objects are equal.
This is just one way JPA handles multiple-column primary keys when it maps the data
to your Java domain model. Next, we look at another way JPA handles this with the
@EmbeddedId annotation.
@EmbeddedId annotation
The second way JPA handles multiple-column primary keys is with the @EmbeddedId
annotation. Using the @EmbeddedId is very similar to using @IdClass , but @Embed-
dedId takes advantage of the @Embeddable annotation and turns your domain model
object into a composite. Let's take a look at an example. Suppose the CATEGORY table
is part of a legacy project and the table uses the category name and creation date as the
Search WWH ::




Custom Search