Table of Contents
This chapter provides an overview on how to annotate domain objects using JPA. It isn't comprehensive by any means, but should deal with most of the common cases. Hunt out a book dedicated to JPA persistence (such as like Bauer/King's Java Persistence with Hibernate) for a much more thorough treatment. See also Appendix B, Annotations Reference for an overview of the supported annotations.
Domain classes that are persistent entities - which is most of
them - should be annotated using
javax.persistence.Entity
. In addition - as
described in Chapter 2, JPA Objects / Naked Objects Restrictions -
JPA Objects requires that all entities are
annotated using
javax.persistence.@DiscriminatorValue
and must
define a single property to act as the identifier, annotated using
@javax.persistence.Id
. The type of this Id
property will depend on the number of instances expected, but will
generally be one of java.lang.Integer
,
java.lang.Long
.
JPA Objects itself does not care how the
values for the property are generated. It's usually easiest to get the
RDBMS to generate the IDs, using a
sequence or identity (or perhaps a table). This is specified using the
@javax.persistence.GeneratedValue
annotation.
@Entity @DiscriminatorValue("CUS") public class Customer { private Integer id; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { ... } private void setId(Integer id) { ... } ... }
Other generation strategies include SEQUENCE, IDENTITY and TABLE. Note that it isn't necessary for the setter to have public visibility.
For very large ranges it is also possible to use
java.lang.BigInteger
. This isn't a datatype
supported out-of-the-box by JPA, but Hibernate can be
made to support it. See for example this blog
post for details on how.
Alternatively, you can take control yourself, and hook into
JPA's @PrePersist
lifecycle
method.