Java Reference
In-Depth Information
You simply annotate the property to let JPA know it's to use that value to uniquely identify
a
Category
. As the following examples show, you can annotate either the property
@Id
private long id;
or the getter method
@Id
public long getId() { return id; }
The value of the
@Id
property is used by JPA to uniquely identify a
Category
. This
means if JPA wants to know if two
Category
objects are the same, it'll compare the
@Id
property values, and if the values are equal, then JPA thinks the two
Category
objects are
the same. The
@Id
property can support primitives (
int
,
long
,
double
, and the like),
and in these cases JPA performs a direct equality comparison. The
@Id
property also sup-
ports
Serializable
types (
String
,
Date
, and so on), and in these cases JPA will use
the
equals()
method.
It's important to remember that the
@Id
annotation will work only if the primary key is a
single column of the table. Most modern projects will add a column to the table for this
very purpose. But legacy projects may not have a single-column primary key but instead
rely on multiple columns to uniquely identify a row in the table. JPA has two ways of hand-
ling multiple column primary keys. We'll look at these next.
@IdClass annotation
The first way JPA handles multiple-column primary keys is with the
@IdClass
an-
notation. This allows you to mark multiple properties in your Java object with
@Id
(the
columns of the table that make up the primary key) and then define a class that basically
follows the comparator patterns and defines how those multiple
@Id
values are supposed
to be compared to determine equality. Let's 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 primary key. The first thing you'll do in the following listing is define these two prop-
erties in the
Category
class and annotate them with
@Id
so JPA knows these two classes
together uniquely identify the entity.