Java Reference
In-Depth Information
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 placed just above the
getter method for the primary key class. This is the strategy that the NetBeans wizard
follows. It is also correct to specify the annotation right above the field declaration.
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
GenerationType.AUTO
Indicates that the persistence provider will
automatically select a primary key generation
strategy. Used by default if no primary key
generation strategy is specified.
GenerationType.IDENTITY
Indicates that an identity column in the
database table the JPA entity maps to must be
used to generate the primary key value.
GenerationType.SEQUENCE
Indicates that a database sequence should
be used to generate the entity's primary key
value.
GenerationType.TABLE
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, therefore 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. Consult the Java EE 5
JavaDoc at http://java.sun.com/javaee/5/docs/api/ for details.
For further knowledge on primary key generation strategies you can refer EJB 3
Developer Guide by Michael Sikora , which is another book by Packt Publishing
( http://www.packtpub.com/developer-guide-for-ejb3/book ).
 
Search WWH ::




Custom Search