Java Reference
In-Depth Information
As we can see, a JPA entity is a standard Java object. There is no need to extend any
special class or implement any special interface. What differentiates a JPA entity
from other Java objects are a few JPA-specific annotations.
The @Entity annotation is used to indicate that our class is a JPA entity. Any object
we want to persist to a database via JPA must be annotated with this annotation.
The @Id annotation is used to indicate what field in our JPA entity is its primary key.
The primary key is a unique identifier for our entity. No two entities may have the
same value for their primary key field. This annotation can be used on the field that
serves as a primary key; this is the strategy that the NetBeans wizard uses. It is also
correct to annotate the getter method for the entity's primary key field.
The @Entity and the @Id annotations are the bare minimum two annotations that
a class needs in order to be considered a JPA entity. JPA allows primary keys to
be automatically generated; in order to take advantage of this functionality, the
@GeneratedValue annotation can be used. As we can see, the NetBeans-generated
JPA entity uses this annotation. This annotation is used to indicate the strategy to use
to generate primary keys. All possible primary key generation strategies are listed in
the following table:
Primary key generation strategy Description
This indicates that the persistence provider will
automatically select a primary key generation
strategy. This is used by default if no primary key
generation strategy is specified.
This indicates that an identity column in the
database table the JPA entity maps to must be used
to generate the primary key value.
This indicates that a database sequence should be
used to generate the entity's primary key value.
This indicates that a database table should be used
to generate the entity's primary key value.
In most cases, the GenerationType.AUTO strategy works properly, so it is almost
always used. For this reason, the New Entity Class wizard uses this strategy.
When using the sequence or table generation strategies, we might
have to indicate the sequence or table used to generate the primary
keys. These can be specified by using the @SequenceGenerator
and @TableGenerator annotations, respectively. Refer to the Java
EE 7 JavaDoc at
api/ for details.
Search WWH ::

Custom Search