JPA Annotation Reference
Version: May 5, 2006
The Java Persistence API (JPA), part of the Java Enterprise Edition 5 (Java EE 5) Enterprise Java Beans (EJB) 3.0 specification, greatly simplifies EJB persistence and provides an object-relational mapping approach that allows you to declaratively define how to map Java objects to relational database tables in a standard, portable way that works both inside a Java EE 5 application server and outside an EJB container in a Java Standard Edition (Java SE) 5 application.
Before JPA, Java EE applications represented persistent classes as a container-managed entity beans. Using JPA, you can designate any plain old Java object (POJO) class as a JPA entity: a Java object whose non-transient fields should be persisted to a relational database using the services of a JPA persistence provider (either within a Java EE EJB container or outside of an EJB container in a simple Java SE application).
When using JPA, you configure the JPA behavior of your entities using:
defaults: you can rely on default JPA behavior to do the right thing for the most common and important configuration.
annotations: a simple, expressive means of decorating Java source code with metadata that is compiled into the corresponding Java class files for interpretation at runtime by a JPA persistence provider to manage JPA behavior.
For example, to designate a Java class as a JPA entity, use the @Entity annotation as follows:
@Entity
public class Employee implements Serializable {
...
}
You can selectively decorate your entity classes with annotations to override defaults. This is known as configuration by exception.
orm.xml: you can use this XML file as an alternative to annotations entirely or in combination with annotations as a means of adding JPA entities or overriding annotations at deployment time.
persistence.xml: you can use this XML file to define one or more persistence units (see @PersistenceUnit) that define an entity manager's configuration by logically grouping:
Entity manager: including, entity manager provider (EntityManagerFactory), the entity managers obtained from it, and entity manager configuration (@PersistenceContext).
Persistent managed classes: the classes you intend to manage using an entity manager, namely, entity classes (@Entity), embeddable classes (@Embeddable and @Embedded), and mapped superclasses (@MappedSuperclass).
All persistent managed classes in a given persistence unit must be collocated in their mapping to a single database.
Mapping metadata: the information that describes how to map persistent managed classes to database tables. You specify mapping metadata using annotations on persistent managed classes and orm.xml files.
vendor extensions: you can use system properties to access functionality in a particular vendor's JPA persistence provider implementation that is outside the scope of the JPA specification.
This reference quotes extensively from the JSR-000220 Enterprise JavaBeans v.3.0 specification to summarize annotation information by category (see Table 1-1) and explains when and how you use these annotations to customize JPA behavior to meet your application requirements.
For more information, see:
Index of Annotations
Complete JPA annotation Javadoc
Table 1-1 JPA Annotations by Category
Category Description Annotations
Entity
By default, a JPA persistence provider assumes that a Java class is non-persistent and not eligible for JPA services unless it is decorated with this annotation.
Use this annotation to designate a plain old Java object (POJO) class as an entity so that you can use it with JPA services.
You must designate a class as a JPA entity (either using this annotation or the orm.xml file) before you can use the class with JPA services.
@Entity
Database Schema Attributes
By default, a JPA persistence provider assumes that an entity's name corresponds to a database table of the same name and that an entity's data member names correspond to database columns with the same names.
Use these annotations to override this default behavior and fine-tune the relationship between your object model and data model.
@Table
@SecondaryTable
@SecondaryTables
@Column
@JoinColumn
@JoinColumns
@PrimaryKeyJoinColumn
@PrimaryKeyJoinColumns
@JoinTable
@UniqueConstraint
Identity
By default, a JPA persistence provider assumes that each entity must have at least one field or property that serves as a primary key.
Use these annotations to specify one of the following:
one @Id
multiple @Id and an @IdClass
one @EmbeddedId
You can also use these annotations to fine-tune how your database maintains the identity of your entities.
@Id
@IdClass
@EmbeddedId
@GeneratedValue
@SequenceGenerator
@TableGenerator
Direct Mappings
By default, a JPA persistence provider automatically configures a Basic mapping for most Java primitive types, wrappers of the primitive types, and enums.
Use these annotations to fine-tune how your database implements these mappings.
@Basic
@Enumerated
@Temporal
@Lob
@Transient
Relationship Mappings
A JPA persistence provider requires that you map relationships explicitly.
Use these annotations to specify the type and characteristics of entity relationships to fine-tune how your database implements these relationships.
@OneToOne
@ManyToOne
@OneToMany
@ManyToMany
@MapKey
@OrderBy
Composition
By default, a JPA persistence provider assumes that every entity is mapped to its own table.
Use these annotations to override this behavior for entities that are owned by other entities.
@Embeddable
@Embedded
@AttributeOverride
@AttributeOverrides
@AssociationOverride
@AssociationOverrides
Inheritance
By default, a JPA persistence provider assumes that all persistent fields are defined by a single entity class.
Use these annotations if your entity class inherits some or all persistent fields from one or more superclasses.
@Inheritance
@DiscriminatorColumn
@DiscriminatorValue
@MappedSuperclass
@AssociationOverride
@AssociationOverrides
@AttributeOverride
@AttributeOverrides
Locking
By default, a JPA persistence provider assumes that the application is responsible for data consistency.
Use this annotation to enable JPA-managed optimistic locking (recommended).
@Version
Lifecycle Callback Events
By default, a JPA persistence provider handles all persistence operations.
Use these annotations to associate entity methods with JPA lifecycle events if you need to invoke custom logic at any point during the entity lifecycle. Figure 1-1 illustrates the relationship amongst these lifecycle events.
@PrePersist
@PostPersist
@PreRemove
@PostRemove
@PreUpdate
@PostUpdate
@PostLoad
@EntityListeners
@ExcludeDefaultListeners
@ExcludeSuperclassListeners
Entity Manager
In an application that uses a JPA persistence provider, you perform all persistence operations (create, read, update, and delete) using an instance of EntityManager.
Use these annotations to associate an entity with an entity manager and to customize the entity manager's environment.
@PersistenceUnit
@PersistenceUnits
@PersistenceContext
@PersistenceContexts
@PersistenceProperty
Queries
In an application that uses a JPA persistence provider, you can use an entity manager to create and execute queries dynamically or you can pre-define queries and execute them by name at run time.
Use these annotations to pre-define queries and manage their result sets.
@NamedQuery
@NamedQueries
@NamedNativeQuery
@NamedNativeQueries
@QueryHint
@ColumnResult
@EntityResult
@FieldResult
@SqlResultSetMapping
@SqlResultSetMappings
@AssociationOverride
By default, a JPA persistence provider automatically assumes that a subclass inherits both persistent properties and their association mappings as defined in a superclass.
Use the @AssociationOverride annotation to customize an @OneToOne or @ManyToOne mapping inherited from a @MappedSuperclass or @Embeddable to change the @JoinColumn associated with the field or property if the inherited column definition is incorrect for your entity (for example, if the inherited column name is incompatible with a pre-existing data model, or invalid as a column name in your database).
If you have more than one @AssociationOverride change to make, you must use @AssociationOverrides.
To customize a basic mapping to change its @Column, use @AttributeOverride.
Table 1-4 lists the attributes of this annotation. For more details, see the API.
Table 1-2 @AssociationOverride Attributes
Attribute Required Description
joinColumns
To specify the join columns that are being mapped to the persistent attribute, set joinColums to an array of JoinColumn instances (see @JoinColumn).
The mapping type will remain the same as is defined in the embeddable class or mapped superclass.
name
The name of the property in the embedded object that is being mapped if property-based access is being used, or the name of the field if field-based access is used.
Example 1-4 shows a @MappedSuperclass that the entity in Example 1-5 extends. Example 1-5 shows how to use @AssociationOverride in the entity subclass to override the @JoinColumn defined (by default) in the @MappedSuperclass Employee for the association to Address.
With the @AssociationOverride, the Employee table contains columns:
ID
VERSION
ADDR_ID
WAGE
Without the @AssociationOverride, the Employee table contains columns:
ID
VERSION
ADDRESS
WAGE
Example 1-1 @MappedSuperclass
@MappedSuperclass
public class Employee {
@Id protected Integer id;
@Version protected Integer version;
@ManyToOne protected Address address;
...
}
Example 1-2 @AssociationOverride
@Entity@AssociationOverride(name="address", joinColumns=@JoinColumn(name="ADDR_ID"))public class PartTimeEmployee extends Employee { @Column(name="WAGE") protected Float hourlyWage;
...
}
@AssociationOverrides
If you need to specify more than one @AssociationOverride, you must specify all your association overrides using a single @AssociationOverrides annotation.
Table 1-5 lists the attributes of this annotation. For more details, see the API.
Table 1-3 @AssociationOverrides Attributes
Attribute Required Description
value
To specify two or more association overrides, set value to an array of AssociationOverride instances (see @AssociationOverride).
Example 1-6 shows how to use this annotation to specify two association overrides.
Example 1-3 @AssociationOverrides
@Entity
@AssociationOverrides({
@AssociationOverride(name="address", joinColumn=@Column(name="ADDR_ID")),
@AssociationOverride(name="id", joinColumn=@Column(name="PTID"))
})
public class PartTimeEmployee extends Employee {
@Column(name="WAGE")
protected Float hourlyWage;
...
}
@AttributeOverride
By default, a JPA persistence provider automatically assumes that a subclass inherits both persistent properties and their basic mappings as defined in a superclass.
Use the @AttributeOverride annotation to customize a basic mapping inherited from a @MappedSuperclass or @Embeddable to change the @Column associated with the field or property if the inherited column definition is incorrect for your Entity. (for example, if the inherited column name is incompatible with a pre-existing data model, or invalid as a column name in your database).
If you have more than one @AttributeOverride change to make, you must use @AttributeOverrides.
To customize an association mapping to change its @JoinColumn, use @AssociationOverride.
Table 1-4 lists the attributes of this annotation. For more details, see the API.
Table 1-4 @AttributeOverride Attributes
Attribute Required Description
column
The @Column that is being mapped to the persistent attribute. The mapping type will remain the same as is defined in the embeddable class or mapped superclass.
name
The name of the property in the embedded object that is being mapped if property-based access is being used, or the name of the field if field-based access is used.
Example 1-4 shows a @MappedSuperclass that the entity in Example 1-5 extends. Example 1-5 shows how to use @AttributeOverride in the entity subclass to override the @Column defined (by default) in the @MappedSuperclass Employee for the basic mapping to Address.
With the @AttributeOverride, the Employee table contains columns:
ID
VERSION
ADDR_STRING
WAGE
Without the @AttributeOverride, the Employee table contains columns:
ID
VERSION
ADDRESS
WAGE
Example 1-4 @MappedSuperclass
@MappedSuperclass
public class Employee {
@Id protected Integer id;
@Version protected Integer version;
protected String address;
...
}
Example 1-5 @AttributeOverride
@Entity
@AttributeOverride(name="address", column=@Column(name="ADDR_STRING"))
public class PartTimeEmployee extends Employee {
@Column(name="WAGE")
protected Float hourlyWage;
...
}
@AttributeOverrides
If you need to specify more than one @AttributeOverride, you must specify all your attribute overrides using a single @AttributeOverrides annotation.
Table 1-5 lists the attributes of this annotation. For more details, see the API.
Table 1-5 @AttributeOverrides Attributes
Attribute Required Description
value
To specify two or more attribute overrides, set value to an array of AttributeOverride instances (see @AttributeOverride).
Example 1-6 shows how to use this annotation to specify two attribute overrides.
Example 1-6 @AttributeOverrides
@Entity
@AttributeOverrides({
@AttributeOverride(name="address", column=@Column(name="ADDR_ID")),
@AttributeOverride(name="id", column=@Column(name="PTID"))
})
public class PartTimeEmployee extends Employee {
@Column(name="WAGE")
protected Float hourlyWage;
public PartTimeEmployee() {
...
}
public Float getHourlyWage() {
...
}
public void setHourlyWage(Float wage) {
...
}
}
@Basic
By default, a JPA persistence provider automatically configures a @Basic mapping for most Java primitive types, wrappers of the primitive types, and enums.
Use the @Basic annotation to:
configure the fetch type to LAZY
configure the mapping to forbid null values (for non-primitive types) in case null values are inappropriate for your application
Table 1-6 lists the attributes of this annotation. For more details, see the API.
Table 1-6 @Basic Attributes
Attribute Required Description
fetch
Default: FetchType.EAGER.
By default, a JPA persistence provider uses a fetch type of EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.
If this is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).
optional
Default: true.
By default a JPA persistence provider assumes that the value of all (non-primitive) fields and properties may be null.
If this is inappropriate for your application, set optional to false.
Example 1-7 shows how to use this annotation to specify a fetch type of LAZY for a basic mapping.
Example 1-7 @Basic
@Entity
public class Employee implements Serializable {
...
@Basic(fetch=LAZY)
protected String getName() {
return name;
}
...
}
@Column
By default, a JPA persistence provider assumes that each of an entity's persistent fields is stored in a database table column whose name matches that of the persistent field.
Use the @Column annotation:
to associate a persistent field with a different name if the default column name is awkward, incompatible with a pre-existing data model, or invalid as a column name in your database
to associate a persistent field with a column in a secondary table (see @SecondaryTable)
to fine-tune the characteristics of a column in your database
Table 1-7 lists the attributes of this annotation. For more details, see the API.
Table 1-7 @Column Attributes
Attribute Required Description
columnDefinition
Default: empty String.
By default, JPA creates a database table column with minimal SQL.
If you want the column created with more specialized options, set columnDefinition to the SQL fragment that you want JPA to use when generating the DDL for the column.
Note: When you capture DDL information in annotations, some JPA persistence providers can use the DDL when generating your database schema. For example, see "TopLink JPA Extensions for Java2DB Schema Generation".
insertable
Default: true.
By default, a JPA persistence provider assumes that all columns are always included in SQL INSERT statements.
If this column should not be included in these statements, set insertable to false.
length
Default: 255
By default, a JPA persistence provider assumes that all columns have a maximum length of 255 characters when used to hold a String value.
If this column width is inappropriate for your application or database, set the length to the int value appropriate for your database column.
name
Default: a JPA persistence provider assumes that each of an entity's persistent fields is stored in a database table column whose name matches that of the persistent field or property.
To specify an alternative column name, set name to the String column name you want.
nullable
Default: true.
By default, a JPA persistence provider assumes that all columns are allowed to contain a null value.
If this column is not allowed to contain a null value, set nullable to false.
precision
Default: 0.
By default, a JPA persistence provider assumes that all columns have a precision of 0 when used to hold a decimal (exact numeric) value.
If this precision is inappropriate for your application or database, set precision to the appropriate int precision.
scale
Default: 0.
By default, a JPA persistence provider assumes that all columns have a scale of 0 when used to hold a decimal (exact numeric) value.
If this scale is inappropriate for your application or database, set scale to the appropriate int precision.
table
Default: a JPA persistence provider assumes that all the persistent fields of an entity are stored in a single database table whose name is the entity name (see @Table).
If this column is associated with a secondary table (see @SecondaryTable), set name to the String name of the appropriate secondary table name as Example 1-8 shows.
unique
Default: false.
By default, a JPA persistence provider assumes that all columns are allowed to contain duplicate values.
If this column is not allowed to contain duplicate values, set unique to true. When set to true, this is equivalent to using @UniqueConstraint at the table level.
updatable
Default: true.
By default, a JPA persistence provider assumes that a column is always included in SQL UPDATE statements.
If this column should not be included in these statements, set updatable to false.
Example 1-8 shows how to use this annotation to make JPA persist empId to column EMP_NUM in secondary table EMP_HR. By default, JPA persists empName to column empName in primary table Employee.
Example 1-8 @Column
@Entity
@SecondaryTable(name="EMP_HR")
public class Employee implements Serializable {
...
@Column(name="EMP_NUM", table="EMP_HR")
private Long empId;
private String empName;
...
}
@ColumnResult
When you execute a @NamedNativeQuery, it can return entities (including entities of different types), scalar values, or a combination of both.
Use the @ColumnResult annotation to return scalar values. The type of the scalar is determined by the type of the column you identify in the @ColumnResult.
For more information, see also @EntityResult, @FieldResult, and @SqlResultSetMapping.
Table 1-8 lists the attributes of this annotation. For more details, see the API.
Table 1-8 @ColumnResult Attributes
Attribute Required Description
name
Set name to the String equivalent of a column name in the SELECT statement of a native SQL query. If you use a column alias (AS statement) in the SELECT, then set name to the column alias.
Example 1-9 shows how to use this annotation to include Item (see Example 1-10 scalar name in the result list (see Example 1-11). In this case, the result list would be a List of Object arrays like: {[Order, "Shoes"], [Order, "Socks"], ...}.
Example 1-9 Order Entity With @ColumnResult
@SqlResultSetMapping(
name="OrderResults",
entities={
@EntityResult(
entityClass=Order.class,
fields={
@FieldResult(name="id", column="order_id"),
@FieldResult(name="quantity", column="order_quantity"),
@FieldResult(name="item", column="order_item")
}
)
},
columns={
@ColumnResult(
name="item_name"
)
}
)
@Entity
public class Order {
@Id
protected int id;
protected long quantity;
protected Item item;
...
}
Example 1-10 Item Entity
@Entity
public class Item {
@Id
protected int id;
protected String name;
...
}
Example 1-11 Native Query Using an @SqlResultSetMapping With an @ColumnResult
Query q = entityManager.createNativeQuery(
"SELECT o.id AS order_id, " +
"o.quantity AS order_quantity, " +
"o.item AS order_item, " +
"i.name AS item_name, " +
"FROM Order o, Item i " +
"WHERE (order_quantity > 25) AND (order_item = i.id)",
"OrderResults"
);
List resultList = q.getResultList();
// List of Object arrays: {[Order, "Shoes"], [Order, "Socks"], ...}
@DiscriminatorColumn
By default, when @Inheritance attribute strategy is InheritanceType.SINGLE_TABLE or JOINED, the JPA persistence provider creates a discriminator column named DTYPE to differentiate classes in an inheritance hierarchy.
Use the @DiscriminatorColumn annotation:
to specify a discriminator column name if the column name in your data model is not the default column name DTYPE.
to specify a discriminator column length that is appropriate for your application or a pre-existing data model
to fine-tune the characteristics of the discriminator column in your database
Table 1-9 lists the attributes of this annotation. For more details, see the API.
Table 1-9 @DiscriminatorColumn Attributes
Attribute Required Description
columnDefinition
Default: empty String.
By default, a JPA persistence provider creates a database table column with minimal SQL.
If you want the column created with more specialized options, set columnDefinition to the SQL fragment that you want JPA to use when generating the DDL for the column.
discriminatorType
Default: DiscriminatorType.STRING.
By default, a JPA persistence provider assumes that the discriminator type is a String.
If you want to use a different type, set discriminatorType to DiscriminatorType.CHAR or DiscriminatorType.INTEGER.
Your @DiscriminatorValue must conform to this type.
length
Default: 31
By default, a JPA persistence provider assumes that the discriminator column has a maximum length of 255 characters when used to hold a String value.
If this column width is inappropriate for your application or database, set the length to the int value appropriate for your database column.
Your @DiscriminatorValue must conform to this length.
name
Default: a JPA persistence provider assumes that the discriminator column is named "DTYPE".
To specify an alternative column name, set name to the String column name you want.
Example 1-12 shows how to use this annotation to specify a discriminator column named DISC of type STRING and length 20. In this example, the @DiscriminatorValue for this class is specified as CUST. The subclass in Example 1-13 specifies its own @DiscriminatorValue of VIP. In both Customer and ValuedCustomer, the value for @DiscriminatorValue must be convertable to the type specified by @DiscriminatorColumn attribute discriminatorType and must conform to @DiscriminatorColumn attribute length.
Example 1-12 @DiscriminatorColumn and @DiscriminatorValue - Root Class
@Entity
@Table(name="CUST")
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
@DiscriminatorValue(value-"CUST")
public class Customer {
...
}
Example 1-13 @DiscriminatorValue - Subclass
@Entity
@DiscriminatorValue(value="VIP")
public class ValuedCustomer extends Customer {
...
}
@DiscriminatorValue
By default, when @Inheritance attribute strategy is InheritanceType.SINGLE_TABLE or JOINED, the JPA persistence provider uses a @DiscriminatorColumn to differentiate classes in the inheritance hierarchy by entity name (see @Entity).
Use the @DiscriminatorValue annotation to specify the discriminator value used to differentiate an entity in this inheritance hierarchy:
if the entity name is inappropriate for this application
to match an existing database schema
Table 1-10 lists the attributes of this annotation. For more details, see the API.
Table 1-10 @DiscriminatorValue Attributes
Attribute Required Description
value
Set value to the String equivalent of a discriminator value that conforms to the @DiscriminatorColumn attributes discriminatorType and length.
Example 1-14 shows how to use this annotation to specify a discriminator column named DISC of type STRING and length 20. In this example, the @DiscriminatorValue for this class is specified as CUST. The subclass in Example 1-15 specifies its own @DiscriminatorValue of VIP. In both Customer and ValuedCustomer, the value for @DiscriminatorValue must be convertable to the type specified by @DiscriminatorColumn attribute discriminatorType and must conform to @DiscriminatorColumn attribute length.
Example 1-14 @DiscriminatorColumn and @DiscriminatorValue - Root Class
@Entity
@Table(name="CUST")
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
@DiscriminatorValue(value-"CUST")
public class Customer {
...
}
Example 1-15 @DiscriminatorValue - Subclass
@Entity
@DiscriminatorValue(value="VIP")
public class ValuedCustomer extends Customer {
...
}
@Embeddable
By default, a JPA persistence provider assumes that every entity is persisted to its own database table.
Use the @Embeddable annotation to specify a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the entity.
This annotation has no attributes. For more details, see the API.
Example 1-16 shows how to use this annotation to specify that class EmploymentPeriod may be embedded in an entity when used as the type for a persistent field annotated as @Embedded (see Example 1-17).
Example 1-16 @Embeddable
@Embeddable
public class EmploymentPeriod {
java.util.Date startDate;
java.util.Date endDate;
...
}
@Embedded
By default, a JPA persistence provider assumes that every entity is persisted to its own database table.
Use the @Embedded annotation to specify a persistent field whose @Embeddable type can be stored as an intrinsic part of the owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the owning entity.
You can use @Embedded in conjunction with @Embeddable to model a strict ownership relationship so that if the owning object is removed, the owned object is also removed.
Embedded objects should not be mapped across more than one table.
By deafult, column definitions (see @Column) specified in the @Embeddable class apply to the @Embedded class. If you want to override these column definitions, use @AttributeOverride.
This annotation has no attributes. For more details, see the API.
Example 1-17 shows how to use this annotation to specify that @Embeddable class EmploymentPeriod (see Example 1-16) may be embedded in the entity class using the specified attribute overrides (see @AttributeOverride). If you do not need attribute overrides, you can omit the @Embedded annotation entirely: the JPA persistence provider will infer that EmploymentPeriod is embedded from its @Embeddable annotation.
Example 1-17 @Embedded
@Entity
public class Employee implements Serializable {
...
@Embedded
@AttributeOverrides({
@AttributeOverride(name="startDate", column=@Column("EMP_START")),
@AttributeOverride(name="endDate", column=@Column("EMP_END"))
)
public EmploymentPeriod getEmploymentPeriod() {
...
}
...
}
@EmbeddedId
Use the @EmbeddedId annotation to specify an embeddable composite primary key class (usually made up of two or more primitive or JDK object types) owned by the entity. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns.
A composite primary key class has the following characteristics:
It is a plain old Java object (POJO) class.
It must be public and must have a public no-argument constructor.
If you use property-based access, the properties of the primary key class must be public or protected.
It must be serializable.
It must define equals and hashCode methods.
The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
Alternatively, you can make the composite primary key class a non-embedded class (see @IdClass).
This annotation has no attributes. For more details, see the API.
Example 1-18 shows a typical composite primary key class, annotated as @Embeddable. Example 1-19 shows how to configure an entity with this embeddable composite primary key class using the @EmbeddedId annotation.
Example 1-18 Embeddable Composite Primary Key Class
@Embeddable
public class EmployeePK implements Serializable
{
private String name;
private long id;
public EmployeePK()
{
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public int hashCode()
{
return (int) name.hashCode() + id;
}
public boolean equals(Object obj)
{
if (obj == this) return true;
if (!(obj instanceof EmployeePK)) return false;
if (obj == null) return false;
EmployeePK pk = (EmployeePK) obj;
return pk.id == id && pk.name.equals(name);
}
}
Example 1-19 @EmbeddedId
@Entity
public class Employee implements Serializable
{
EmployeePK primaryKey;
public Employee()
{
}
@EmbeddedId
public EmployeePK getPrimaryKey()
{
return primaryKey;
}
public void setPrimaryKey(EmployeePK pk)
{
primaryKey = pk;
}
...
}
@Entity
Use the @Entity annotation to designate a plain old Java object (POJO) class as an entity and make it eligible for JPA services. You must designate a POJO class as an entity before you can use any other JPA annotations.
Table 1-11 lists the attributes of this annotation. For more details, see the API.
Table 1-11 @Entity Attributes
Attribute Required Description
name
Default: a JPA persistence provider assumes that the name of the entity is the name of the entity class. In Example 1-20, the default name is "Employee".
If the entity class name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a table name in your database, set name to an alternative String value.
Example 1-20 shows how to use this annotation.
Example 1-20 @Entity
@Entity
public class Employee implements Serializable {
...
}
@EntityListeners
You can use lifecycle annotations (see Lifecycle Event Annotations) to designate methods in an entity that execute your logic when specified lifecycle events occur.
Use the @EntityListeners annotation to associate one or more entity listener classes with an @Entity or @MappedSuperclass if you need to execute logic when specified lifecycle events occur and:
You do not want to expose lifecycle listener methods in your entity API.
You want to share lifecycle listener logic between different entity types.
When a lifecycle event occurs on the entity or subclass, a JPA persistence provider notifies each entity listener class in the order in which listeners are defined, and invokes the entity listener method (if any) annotated with the corresponding lifecycle event type.
An entity listener class has the following characteristics:
It is a plain old Java object (POJO) class
It has one or more callback methods with the following signature:
public void <MethodName>(Object)
You may specify an argument type of Object or the type of the entity class you will associate the entity listener with.
It has each callback method annotated with one or more lifecycle event annotations.
You may associate a lifecycle event with one and only one callback listener method but you may associate a given callback listener method with more than one lifecycle event.
If you use entity listeners, you can manage what entity listeners are invoked using @ExcludeDefaultListeners and @ExcludeSuperclassListeners.
Table 1-12 lists the attributes of this annotation. For more details, see the API.
Table 1-12 @EntityListeners Attributes
Attribute Required Description
value
To specify the list of entity listener classes for an @Entity or @MappedSuperclass, set value to a Class array of entity listener classes.
Example 1-21 shows how to use this annotation to associate entity listener classes EmployeePersistListener (see Example 1-22) and EmployeeRemoveListener (see Example 1-23) with the entity Employee. Example 1-23 shows that you can associate more than one lifecycle event with a given entity listener class method but any given lifecycle event may appear in an entity listener class only once.
Example 1-21 @EntityListeners
@Entity
@EntityListeners(value={EmployeePersistListner.class, EmployeeRemoveListener.class})
public class Employee implements Serializable {
...
}
Example 1-22 EmployeePersistListener
public class EmployeePersistListener {
@PrePersist
employeePrePersist(Object employee) {
...
}
...
}
Example 1-23 EmployeeRemoveListener
public class EmployeeRemoveListener {
@PreRemove
@PostRemove
employeePreRemove(Object employee) {
...
}
...
}
@EntityResult
When you execute a @NamedNativeQuery, it can return entities (including entities of different types), scalar values, or a combination of both.
Use the @EntityResult annotation to return entities.
For more information, see also @ColumnResult, @FieldResult, and @SqlResultSetMapping.
Table 1-8 lists the attributes of this annotation. For more details, see the API.
Table 1-13 @EntityResult Attributes
Attribute Required Description
entityClass
Set entityClass to the Class of the entity returned by the SELECT statement.
discriminatorColumn
Default: empty String.
By deafult, a JPA persistence provider assumes that a discriminator column (see @Inheritance) is not included in the SELECT statement.
If you use a discriminator column in your SELECT statement, set discriminatorColumn to the String column name you use.
fields
Default: empty FieldResult array.
By default, a JPA persistence provider assumes that the SELECT statement includes all the columns that correspond to all the fields or properties of the entity returned and the column names in the SELECT statement correspond to the field or property names (AS statements are not used).
If your SELECT statement includes only some of the columns that correspond to the fields or properties of the entity returned or the column names in the SELECT statement do not correspond to the field or property names (AS statements are used), set fields to an array of @FieldResult, one @FieldResult per column in the SELECT statement.
Example 1-24 shows how to use this annotation to include both Order and Item (see Example 1-25) entities in the result list (see Example 1-26). In this case, the result list would be a List of Object arrays like: {[Order, Item], [Order, Item], ...}.
Example 1-24 Order Entity With @EntityResult
@SqlResultSetMapping(
name="OrderResults",
entities={
@EntityResult(
entityClass=Order.class,
fields={
@FieldResult(name="id", column="order_id"),
@FieldResult(name="quantity", column="order_quantity"),
@FieldResult(name="item", column="order_item")
}
),
@EntityResult(
entityClass=Item.class,
fields={
@FieldResult(name="id", column="item_id"),
@FieldResult(name="name", column="item_name"),
}
)
}
)
@Entity
public class Order {
@Id
protected int id;
protected long quantity;
protected Item item;
...
}
Example 1-25 Item Entity
@Entity
public class Item {
@Id
protected int id;
protected String name;
...
}
Example 1-26 Native Query Using an @SqlResultSetMapping With an @EntityResult
Query q = entityManager.createNativeQuery(
"SELECT o.id AS order_id, " +
"o.quantity AS order_quantity, " +
"o.item AS order_item, " +
"i.id AS item_id, " +
"i.name AS item_name, " +
"FROM Order o, Item i " +
"WHERE (order_quantity > 25) AND (order_item = i.id)",
"OrderResults"
);
List resultList = q.getResultList();
// List of Object arrays: {[Order, Item], [Order, Item], ...}
@Enumerated
By default, a JPA persistence provider persists the ordinal values of enumerated constants.
Use the @Enumerated annotation to specify whether the JPA persistence provider should persist ordinal or String values of enumerated constants if the String value suits your application requirements or to match an existing database schema.
This annotation can be used with @Basic.
Table 1-14 lists the attributes of this annotation. For more details, see the API.
Table 1-14 @Enumerated Attributes
Attribute Required Description
value
Default: EnumType.ORDINAL.
By default, a JPA persistence provider assumes that for a property or field mapped to an enumerated constant, the ordinal value should be persisted. In Example 1-28, the ordinal value of EmployeeStatus is written to the database when Employee is persisted.
If you want the String value of the enumerated constant persisted, set value to EnumType.STRING.
Given the enumerated constants in Example 1-27, Example 1-28 shows how to use this annotation to specify that the String value of SalaryRate should be written to the database when Employee is persisted. By default, the ordinal value of EmployeeStatus is written to the database.
Example 1-27 Enumerated Constants
public enum EmployeeStatus {FULL_TIME, PART_TIME, CONTRACT}
public enum SalaryRate {JUNIOR, SENIOR, MANAGER, EXECUTIVE}
Example 1-28 @Enumerated
@Entity
public class Employee {
...
public EmployeeStatus getStatus() {
...
}
@Enumerated(STRING)
public SalaryRate getPayScale() {
...
}
...
}
@ExcludeDefaultListeners
A default listener is a lifecycle event listener class specified in the orm.xml file that applies to all entities in a persistence unit (see @PersistenceUnit). A JPA persistence provider first invokes default listeners, if any, in the order defined in the orm.xml file, before any other entity listeners (see @EntityListeners).
Use the @ExcludeDefaultListeners annotation to override (and prevent) default listener execution for a given @Entity or @MappedSuperclass if default listener behavior does not apply.
This annotation has no attributes. For more details, see the API.
Example 1-29 shows how to use this annotation to specify that default listeners should not be executed for the Employee entity.
Example 1-29 @ExcludeDefaultListeners
@Entity
@ExcludeDefaultListeners
public class Employee implements Serializable {
...
}
@ExcludeSuperclassListeners
If the @Entity and @MappedSuperclass classes in an inheritance hierarchy define @EntityListeners, by default, a JPA persistence provider invokes superclass listeners before subclass listeners.
Use the @ExcludeSuperclassListeners annotation to override (and prevent) superclass listener execution for a given @Entity or @MappedSuperclass if superclass listener behavior does not apply.
The @ExcludeSuperclassListeners annotation does not affect default listeners (see @ExcludeDefaultListeners).
This annotation has no attributes. For more details, see the API.
Example 1-29 shows how to use this annotation to specify that superclass listener EmployeeListener should not be executed for the PartTimeEmployee entity but default listeners and subclass listeners PartTimeEmployeeListener1 and PartTimeEmployeeListener2 are executed.
Example 1-30 Entity Listeners at the Superclass Level
@MappedSuperclass
@EntityListeners(value={EmployeeListener.class})
public class Employee {
...
}
Example 1-31 @ExcludeSuperclassListeners at the Subclass Level
@Entity
@ExcludeSuperclassListeners
@EntityListners(value={PartTimeEmployeeListener1.class, PartTimeEmployeeListener2.class})
public class PartTimeEmployee extends Employee {
...
}
@FieldResult
When you execute a @NamedNativeQuery, it can return entities (including entities of different types), scalar values, or a combination of both.
By default, a JPA persistence provider assumes that when returning entities with @EntityResult, the SELECT statement includes all the columns that correspond to all the fields or properties of the entity returned and the column names in the SELECT statement correspond to the field or property names (AS statements are not used).
Use the @FieldResult annotation to map columns in the SELECT statement to fields or properties when returning entities with @EntityResult if your SELECT statement includes only some of the columns that correspond to the fields or properties of the entity returned or the column names in the SELECT statement do not correspond to the field or property names (AS statements are used).
For more information, see also @ColumnResult and @SqlResultSetMapping.
Table 1-15 lists the attributes of this annotation. For more details, see the API.
Table 1-15 @FieldResult Attributes
Attribute Required Description
column
Set column to the String name of the column used in the SELECT statement. If you use a column alias (AS statement) in the SELECT, then set column to the column alias.
name
Set name to the entity's field or property name (as a String) that corresponds to the column name specified by the column attribute.
Example 1-32 shows how to use this annotation to include both Order and Item (see Example 1-33) entities in the result list (see Example 1-34). In this case, the result list would be a List of Object arrays like: {[Order, Item], [Order, Item], ...}.
Example 1-32 Order Entity With @EntityResult and @FieldResult
@SqlResultSetMapping(
name="OrderResults",
entities={
@EntityResult(
entityClass=Order.class,
fields={
@FieldResult(name="id", column="order_id"),
@FieldResult(name="quantity", column="order_quantity"),
@FieldResult(name="item", column="order_item")
}
),
@EntityResult(
entityClass=Item.class,
fields={
@FieldResult(name="id", column="item_id"),
@FieldResult(name="name", column="item_name"),
}
)
}
)
@Entity
public class Order {
@Id
protected int id;
protected long quantity;
protected Item item;
...
}
Example 1-33 Item Entity
@Entity
public class Item {
@Id
protected int id;
protected String name;
...
}
Example 1-34 Native Query Using an @SqlResultSetMapping With an @EntityResult
Query q = entityManager.createNativeQuery(
"SELECT o.id AS order_id, " +
"o.quantity AS order_quantity, " +
"o.item AS order_item, " +
"i.id AS item_id, " +
"i.name AS item_name, " +
"FROM Order o, Item i " +
"WHERE (order_quantity > 25) AND (order_item = i.id)",
"OrderResults"
);
List resultList = q.getResultList();
// List of Object arrays: {[Order, Item], [Order, Item], ...}
@GeneratedValue
By default, the JPA persistence provider manages the provision of unique identifiers for entity primary keys (see @Id).
Use the @GeneratedValue annotation if you want to fine tune this mechanism to:
override the type of identity value generation selected by the persistence provider for your database if you feel another generator type is more appropriate for your database or application
override the primary key generator name selected by the persistence provider if this name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a primary key generator name in your database
Table 1-16 lists the attributes of this annotation. For more details, see the API.
Table 1-16 @GeneratedValue Attributes
Attribute Required Description
generator
Default: the JPA persistence provider assigns a name to the primary key generator it selects.
If this name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a primary key generator name in your database, set generator to the String generator name you want to use.
strategy
Default: GenerationType.AUTO.
By deafult, a JPA persistence provider chooses the type of primary key generator that is most appropriate for the underlying database.
If you feel that another generator type is more appropriate for your database or application, set strategy to the GeneratorType you want:
IDENTITY - specify that the persistence provider use a database identity column
AUTO - specify that the persistence provider should choose a primary key generator that is most appropriate for the underlying database.
SEQUENCE - specify that the persistence provider use a database sequence (see @SequenceGenerator)
TABLE - specify that the persistence provider assign primary keys for the entity using an underlying database table to ensure uniqueness (see @TableGenerator)
Example 1-35 shows how to use this annotation to tell the persistence provider to use a primary key generator of type GeneratorType.SEQUENCE named CUST_SEQ.
Example 1-35 @GeneratedValue
@Entity
public class Employee implements Serializable {
...
@Id
@GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
@Column(name="CUST_ID")
public Long getId() {
return id;
}
...
}
@Id
Use the @Id annotation to designate one or more persistent fields or properties as the entity's primary key.
For each entity, you must designate at least one of the following:
one @Id
multiple @Id and an @IdClass (for a composite primary key)
one @EmbeddedId
This annotation has no attributes. For more details, see the API.
By default, the JPA persistence provider chooses the most appropriate primary key generator (see @GeneratedValue) and is responsible for managing primary key values: you do not need to take any further action. You do not need to take any further action if you are content to use the JPA persistence provider's default key generation mechanism.
Example 1-36 shows how to use this annotation to designate persistent field empID as the primary key of the Employee table.
Example 1-36 @Id
@Entity
public class Employee implements Serializable {
@Id
private int empID;
...
}
@IdClass
Use the @IdClass annotation to specify a composite primary key class (usually made up of two or more primitive or JDK object types) for an entity. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns.
A composite primary key class has the following characteristics:
It is a plain old Java object (POJO) class.
It must be public and must have a public no-argument constructor.
If you use property-based access, the properties of the primary key class must be public or protected.
It must be serializable.
It must define equals and hashCode methods.
The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
Its fields or properties must correspond in type and name to the entity primary key fields or properties annotated with @Id.
Alternatively, you can make the composite primary key class an embedded class owned by the entity (see @EmbeddedId).
Table 1-17 lists the attributes of this annotation. For more details, see the API.
Table 1-17 @IdClass Attributes
Attribute Required Description
value
To specify a composite primary key class, set value to the Class you want (see @AttributeOverride).
Example 1-37 shows a non-embedded composite primary key class. In this class, fields empName and birthDay must correspond in name and type to properties in the entity class. Example 1-38 shows how to configure an EJB 3.0 entity with this non-embedded composite primary key class using the @IdClass annotation. Because entity class fields empName and birthDay are used in the primary key, you must also annotate them using the @Id annotation.
Example 1-37 Non-Embedded Composite Primary Key Class
public class EmployeePK implements Serializable
{
private String empName;
private Date birthDay;
public EmployeePK()
{
}
public String getName()
{
return empName;
}
public void setName(String name)
{
empName = name;
}
public long getDateOfBirth()
{
return birthDay;
}
public void setDateOfBirth(Date date)
{
birthDay = date;
}
public int hashCode()
{
return (int) empName.hashCode();
}
public boolean equals(Object obj)
{
if (obj == this) return true;
if (!(obj instanceof EmployeePK)) return false;
if (obj == null) return false;
EmployeePK pk = (EmployeePK) obj;
return pk.birthDay == birthDay && pk.empName.equals(empName);
}
}
Example 1-38 @IdClass
@IdClass(EmployeePK.class)
@Entity
public class Employee
{
@Id String empName;
@Id Date birthDay;
...
}
@Inheritance
By default, the JPA persistence provider automatically manages the persistence of entities in an inheritance hierarchy.
Use the @Inheritance annotation to customize the persistence provider's inheritance hierarchy support to improve application performance or to match an existing data model.
Table 1-18 lists the attributes of this annotation. For more details, see the API.
Table 1-18 @Inheritance Attributes
Attribute Required Description
strategy
Default: InheritanceType.SINGLE_TABLE.
By deafult, a JPA persistence provider assumes that all the classes in a hierarchy are mapped to a single table differentiated by the discriminator value (see @DiscriminatorValue) in the table's discriminator column (see @DiscriminatorColumn).
If this is not appropriate for your application or if you must match an existing data model, set strategy to the desired InheritanceType:
SINGLE_TABLEFoot 1 - all the classes in a hierarchy are mapped to a single table. The table has a discriminator column (see @DiscriminatorColumn) whose value (see @DiscriminatorValue) identifies the specific subclass to which the instance that is represented by the row belongs.
TABLE_PER_CLASS - each class is mapped to a separate table. All properties of the class, including inherited properties, are mapped to columns of the table for the class.
JOINED - the root of the class hierarchy is represented by a single table and each subclass is represented by a separate table. Each subclass table contains only those fields that are specific to the subclass (not inherited from its superclass) and primary key columns that serve as foreign keys to the primary keys of the superclass table.
Footnote 1 This option provides the best support for both polymorphic relationships between entities and queries that range over the class hierarchy. The disadvantages of this option include the need to make nullable columns that should be NOT NULL.
Example 1-39 shows how to use this annotation to specify that all subclasses of Customer will use InheritanceType.JOINED. The subclass in Example 1-40 will be mapped to its own table that contains a column for each the persistent properties of ValuedCustomer and one foreign key column that contains the primary key to the Customer table.
Example 1-39 @Inheritance - Root Class Using JOINED
@Entity@Inheritance(strategy=JOINED)public class Customer {
@Id
private int customerId;
...
}
Example 1-40 @Inheritance - Subclass Using JOINED
@Entity
public class ValuedCustomer extends Customer {
...
}
In Example 1-41, by default, InheritanceType.SINGLE_TABLE applies to Customer and all its subclasses. In this example, the default discriminator table column DTYPE (see @DiscriminatorColumn) is specified as having a discriminator type of INTEGER and the @DiscriminatorValue for Customer is specified as 1. Example 1-42 shows how to specify the discriminator value for subclass ValuedCustomer as 2. In this example, all the persistent properties of both Customer and ValuedCustomer will be mapped to a single table.
Example 1-41 @Inheritance - Root Class Specifying its Discriminator Column
@Entity
@DiscriminatorColumn(discriminatorType=DiscriminatorType.INTEGER)
@DiscriminatorValue(value="1")
public class Customer {
...
}
Example 1-42 @Inheritance - Subclass Specifying its Discriminator Value
@Entity
@DiscriminatorValue(value="2")
public class ValuedCustomer extends Customer {
...
}
@JoinColumn
By default, in an entity association, a JPA persistence provider assumes a database schema based on existing names (such as field or property names) so that it can automatically determine the single join column (the column that contains the foreign key) to use.
Use the @JoinColumn annotation if:
the default join column name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a column name in your database
you want to join using a column in the foreign table other than the primary key column
you want to use two or more join columns (see @JoinColumns)
you want to use a join table (see @JoinTable)
Table 1-19 lists the attributes of this annotation. For more details, see the API.
Table 1-19 @JoinColumn Attributes
Attribute Required Description
columnDefinition
Default: empty String.
JPA creates a database table column with minimal SQL.
If you want the column created with more specialized options, set columnDefinition to the String SQL fragment that you want JPA to use when generating the DDL for the column.
insertable
Default: true.
By default, a JPA persistence provider assumes that it can insert into all table columns.
If this column is read-only, set insertable to false.
name
Default: if you are using a single join column, a JPA persistence provider assumes that the name of the foreign key column is one of the concatenation of the following:
the name of the referencing relationship property + "_" + the name of the referenced primary key column.
the name of the field of the referencing entity + "_" + the name of the referenced primary key column.
If there is no such referencing relationship property or field in the entity (see @JoinTable), the join column name is formed as the concatenation of: the name of the entity + "_" + the name of the referenced primary key column.
This is the name of the foreign key column. If the join is for a one-to-one or many-to-one entity relationship, this column is in the table of the source entity. If the join is for a many-to-many entity relationship, this column is in a join table (see @JoinTable).
If the join column name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a column name in your database, set name to the String column name you want.
nullable
Default: true.
By default, a JPA persistence provider assumes that all columns are allowed to contain a null value.
If this column is not allowed to contain a null value, set nullable to false.
referencedColumnName
Default: if you are using a single join column, a JPA persistence provider assumes that in an entity relationship, the referenced column name is the name of the referenced primary key column.
If used in a join table (see @JoinTable), the referenced key column is in the entity table of the owning entity, or inverse entity if the join is part of the inverse join definition.
To specify an alternative column name, set referencedColumnName to the String column name you want.
table
Default: a JPA persistence provider assumes that all the persistent fields of an entity are stored in a single database table whose name is the entity class name (see @Table).
If this column is associated with a secondary table (see @SecondaryTable), set name to the String name of the appropriate secondary table name as Example 1-8 shows.
unique
Default: false.
By default, a JPA persistence provider assumes that all columns are allowed to contain duplicate values.
If this column is not allowed to contain duplicate values, set unique to true.
updatable
Default: true.
By default, a JPA persistence provider assumes that it can update all table columns.
If this column is read-only, set updatable to false
Example 1-43 shows how to use this annotation to make JPA use database table Employee column ADDR_ID as the join column.
Example 1-43 @JoinColumn
@Entity
public class Employee implements Serializable {
...
@ManyToOne
@JoinColumn(name="ADDR_ID")
public Address getAddress() {
return address;
}
}
@JoinColumns
By default, in an entity association, a JPA persistence provider assumes that a single join column is used.
Use the @JoinColumns annotation if you want to specify two or more join columns (that is, a composite primary key).
Table 1-20 lists the attributes of this annotation. For more details, see the API.
Table 1-20 @JoinColumns Attributes
Attribute Required Description
value
To specify two or more join columns, set value to an array of JoinColumn instances (see @JoinColumn).
Example 1-44 shows how to use this annotation to specify the names of two join columns: ADDR_ID in the Employee table which contains foreign key values from Address table column ID and ADDR_ZIP in the Employee table which contains foreign key values from Address table column ZIP.
Example 1-44 @JoinColumns
@Entity
public class Employee implements Serializable {
...
@ManyToOne
@JoinColumns({
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
public Address getAddress() {
return address;
}
...
}
@JoinTable
By default, a JPA persistence provider uses a single join table when mapping entity associations on the owning side of a many-to-many association, or in a unidirectional one-to-many association. The join table name and its column names are all specified by defaults and a JPA persistence provider assumes that there is a join column for each primary key column in the primary table of the entity on the owning side of the relationship.
Use the @JoinTable annotation if you want to:
change the name of the join table because the default name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a table name in your database
change the column names of the join table because the default names are awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a column name in your database
configure the join table with a specific catalog or schema
configure one or more join table columns with a unique constraint
use multiple join columns per entity
Table 1-21 lists the attributes of this annotation. For more details, see the API.
Table 1-21 @JoinTable Attributes
Attribute Required Description
catalog
Default: empty String.
By deafult, JPA uses whatever the default catalog is for your database.
If the default catalog is inappropriate for your application, set the catalog to the String catalog name to use.
inverseJoinColumns
Default: empty array of JoinColumn.
By default, a JPA persistence provider assumes that there is a single join column on the owned (or inverse side) of the association: the owned entity's primary key column. JPA names this column by concatenating the name of the owned entity + "_" + the name of the referenced primary key column.
If such a column name is awkward, a reserved word, incompatible with a pre-existing data model, or if you want to specify more than one join column, then set joinColumns to one or more instances of JoinColumn (see @JoinColumn)
joinColumns
Default: empty array of JoinColumn.
By default, a JPA persistence provider assumes that there is a join column for each of the owning entity's primary key columns. The persistence provider names these columns by concatenating the name of the owning entity + "_" + the name of the referenced primary key column.
If such a column name is awkward, a reserved word, incompatible with a pre-existing data model, or if you want to specify more than one join column, then set joinColumns to one or more instances of JoinColumn (see @JoinColumn).
name
Default: a JPA persistence provider names the join table by concatenating the table names of the associated primary tables (owning side first) using an underscore.
If such a join table name is awkward, a reserved word, or incompatible with a pre-existing data model, set name to the appropriate join table name. In Example 1-45, JPA uses the join table named EJB_PROJ_EMP.
schema
Default: empty String.
By deafult, JPA uses whatever the default schema is for your database.
If the default schema is inappropriate for your application, set the schema to the String schema name to use.
uniqueConstraints
Default: empty array of UniqueConstraint.
By default, a JPA persistence provider assumes that none of the columns in the join table have unique constraints.
If unique constraints do apply to one or more columns in this table, set uniqueContraints to an array of one or more UniqueConstraint instances. For more information, see @UniqueConstraint.
Example 1-45 shows how to use this annotation to specify a join table named EMP_PROJ_EMP for a many-to-many relationship between entities Employee and Project. In the join table, there are two columns: EMP_ID and PROJ_ID. The EMP_ID column contains primary key values from the Employee table whose primary key column (referenced column) is named ID. The PROJ_ID column contains primary key values from the Project table whose primary key column (referenced column) is also named ID.
Example 1-45 @JoinTable
@Entity
public class Employee implements Serializable {
...
@ManyToMany
@JoinTable(
name="EJB_PROJ_EMP",
joinColumns=@JoinColumn(name="EMP_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="PROJ_ID", referencedColumnName="ID")
)
public Collection getProjects() {
return projects;
}
...
}
@Lob
By default, a JPA persistence provider assumes that all persistent data can be represented as typical database data types.
Use the @Lob annotation with the @Basic mapping to specify that a persistent property or field should be persisted as a large object to a database-supported large object type.
A Lob may be either a binary or character type. The persistence provider infers the Lob type from the type of the persistent field or property.
For string and character-based types, the default is Clob. In all other cases, the default is Blob.
You can also use the @Column attribute columnDefinition to further refine the Lob type.
This annotation has no attributes. For more details, see the API.
Example 1-46 shows how to use this annotation to specify that persistent field pic should be persisted as a Blob.
Example 1-46 @Lob
@Entity
public class Employee implements Serializable {
...
@Lob
@Basic(fetch=LAZY)
@Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
protected byte[] pic;
...
}
@ManyToMany
By default, JPA automatically defines a @ManyToMany mapping for a many-valued association with many-to-many multiplicity.
Use the @ManyToMany annotation to:
configure the fetch type to LAZY
configure the mapping to forbid null values (for non-primitive types) in case null values are inappropriate for your application
configure the associated target entity because the Collection used is not defined using generics
configure the operations that must be cascaded to the target of the association: for example, if the owning entity is removed, ensure that the target of the association is also removed
configure the details of the join table used by the persistence provider (see @JoinTable)
Table 1-22 lists the attributes of this annotation. For more details, see the API.
Table 1-22 @ManyToMany Attributes
Attribute Required Description
cascade
Default: empty array of CascadeType.
By default, JPA does not cascade any persistence operations to the target of the association.
If you want some or all persistence operations cascaded to the target of the association, set cascade to one or more CascadeType instances, including:
ALL - any persistence operation performed on the owning entity is cascaded to the target of the association.
MERGE - if the owning entity is merged, the merge is cascaded to the target of the association.
PERSIST - if the owning entity is persisted, the persist is cascaded target of the association.
REFRESH - if the owning entity is refreshed, the refresh is cascaded target of the association.
REMOVE - if the owning entity is removed, the target of the association is also removed.
fetch
Default: FetchType.EAGER.
By deafult, a JPA persistence provider uses a fetch type of EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.
If this is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).
mappedBy
Default: if the relationship is unidirectional, the JPA persistence provider determines the field that owns the relationship.
If the relationship is bidirectional, then set the mappedBy attribute on the inverse (non-owning) side of the association to the name of the field or property that owns the relationship (as Example 1-48 shows).
targetEntity
Default: the parameterized type of the Collection when defined using generics.
By default, if you are using a Collection defined using generics, then the persistence provider infers the associated target entity from the type of the object being referenced.
If your Collection does not use generics, then you must specify the entity class that is the target of the association: set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.
Example 1-47 and Example 1-48show how to use this annotation to configure a many-to-many mapping between Customer and PhoneNumber using generics.
Example 1-47 @ManyToMany - Customer Class With Generics
@Entity
public class Customer implements Serializable {
...
@ManyToMany
@JoinTable(
name="CUST_PHONE",
joinColumns=
@JoinColumn(name="CUST_ID", referencedColumnName="ID"),
inverseJoinColumns=
@JoinColumn(name="PHONE_ID", referencedColumnName="ID")
)
public Set<PhoneNumber> getPhones() {
return phones;
}
...
}
Example 1-48 @ManyToMany - PhoneNumber Class With Generics
@Entity
public class PhoneNumber implements Serializable {
...
@ManyToMany(mappedBy="phones")
public Set<Customer> getCustomers() {
return customers;
}
...
}
@ManyToOne
By default, JPA automatically defines a ManyToOne mapping for a single-valued association to another entity class that has many-to-one multiplicity.
Use the @ManyToOne annotation to:
configure the fetch type to LAZY
configure the mapping to forbid null values (for non-primitive types) in case null values are inappropriate for your application
configure the associated target entity if it cannot be inferred from the type of the object being referenced
configure the operations that must be cascaded to the target of the association: for example, if the owning entity is removed, ensure that the target of the association is also removed
Table 1-23 lists the attributes of this annotation. For more details, see the API.
Table 1-23 @ManyToOne Attributes
Attribute Required Description
cascade
Default: empty array of CascadeType.
By default, JPA does not cascade any persistence operations to the target of the association.
If you want some or all persistence operations cascaded to the target of the association, set cascade to one or more CascadeType instances, including:
ALL - any persistence operation performed on the owning entity is cascaded to the target of the association.
MERGE - if the owning entity is merged, the merge is cascaded to the target of the association.
PERSIST - if the owning entity is persisted, the persist is cascaded target of the association.
REFRESH - if the owning entity is refreshed, the refresh is cascaded target of the association.
REMOVE - if the owning entity is removed, the target of the association is also removed.
fetch
Default: FetchType.EAGER.
By deafult, the JPA persistence provider uses a fetch type of EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.
If this is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).
optional
Default: true.
By default a JPA persistence provider assumes that the value of all (non-primitive) fields and properties may be null.
If this is inappropriate for your application, set optional to false.
targetEntity
Default: the JPA persistence provider infers the associated target entity from the type of the object being referenced
If the persistence provider cannot infer the type of the target entity, then set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.
Example 1-49 show how to use this annotation to configure a many-to-one mapping between Customer (the owned side) and Order (the owning side) using generics.
Example 1-49 @ManyToOne
@Entity
public class Order implements Serializable {
...
@ManyToOne(optional=false)
@JoinColumn(name="CUST_ID", nullable=false, updatable=false)
public Customer getCustomer() {
return customer;
}
...
}
@MapKey
By default, a JPA persistence provider assumes that the primary key of the associated entity is the Map key for associations of type java.util.Map:
If the primary key is a non-composite primary key annotated as @Id, an instance of this field or property's type is used as the Map key.
If the primary key is a composite primary key annotated as @IdClass, an instance of the primary key class is used as the Map key.
Use the @MapKey annotation to:
specify some other field or property as the Map key if the primary key of the associated entity is not appropriate for your application
specify an embedded composite primary key class (see @EmbeddedId)
The field or property you specify must have a unique constraint (see @UniqueConstraint).
Table 1-24 lists the attributes of this annotation. For more details, see the API.
Table 1-24 @MapKey Attributes
Attribute Required Description
name
Default: By default, a JPA persistence provider uses the primary key of the associated entity as the Map key for a property or field mapped to a java.util.Map for non-composite primary keys or composite primary keys annotated as @IdClass.
If you want to use some other field or property as the Map key, set name to the associated entity's String field or property name to use.
In Example 1-52, Project owns a one to many relationship to instances of Employee as a Map. Example 1-52 shows how to use the @MapKey annotation to specify that the key for this Map is Employee field empPK, an embedded composite primary key (see Example 1-51) of type EmployeePK (see Example 1-52).
Example 1-50 Project Entity Using @MapKey
@Entitypublic class Project { ... @OneToMany(mappedBy="project") @MapKey(name="empPK") public Map<EmployeePK, Employee> getEmployees() { ...
} ...}
Example 1-51 Employee Entity
@Entitypublic class Employee { @EmbeddedId public EmployeePK getEmpPK() { ...
} ... @ManyToOne @JoinColumn(name="proj_id") public Project getProject() {
...
}...}
Example 1-52 EmployeePK Composite Primary Key Class
@Embeddablepublic class EmployeePK { String name; Date birthDate;}
@MappedSuperclass
By default, a JPA persistence provider assumes that all the persistent fields of an entity are defined in that entity.
Use the @MappedSuperclass annotation to designate a superclass from which your entity class inherits persistent fields. This is a convenient pattern when multiple entity classes share common persistent fields or properties.
You can annotate this superclass's fields and properties with any of the direct and relationship mapping annotations (such as @Basic and @ManyToMany) as you would for an entity but these mappings apply only to its subclasses since no table exists for the superclass itself. The inherited persistent fields or properties belong to the subclass's table.
You can use the @AttributeOverride or @AssociationOverride annotations in the subclass to override the superclass's mapping configuration.
This annotation has no attributes. For more details, see the API.
Example 1-53 shows how to use this annotation to specify Employee as a mapped superclass. Example 1-54 shows how to extend this superclass in an entity and how to use @AttributeOverride in the entity class to override configuration made in the superclass.
Example 1-53 @MappedSuperclass
@MappedSuperclass
public class Employee {
@Id
protected Integer empId;
@Version
protected Integer version;
@ManyToOne
@JoinColumn(name="ADDR")
protected Address address;
public Integer getEmpId() {
...
}
public void setEmpId(Integer id) {
...
}
public Address getAddress() {
...
}
public void setAddress(Address addr) {
...
}
}
Example 1-54 Extending a @MappedSuperclass
@Entity
@AttributeOverride(name="address", column=@Column(name="ADDR_ID"))
public class PartTimeEmployee extends Employee {
@Column(name="WAGE")
protected Float hourlyWage;
public PartTimeEmployee() {
...
}
public Float getHourlyWage() {
...
}
public void setHourlyWage(Float wage) {
...
}
}
@NamedNativeQueries
If you need to specify more than one @NamedNativeQuery, you must specify all your named queries using a single @NamedNativeQueries annotation.
Table 1-5 lists the attributes of this annotation. For more details, see the API.
Table 1-25 @NamedNativeQueries Attributes
Attribute Required Description
value
To specify two or more attribute overrides, set value to an array of NamedNativeQuery instances (see @NamedNativeQuery).
Example 1-6 shows how to use this annotation to specify two named native queries.
Example 1-55 @NamedNativeQueries
@Entity
@NamedNativeQueries({
@NamedNativeQuery(
name="findAllPartTimeEmployees",
query="SELECT * FROM EMPLOYEE WHERE PRT_TIME=1"
),
@NamedNativeQuery(
name="findAllSeasonalEmployees",
query="SELECT * FROM EMPLOYEE WHERE SEASON=1"
)
})
public class PartTimeEmployee extends Employee {
...
}
@NamedNativeQuery
In an application that uses a JPA persistence provider, you can use an entity manager to create and execute queries dynamically or you can pre-define queries and execute them by name at run time.
Use the @NamedNativeQuery annotation to create pre-defined queries associated with an @Entity or @MappedSuperclass that:
use SQL native to the underlying database
are frequently used
are complex and difficult to create
can be shared amongst different entities
return entities, scalar values, or a combination of both (see also @ColumnResult, @EntityResult, @FieldResult, and @SqlResultSetMapping)
If you have more than one @NamedNativeQuery to define, you must use @NamedNativeQueries.
To pre-define portable queries suitable for any database, see @NamedQuery.
Table 1-6 lists the attributes of this annotation. For more details, see the API.
Table 1-26 @NamedNativeQuery Attributes
Attribute Required Description
query
To specify the query, set query to the SQL query as a String.
For more information on native SQL query language, see your database documentation.
hints
Default: empty QueryHint array.
By default a JPA persistence provider assumes that the SQL query should be executed exactly as given by the query attribute.
To fine-tune the execution of the query, you can optionally set hints to a QueryHint array (see @QueryHint). At execution time, the EntityManager will pass the hints to the underlying database.
name
To specify the name of the query, set name to the String name you want.
This is the name by which you invoke the query at runtime (see Example 1-60).
resultClass
Default: a JPA persistence provider assumes that the result class is the Class of the associated entity.
To specify a result class, set resultClass to the Class you want.
resultSetMapping
Default: a JPA persistence provider assumes that the SELECT statement in a native SQL query: returns a single type of entity; includes all the columns that correspond to all the fields or properties of the entity returned; and uses column names that correspond to the field or property names (AS statements are not used).
To control how a JPA persistence provider maps the JDBC result set to entity fields or properties and scalars, specify a result set mapping by setting resultSetMapping to the String name of the @SqlResultSetMapping you want.
Example 1-59 shows how to use the @NamedNativeQuery annotation to define a query using SQL native to the underlying database. Example 1-60 shows how you use the EntityManager to acquire this query and use Query method getResultList to execute it.
Example 1-56 Implementing an Oracle Hierarchical Query Using @NamedNativeQuery
@Entity
@NamedNativeQuery(
name="findAllEmployees",
query="SELECT * FROM EMPLOYEE"
)
public class Employee implements Serializable {
...
}
Example 1-57 Executing a Named Native Query
Query queryEmployees = em.createNamedQuery("findAllEmployees");
Collection employees = queryEmployees.getResultList();
@NamedQueries
If you need to specify more than one @NamedQuery, you must specify all your named queries using a single @NamedQueries annotation.
Table 1-5 lists the attributes of this annotation. For more details, see the API.
Table 1-27 @NamedQueries Attributes
Attribute Required Description
value
To specify two or more attribute overrides, set value to an array of NamedQuery instances (see @NamedQuery).
Example 1-6 shows how to use this annotation to specify two named queries.
Example 1-58 @NamedQueries
@Entity
@NamedQueries({
@NamedQuery(
name="findAllEmployeesByFirstName",
query="SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = :firstname"
),
@NamedQuery(
name="findAllEmployeesByLasttName",
query="SELECT OBJECT(emp) FROM Employee emp WHERE emp.lasstName = :lastname"
)
})
public class PartTimeEmployee extends Employee {
...
}
@NamedQuery
In an application that uses a JPA persistence provider, you can use an entity manager to create and execute queries dynamically or you can pre-define queries and execute them by name at run time.
Use the @NamedQuery annotation to create pre-defined queries associated with an @Entity or @MappedSuperclass that:
use the JPA query language (see JSR-000220 Enterprise JavaBeans v3.0 specification, Chapter 4) for portable execution on any underlying database
are frequently used
are complex and difficult to create
can be shared amongst different entities
only return entities (never return scalar values) and only return entities of a single type
If you have more than one @NamedQuery to define, you must use @NamedQueries.
To pre-define queries in SQL native to a known, underlying database, see @NamedNativeQuery. Using a native SQL query, you can return entities (including entities of different types), scalar values, or both.
Table 1-6 lists the attributes of this annotation. For more details, see the API.
Table 1-28 @NamedQuery Attributes
Attribute Required Description
query
To specify the query, set query to the JPA query language query as a String.
For more information on the JPA query language, see the JSR-000220 Enterprise JavaBeans v.3.0 specification, Chapter 4.
hints
Default: empty QueryHint array.
By default a JPA persistence provider assumes that the JPA query should be executed exactly as given by the query attribute regardless of the underlying database.
If you know what the underlying database will be at runtime, to fine-tune the execution of the query, you can optionally set hints to a QueryHint array (see @QueryHint). At execution time, the EntityManager will pass the hints to the underlying database.
name
To specify the name of the query, set name to the query name as a String.
This is the name by which you invoke the query at runtime (see Example 1-60).
Example 1-59 shows how to use the @NamedQuery annotation to define a JPA query language query that takes a parameter named firstname. Example 1-60 shows how you use the EntityManager to acquire this query and use Query method setParameter to set the firstname parameter.
Example 1-59 Implementing a Query with Parameters Using @NamedQuery
@Entity
@NamedQuery(
name="findAllEmployeesByFirstName",
query="SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = :firstname"
)
public class Employee implements Serializable {
...
}
Example 1-60 Executing a Named Query
Query queryEmployeesByFirstName = em.createNamedQuery("findAllEmployeesByFirstName");
queryEmployeeByFirstName.setParameter("firstName", "John");
Collection employees = queryEmployessByFirstName.getResultList();
@OneToMany
By default, JPA automatically defines a OneToMany mapping for a many-valued association with one-to-many multiplicity.
Use the @OneToMany annotation to:
configure the fetch type to LAZY
configure the associated target entity because the Collection used is not defined using generics
configure the operations that must be cascaded to the target of the association: for example, if the owning entity is removed, ensure that the target of the association is also removed
configure the details of the join table used by the persistence provider for uni-directional one-to-many relationships (see @JoinTable)
Table 1-29 lists the attributes of this annotation. For more details, see the API.
Table 1-29 @OneToMany Attributes
Attribute Required Description
cascade
Default: empty array of CascadeType.
By default, JPA does not cascade any persistence operations to the target of the association.
If you want some or all persistence operations cascaded to the target of the association, set cascade to one or more CascadeType instances, including:
ALL - any persistence operation performed on the owning entity is cascaded to the target of the association.
MERGE - if the owning entity is merged, the merge is cascaded to the target of the association.
PERSIST - if the owning entity is persisted, the persist is cascaded target of the association.
REFRESH - if the owning entity is refreshed, the refresh is cascaded target of the association.
REMOVE - if the owning entity is removed, the target of the association is also removed.
fetch
Default: FetchType.EAGER.
By deafult, the JPA persistence provider uses a fetch type of EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.
If this is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).
mappedBy
Default: if the relationship is unidirectional, the persistence provider determines the field that owns the relationship.
If the relationship is bidirectional, then set the mappedBy element on the inverse (non-owning) side of the association to the name of the field or property that owns the relationship as Example 1-62 shows.
targetEntity
Default: the parameterized type of the Collection when defined using generics.
By default, if you are using a Collection defined using generics, then the persistence provider infers the associated target entity from the type of the object being referenced.
If your Collection does not use generics, then you must specify the entity class that is the target of the association: set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.
Example 1-61 and Example 1-62 show how to use this annotation to configure a one-to-many mapping between Customer (the owned side) and Order (the owning side) using generics.
Example 1-61 @OneToMany - Customer Class With Generics
@Entity
public class Customer implements Serializable {
...
@OneToMany(cascade=ALL, mappedBy="customer")
public Set<Order> getOrders() {
return orders;
}
...
}
Example 1-62 @ManyToOne - Order Class With Generics
@Entity
public class Customer implements Serializable {
...
@ManyToOne
@JoinColumn(name="CUST_ID", nullable=false)
public Customer getCustomer() {
return customer;
}
...
}
@OneToOne
By default, JPA automatically defines a OneToOne mapping for a single-valued association to another entity that has one-to-one multiplicity and infers the associated target entity from the type of the object being referenced.
Use the @OneToOne annotation to:
configure the fetch type to LAZY
configure the mapping to forbid null values (for non-primitive types) in case null values are inappropriate for your application
configure the associated target entity if it cannot be inferred from the type of the object being referenced
configure the operations that must be cascaded to the target of the association: for example, if the owning entity is removed, ensure that the target of the association is also removed
Table 1-30 lists the attributes of this annotation. For more details, see the API.
Table 1-30 @OneToOne Attributes
Attribute Required Description
cascade
Default: empty CascadeType array.
By default, JPA does not cascade any persistence operations to the target of the association.
If you want some or all persistence operations cascaded to the target of the association, set cascade to one or more CascadeType instances, including:
ALL - any persistence operation performed on the owning entity is cascaded to the target of the association.
MERGE - if the owning entity is merged, the merge is cascaded to the target of the association.
PERSIST - if the owning entity is persisted, the persist is cascaded target of the association.
REFRESH - if the owning entity is refreshed, the refresh is cascaded target of the association.
REMOVE - if the owning entity is removed, the target of the association is also removed.
fetch
Default: FetchType.EAGER.
By default, the JPA persistence provider uses a fetch type of EAGER: this is a requirement on the persistence provider runtime that data must be eagerly fetched.
If this is inappropriate for your application or a particular persistent field, set fetch to FetchType.LAZY: this is a hint to the persistence provider that data should be fetched lazily when it is first accessed (if possible).
mappedBy
Default: the JPA persistence provider infers the associated target entity from the type of the object being referenced.
If the persistence provider cannot infer the associated target entity, then set the mappedBy element on the inverse (non-owning) side of the association to the String name of the field or property that owns the relationship as Example 1-64 shows.
optional
Default: true.
By default, a JPA persistence provider assumes that the value of all (non-primitive) fields and properties may be null.
If this is inappropriate for your application, set optional to false.
targetEntity
Default: the JPA persistence provider infers the associated target entity from the type of the object being referenced.
If the persistence provider cannot infer the type of the target entity, then set the targetEntity element on owning side of the association to the Class of the entity that is the target of the relationship.
Example 1-63 and Example 1-64 show how to use this annotation to configure a one-to-one mapping between Customer (the owning side) and CustomerRecord (the owned side).
Example 1-63 @OneToOne - Customer Class
@Entity
public class Customer implements Serializable {
...
@OneToOne(optional=false)
@JoinColumn(name="CUSTREC_ID", unique=true, nullable=false, updatable=false)
public CustomerRecord getCustomerRecord() {
return customerRecord;
}
...
}
Example 1-64 @OneToOne - CustomerRecord Class
@Entity
public class CustomerRecord implements Serializable {
...
@OneToOne(optional=false, mappedBy="customerRecord")
public Customer getCustomer() {
return customer;
}
...
}
@OrderBy
By default, a JPA persistence provider retrieves the members of a Collection association in ascending order by primary key of the associated entities.
Use the @OrderBy annotation with @OneToMany and @ManyToMany to specify:
one or more other field or property names to order by
different orders (ascending or descending) for each such field or property names
Table 1-31 lists the attributes of this annotation. For more details, see the API.
Table 1-31 @OrderBy Attributes
Attribute Required Description
value
Default: a JPA persistence provider retrieves the members of a Collection association in ascending order by primary key of the associated entities.
If you want to order by some other fields or properties and specify different, set value to a comma separated list of the following elements: "property-or-field-name ASC|DESC" (see Example 1-65).
Example 1-65 shows how to use the @OrderBy annotation to specify that Project method getEmployees should return a List of Employee in ascending order by Employee field lastname and in descending order by Employee field seniority. Example 1-66 shows that by default, Employee method getProjects returns a List in ascending order by Employee primary key empId.
Example 1-65 Project Entity
@Entity public class Project {
...
@ManyToMany
@OrderBy("lastname ASC", "seniority DESC")
public List<Employee> getEmployees() {
...
};
...
}
Example 1-66 Employee Entity
@Entity public class Employee {
@Id
private int empId;
...
private String lastname;
...
private int seniority;
...
@ManyToMany(mappedBy="employees")
// By default, returns a List in ascending order by empId
public List<Project> getProjects() {
...
};
...
}
@PersistenceContext
In an application that uses a JPA persistence provider, you use an entity manager to perform all persistence operations (create, read, update, and delete). A Java EE application obtains an entity manager using dependency injection or direct lookup of the entity manager in the JNDI namespace.
Use the @PersistenceContext annotation to obtain an entity manager:
using dependency injection
by name using JNDI lookup
associated with a specific persistence unit (see also @PersistenceUnit)
with an extended persistence context
customized with specific persistence properties (see @PersistenceProperty)
If you have more than one @PersistenceContext to specify, you must use @PersistenceContexts.
Table 1-32 lists the attributes of this annotation. For more details, see the API.
Table 1-32 @PersistenceContext Attributes
Attribute Required Description
name
Default: a JPA persistence provider retrieves the default entity manager.
If you want to inject or look up a specific entity manager, set name to the String name of the entity manager you want to use.
For dependency injection, name is not required.
For JNDI look up, name must be set to the name by which the entity manager is to be accessed in the environment referencing context.
properties
Default: a JPA persistence provider assumes that the entity manager will use default properties.
If you want to configure JPA persistence provider properties, including vendor-specific properties (for example, see "TopLink JPA Persistence.xml File Extensions"), set properties to an array of @PersistenceProperty instances.
type
Default: PersistenceContextType.TRANSACTION.
By default, a JPA persistence provider assumes that entity managers are container-managed and the lifetime of their persistence context is scoped to a single transaction: that is, the persistence context comes into existence at the time a transaction is started and ceases to exist when that transaction commits.
Set type to PersistenceContextType.EXTENDED if:
your persistence context is application-managed
you want the extended persistence context to exist from the time the EntityManager instance is created until it is closed
you want the entity manager to maintain references to entity objects after a transaction has committed
you want to invoke EntityManager methods persist, remove, merge, and refresh regardless of whether a transaction is active
unitName
Default: a JPA persistence provider retrieves the default entity manager for the default persistence unit.
If you want to inject or look up an entity manager associated with a specific persistence unit, set unitName to the String persistence unit name you want. Alternatively, you can use a @PersistenceUnit if you need to specify both the EntityManagerFactory and the persistence unit.
For dependency injection, unitName is not required.
For JNDI look up, if you specify a unitName, then the entity manager accessed by name must be associated with this persistence unit.
Example 1-67 shows how to use this annotation to inject an entity manager in a stateless session bean and Example 1-68 shows how to use this annotation to look up an entity manager in JNDI.
Example 1-67 Using @PersistenceContext and Dependency Injection
@Stateless
public class OrderEntryBean implements OrderEntry {
@PersistenceContext
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
}
Example 1-68 Using @PersistenceContext and JNDI Lookup
@Stateless
public class OrderEntryBean implements OrderEntry {
@PersistenceContext(name="OrderEM")
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
em = (EntityManager)ctx.lookup("OrderEM");
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
}
@PersistenceContexts
If you need to specify more than one @PersistenceContext, you must specify all your persistence contexts using a single @PersistenceContexts annotation.
Table 1-33 lists the attributes of this annotation. For more details, see the API.
Table 1-33 @PersistenceContexts Attributes
Attribute Required Description
value
To specify two or more persistence contexts, set value to an array of PersistenceContext instances (see @PersistenceContext).
Example 1-69 shows how to use this annotation to specify two persistence contexts.
Example 1-69 @PersistenceContexts
@Stateless
public class OrderEntryBean implements OrderEntry {
@PersistenceContexts({
@PersistenceContext(name="OrderEM")
@PersistenceContext(name="ItemEM"),
})
public void enterOrder(int custID, Order newOrder) {
EntityManager em = (EntityManager)ctx.lookup("OrderEM");
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
public void enterItem(int orderID, Item newItem) {
EntityManager em = (EntityManager)ctx.lookup("ItemEM");
...
}
}
@PersistenceProperty
By default, a JPA persistence provider assumes that the entity manager you obtain using @PersistenceContext will use default properties.
Use the @PersistenceProperty annotation to specify properties, including vendor-specific properties, for the container or persistence provider to:
customize entity manager behavior
exploit specific features in the vendor's JPA persistence provider implementation
Properties are passed to the persistence provider when the entity manager is created. Unrecognized properties are simply ignored.
Table 1-34 lists the attributes of this annotation. For more details, see the API.
Table 1-34 @PersistenceProperty Attributes
Attribute Required Description
name
To specify the name of the persistence property, set name to the String property name.
For more information on persistence properties, see your JPA persistence provider documentation.
value
To specify the value of the persistence property, set value to the String property value you want.
For more information on persistence property values, see your JPA persistence provider documentation.
Example 1-70 shows how to use the @PersistenceProperty annotation to customize the query to take advantage of a vendor JPA extension provided by TopLink Essentials: in this case, the property ensures that a full TopLink cache is used in this persistence context. For more information, see "TopLink JPA Persistence.xml File Extensions".
Example 1-70 @PersistenceProperty
@Stateless
public class OrderEntryBean implements OrderEntry {
@PersistenceContext(
properties={
@PersistenceProperty={name="toplink.cache.type.default", value="CacheType.Full"}
}
)
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
}
@PersistenceUnit
By default, a JPA persistence provider uses the default EntityManagerFactory associated with the default persistence unit or the persistence unit you specify using @PersistenceContext attribute unitName.
Use the @PersistenceUnit annotation to specify the EntityManagerFactory that you want your JPA persistence provider to use to:
obtain specialized entity managers
specify both EntityManagerFactory and persistence unit
If you have more than one @PersistenceUnit to specify, you must use @PersistenceUnits.
Table 1-34 lists the attributes of this annotation. For more details, see the API.
Table 1-35 @PersistenceUnit Attributes
Attribute Required Description
name
Default: a JPA persistence provider obtains its EntityManager instances from the default EntityManagerFactory.
If you want the JPA persistence provider to use a specific EntityManagerFactory when injecting or looking up an entity manager, set name to the String name of the entity manager factory you want.
For dependency injection, name is not required.
For JNDI look up, name must be set to the name by which the entity manager is to be accessed in the environment referencing context.
unitName
Default: a JPA persistence provider retrieves the default entity manager for the default persistence unit.
If you want to inject or look up an entity manager associated with a specific persistence unit, set unitName to the String persistence unit name you want. See also @PersistenceContext.
For dependency injection, unitName is not required.
For JNDI look up, if you specify a unitName, then the EntityManagerFactory accessed by name must be associated with this persistence unit.
Example 1-71 shows how to use the @PersistenceUnit annotation to specify the JNDI name of the EntityManagerFactory to use and the persistence unit name associated with that factory. When the JPA persistence provider uses JNDI to obtain an entity manager with persistence context OrderEM, it will use the EntityManagerFactory with JNDI name OrderEMFactory associated with persistence unit OrderEMUnit.
Example 1-71 Using @PersistenceUnit to Specify Factory and Unit
@Stateless
public class OrderEntryBean implements OrderEntry {
@PersistenceContext(name="OrderEM")
@PersistenceUnit(name="OrderEMFactory", unitName="OrderEMUnit")
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
em = (EntityManager)ctx.lookup("OrderEM");
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
}
Example 1-72 shows an alternative approach using @PersistenceContext attribute unitName to specify only the persistence unit. In this case, when the JPA persistence provider uses JNDI to obtain an entity manager with persistence context OrderEM, it will use the default EntityManagerFactory associated with persistence unit OrderEMUnit.
Example 1-72 Using @PersistenceContext Attribute unitName
@Stateless
public class OrderEntryBean implements OrderEntry {
@PersistenceContext(name="OrderEM", unitName="OrderEMUnit")
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
em = (EntityManager)ctx.lookup("OrderEM");
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
}
@PersistenceUnits
If you need to specify more than one @PersistenceUnit, you must specify all your persistence units using a single @PersistenceUnits annotation.
Table 1-36 lists the attributes of this annotation. For more details, see the API.
Table 1-36 @PersistenceUnits Attributes
Attribute Required Description
value
To specify two or more persistence units, set value to an array of PersistenceUnit instances (see @PersistenceUnit).
Example 1-73 shows how to use this annotation to specify two persistence units. In this case, @PersistenceContext attribute unitName and @PersistenceUnit attribute unitName must correspond in order to associate persistence context and persistence unit.
Example 1-73 @PersistenceUnits
@Stateless
public class OrderEntryBean implements OrderEntry {
@PersistenceContexts({
@PersistenceContext(name="OrderEM", unitName="OrderEMUnit")
@PersistenceContext(name="ItemEM", unitName="ItemEMUnit"),
})
@PersistenceUnits({
@PersistenceUnit(name="OrderEMFactory", unitName="OrderEMUnit"),
@PersistenceUnit(name="ItemEMFactory", unitName="ItemEMUnit")
})
public void enterOrder(int custID, Order newOrder) {
EntityManager em = (EntityManager)ctx.lookup("OrderEM");
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
public void enterItem(int orderID, Item newItem) {
EntityManager em = (EntityManager)ctx.lookup("ItemEM");
...
}
}
@PrimaryKeyJoinColumn
By default, when one entity extends another using InheritanceType.JOINED (see @Inheritance), a JPA persistence provider assumes that the foreign key columns of the subclass have the same names as the primary key columns of the primary table of the superclass.
Use the @PrimaryKeyJoinColumn annotation:
if the foreign key columns of the subclass do not have the same names as the primary key columns of the primary table of the superclass in this scenario
with a @SecondaryTable annotation to join a secondary table to a primary table
in a @OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.
to use composite foreign keys (see @PrimaryKeyJoinColumns)
Table 1-37 lists the attributes of this annotation. For more details, see the API.
Table 1-37 @PrimaryKeyJoinColumn Attributes
Attribute Required Description
columnDefinition
Default: empty String.
By deafult, JPA creates a database table column with minimal SQL.
If you want the column created with more specialized options, set columnDefinition to the String SQL fragment that you want JPA to use when generating the DDL for the column.
Do not use this attribute with a @OneToOne mapping.
name
Default: a JPA persistence provider assumes one of the following names for the primary key column of the current table (depending on how you are using this annotation):
InheritanceType.JOINED (see @Inheritance): the same name as the primary key column of the superclass.
@SecondaryTable mapping: the same name as the primary key column of the primary table.
@OneToOne mapping: the same name as the primary key column for the table for the referencing entity.
If this name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a column name in your database, set name to the String column name you want.
referencedColumnName
Default: a JPA persistence provider assumes one of the following names for the name of the primary key column of the table being joined to (depending on how you are using this annotation):
InheritanceType.JOINED (see @Inheritance): the same name as the primary key column of the primary table of the superclass.
@SecondaryTable mapping: the same name as the name of the primary key column of the primary table.
@OneToOne mapping: the same name as the primary key column of the table for the referenced entity.
If this name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a column name in your database, set referencedColumnName to the String column name you want.
Example 1-74 shows an entity base class Customer and Example 1-75 shows how to use @PrimaryKeyJoinColumn to specify primary key join column CUST_ID in the primary table of ValuedCustomer, a subclass of Customer.
Example 1-74 @PrimaryKeyJoinColumn - InheritanceType.JOINED Superclass
@Entity
@Table(name="CUST")
@Inheritance(strategy=JOINED)
@DiscriminatorValue("CUST")
public class Customer {
...
}
Example 1-75 @PrimaryKeyJoinColumn - InheritanceType.JOINED Subclass
@Entity
@Table(name="VCUST")
@DiscriminatorValue("VCUST")
@PrimaryKeyJoinColumn(name="CUST_ID")
public class ValuedCustomer extends Customer {
...
}
@PrimaryKeyJoinColumns
By deafult, a JPA persistence provider assumes that each entity has single-column primary key.
Use the @PrimaryKeyJoinColumns annotation if you want to specify a primary key composed of two or more columns.
Table 1-38 lists the attributes of this annotation. For more details, see the API.
Table 1-38 @PrimaryKeyJoinColumns Attributes
Attribute Required Description
value
To specify a composite (multi-column) primary key, set value to an array of PrimaryKeyJoinColumn instances (see @PrimaryKeyJoinColumn).
Example 1-76 shows how to use this annotation to specify a composite primary key composed of columns CUST_ID and CUST_TYPE.
Example 1-76 @PrimaryKeyJoinColumns
@Entity
@Table(name="VCUST")
@DiscriminatorValue("VCUST")
@PrimaryKeyJoinColumns({
@PrimaryKeyJoinColumn(name="CUST_ID",referencedColumnName="ID"),
@PrimaryKeyJoinColumn(name="CUST_TYPE",referencedColumnName="TYPE")
})
public class ValuedCustomer extends Customer {
...
}
@QueryHint
By default, a JPA persistence provider assumes that a @NamedQuery or @NamedNativeQuery should be executed exactly as specified by the query String.
Use the @QueryHint annotation to specify vendor-specific JPA query extensions to:
improve query performance
exploit specific features in the vendor's JPA persistence provider implementation
Table 1-6 lists the attributes of this annotation. For more details, see the API.
Table 1-39 @QueryHint Attributes
Attribute Required Description
name
To specify the name of the hint, set name to String hint name.
For more information on hints, see your JPA persistence provider documentation.
value
To specify the value of the hint, set value to the String hint value you want.
For more information on hint values, see your JPA persistence provider documentation.
Example 1-77 shows how to use the @QueryHint annotation to customize the query to take advantage of a vendor JPA extension provided by TopLink Essentials: in this case, the hint ensures that the TopLink cache is always refreshed when this query is executed. For more information, see "TopLink JPA Extensions for Query Hints".
Example 1-77 @QueryHint
@Entity
@NamedQuery(
name="findAllEmployees",
query="SELECT * FROM EMPLOYEE WHERE MGR=1"
hints={@QueryHint={name="toplink.refresh", value="true"}}
)
public class Employee implements Serializable {
...
}
@SecondaryTable
By default, a JPA persistence provider assumes that all the persistent fields of an entity are stored in a single database table whose name is the entity name: this table is known as the primary table (see @Table).
Use the @SecondaryTable annotation to associate an entity with an additional database table if you want JPA to persist some of the entity's persistent fields to the primary table and some to other database tables. In this case, you associate an entity's persistent field with a table using the @Column annotation.
If you want to associate two or more secondary tables with an entity, you can use @SecondaryTables.
Table 1-40 lists the attributes of this annotation. For more details, see the API.
Table 1-40 @SecondaryTable Attributes
Attribute Required Description
name
If your entity uses a secondary table, set name to the String table name.
catalog
Default: a JPA persistence provider uses whatever the default catalog is for your database.
If the default catalog is inappropriate for your application, set the catalog to the String catalog name to use.
pkJoinColumns
Default: a JPA persistence provider assumes that none of the columns in the entity's database table are used for primary key joins.
If one or more columns are used for primary key joins in this table, set pkJoinColumns to an array of one or more @PrimaryKeyJoinColumn instances. For more information, see @PrimaryKeyJoinColumn.
schema
Default: a JPA persistence provider uses whatever the default schema is for your database.
If the default schema is inappropriate for your application, set the schema to the String schema name to use.
uniqueConstraints
Default: a JPA persistence provider assumes that none of the columns in the entity's database table have unique constraints.
If unique constraints do apply to one or more columns in this table, set uniqueContraints to an array of one or more @UniqueConstraint instances. For more information, see @UniqueConstraint.
Example 1-78 shows how to use this annotation to specify a secondary table named EMP_HR. In this example, by default, JPA persists entity persistent field empId to the primary table named Employee in column empId and persists empSalary to the secondary table EMP_HR in column empSalary. For more information, see @Column.
Example 1-78 @SecondaryTable
@Entity
@SecondaryTable(name="EMP_HR")
public class Employee implements Serializable {
...
private Long empId;
@Column(table="EMP_HR", name="EMP_SALARY"))
private Float empSalary;
...
}
@SecondaryTables
If you need to specify more than one @SecondaryTable, you may specify all your secondary tables using a single @SecondaryTables annotation.
Table 1-41 lists the attributes of this annotation. For more details, see the API.
Table 1-41 @SecondaryTables Attributes
Attribute Required Description
value
To specify two or more secondary tables, set value to an array of SecondaryTable instances (see @SecondaryTable).
Example 1-79 shows how to use this annotation to specify two secondary tables named EMP_HR and EMP_TR. In this example, by default, JPA persists entity persistent field empId to the primary table named Employee in column empId. JPA persists empSalary to secondary table EMP_HR in column empSalary and empClass to secondary table EMP_TR in column empClass. For more information, see @Column.
Example 1-79 @SecondaryTables
@Entity
@SecondaryTables({
@SecondaryTable(name="EMP_HR"),
@SecondaryTable(name="EMP_TR")
})
public class Employee implements Serializable {
...
private Long empId;
@Column(table="EMP_HR", name="EMP_SALARY"))
private Float empSalary;
@Column(table="EMP_TR", name="EMP_CLASS"))
private Float empClass;
...
}
@SequenceGenerator
If you use the @GeneratedValue annotation to specify a primary key generator of type SEQUENCE, then you can use the @SequenceGenerator annotation to fine tune this primary key generator to:
change the allocation size to match your application requirements or database performance parameters
change the initial value to match an existing data model (for example, if you are building on an existing data set for which a range of primary key values has already been assigned or reserved)
use a pre-defined sequence in an existing data model
Table 1-42 lists the attributes of this annotation. For more details, see the API.
Table 1-42 @SequenceGenerator Attributes
Attribute Required Description
name
The name of the SequenceGenerator must match the name of a GeneratedValue with its startegy set to SEQUENCE.
allocationSize
Default: 50.
By default, the JPA persistence provider uses an allocation size of 50.
If this allocation size does not match your application requirements or database performance parameters, set allocationSize to the int value you want.
initialValue
Default: 0.
By default, a JPA persistence provider assumes that the persistence provider starts all primary key values from 0.
If this does not match an existing data model, set initialValue to the int value you want.
sequenceName
Default: the JPA persistence provider assigns a sequence name of its own creation.
If you prefer to use an existing or pre-defined sequence, set sequenceName to the String name you want.
Example 1-80 shows how to use this annotation to specify the allocation size for the SEQUENCE primary key generator named CUST_SEQ.
Example 1-80 @SequenceGenerator
@Entity
public class Employee implements Serializable {
...
@Id
@SequenceGenerator(name="CUST_SEQ", allocationSize=25)
@GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
@Column(name="CUST_ID")
public Long getId() {
return id;
}
...
@SqlResultSetMapping
When you execute a @NamedNativeQuery, it can return entities (including entities of different types), scalar values, or a combination of both.
By default, as Example 1-81 shows, a JPA persistence provider assumes that the SELECT statement in a native SQL query:
returns a single type of entity
includes all the columns that correspond to all the fields or properties of the entity returned
uses column names that correspond to the field or property names (AS statements are not used)
Example 1-81 Simple Native SQL Query
Query q = entityManager.createNativeQuery(
"SELECT o.id, o.quantity, o.item " +
"FROM Order o, Item i " +
"WHERE (o.item = i.id) AND (i.name = "widget")",
Order.class
);
List resultList = q.getResultList();
// List of Order entity objects: {Order, Order, ...}
Use the @SqlResultSetMapping annotation to control how a JPA persistence provider maps the JDBC result set to entity fields or properties and scalars if the native SQL query:
returns more than one type of entity
returns only scalar values or a combination of entities and scalar values
uses column aliases (AS statements)
If you have more than one @SqlResultSetMapping, you must use @SqlResultSetMappings.
Table 1-8 lists the attributes of this annotation. For more details, see the API.
Table 1-43 @SqlResultSetMapping Attributes
Attribute Required Description
name
Set name to the String name of this @SqlResultSetMapping.
This is the name you use to associate the @SqlResultSetMapping with a native SQL query (see Example 1-84).
columns
Default: empty ColumnResult array.
By deafult, a JPA persistence provider assumes that the SELECT statement returns only entities.
If your SELECT statement returns scalar values, set columns to an array of ColumnResult instances, one @ColumnResult per scalar result.
entities
Default: empty EntityResult array.
By default, a JPA persistence provider assumes that the SELECT statement returns a single type of entity.
If your SELECT statement returns more than one type of entity, set entities to an array of EntityResult instances, one @EntityResult per entity type returned.
Example 1-82 shows how to use this annotation to include both Order and Item (see Example 1-83) entities and scalar name in the result list (see Example 1-84). In this case, the result list would be a List of Object arrays like: {[Order, Item, "Shoes"], [Order, Item, "Socks"], ...}.
Example 1-82 Order Entity With @SqlResultSetMapping
@SqlResultSetMapping(
name="OrderResults",
entities={
@EntityResult(
entityClass=Order.class,
fields={
@FieldResult(name="id", column="order_id"),
@FieldResult(name="quantity", column="order_quantity"),
@FieldResult(name="item", column="order_item")
}
),
@EntityResult(
entityClass=Item.class,
fields={
@FieldResult(name="id", column="item_id"),
@FieldResult(name="name", column="item_name"),
}
)
}
columns={
@ColumnResult(
name="item_name"
)
}
)
@Entity
public class Order {
@Id
protected int id;
protected long quantity;
protected Item item;
...
}
Example 1-83 Item Entity
@Entity
public class Item {
@Id
protected int id;
protected String name;
...
}
Example 1-84 Native Query Using an @SqlResultSetMapping With an @EntityResult
Query q = entityManager.createNativeQuery(
"SELECT o.id AS order_id, " +
"o.quantity AS order_quantity, " +
"o.item AS order_item, " +
"i.id AS item_id, " +
"i.name AS item_name, " +
"FROM Order o, Item i " +
"WHERE (order_quantity > 25) AND (order_item = i.id)",
"OrderResults"
);
List resultList = q.getResultList();
// List of Object arrays: {[Order, Item, "Shoes"], [Order, Item, "Socks"], ...}
@SqlResultSetMappings
If you need to specify more than one @SqlResultSetMapping, you must specify all your SQL result set mappings using a single @SqlResultSetMappings annotation.
Table 1-5 lists the attributes of this annotation. For more details, see the API.
Table 1-44 @SqlResultSetMappings Attributes
Attribute Required Description
value
To specify two or more SQL result set mappings, set value to an array of @SqlResultSetMapping instances.
Example 1-85 shows how to use this annotation to specify two @SqlResultSetMapping instances.
Example 1-85 @SqlResultSetMappings
SqlResultSetMappings({
@SqlResultSetMapping(
name="OrderItemItemNameResults",
entities={
@EntityResult(entityClass=Order.class),
@EntityResult(entityClass=Item.class)
}
columns={
@ColumnResult(name="item_name")
}
),
@SqlResultSetMapping(
name="OrderItemResults",
entities={
@EntityResult(entityClass=Order.class),
@EntityResult(entityClass=Item.class)
}
)
})
@Entity
public class Order {
@Id
protected int id;
protected long quantity;
protected Item item;
...
}
@Table
By default, a JPA persistence provider assumes that all the persistent fields of an entity are stored in a single database table whose name is the entity name (see @Entity).
Use the @Table annotation to specify the primary table associated with an entity if:
the entity name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a table name in your database
you need to control what catalog or schema the table belongs to
If you want JPA to persist some fields to the primary table and other fields to one or more secondary tables, see @SecondaryTable.
Table 1-45 lists the attributes of this annotation. For more details, see the API.
Table 1-45 @Table Attributes
Attribute Required Description
catalog
Default: a JPA persistence provider uses whatever the default catalog is for your database.
If the default catalog is inappropriate for your application, set the catalog to the String catalog name to use.
name
Default: a JPA persistence provider assumes that an entity's database table has the same name as the entity class. In Example 1-86, the default name is Employee.
If the entity class name is awkward, a reserved word, or incompatible with a pre-existing data model, set name to the appropriate database table name. In Example 1-86, JPA persists the entity class Employee in the database table named EMP.
schema
Default: a JPA persistence provider uses whatever the default schema is for your database.
If the default schema is inappropriate for your application, set the schema to the String schema name to use.
uniqueConstraints
Default: a JPA persistence provider assumes that none of the columns in the entity's database table have unique constraints.
If unique constraints do apply to one or more columns in this table, set uniqueContraints to an array of one or more @UniqueConstraint instances. For more information, see @UniqueConstraint.
Example 1-86 shows how to use this annotation to specify the primary table name.
Example 1-86 @Table
@Entity
@Table(name="EMP")
public class Employee implements Serializable {
...
}
@TableGenerator
If you use the @GeneratedValue annotation to specify a primary key generator of type TABLE, then you can use the @TableGenerator annotation to fine tune this primary key generator to:
change the name of the primary key generator's table because the name is awkward, a reserved word, incompatible with a pre-existing data model, or invalid as a table name in your database
change the allocation size to match your application requirements or database performance parameters
change the initial value to match an existing data model (for example, if you are building on an existing data set for which a range of primary key values has already been assigned or reserved)
configure the primary key generator's table with a specific catalog or schema
configure a unique constraint on one or more columns of the primary key generator's table
Table 1-46 lists the attributes of this annotation. For more details, see the API.
Table 1-46 @TableGenerator Attributes
Attribute Required Description
name
The name of the SequenceGenerator must match the name of a GeneratedValue with its startegy set to TABLE. The scope of the generator name is global to the persistence unit (across all generator types).
allocationSize
Default: 50.
By default, the JPA persistence provider uses an allocation size of 50.
If this allocation size does not match your application requirements or database performance parameters, set allocationSize to the int value you want.
catalog
Default: a JPA persistence provider uses whatever the default catalog is for your database.
If the default catalog is inappropriate for your application, set the catalog to the String catalog name to use.
initialValue
Default: 0.
By default, a JPA persistence provider starts all primary key values from 0.
If this does not match an existing data model, set initialValue to the int value you want.
pkColumnName
Default: the JPA persistence provider provides a name for the primary key column in the generator table.
If this name is inappropriate for your application, set pkColumnName to the String name you want.
pkColumnValue
Default: the JPA persistence provider provides a suitable primary key value for the primary key column in the generator table.
If this value is inappropriate for your application, set pkColumnValue to the String value you want.
schema
Default: a JPA persistence provider uses whatever the default schema is for your database.
If the default schema is inappropriate for your application, set the schema to the String schema name to use.
table
Default: a JPA persistence provider provides a suitable name for the table that stores the generated ID values.
If the default table name is inappropriate for your application, set table tot he String table name you want.
uniqueConstraints
Default: a JPA persistence provider assumes that none of the columns in the primary key generator table have unique constraints.
If unique constraints do apply to one or more columns in this table, set uniqueContraints to an array of one or more UniqueConstraint instances. For more information, see @UniqueConstraint.
valueColumnName
Default: a JPA persistence provider provides a suitable name for the column that stores the generated ID values.
If the default column name is inappropriate for your application, set valueColumnName tot he String column name you want.
Example 1-87 shows how to use this annotation to specify the allocation size for the TABLE primary key generator named empGen.
Example 1-87 @TableGenerator
@Entity
public class Employee implements Serializable {
...
@Id
@TableGenerator(
name="empGen",
allocationSize=1
)
@GeneratedValue(strategy=TABLE, generator="empGen")
@Column(name="CUST_ID")
public Long getId() {
return id;
}
...
@Temporal
Use the @Temporal annotation to specify the database type that a JPA persistence provider should persist for persistent fields or properties of type java.util.Date and java.util.Calendar only.
This annotation can be used with @Basic.
Table 1-14 lists the attributes of this annotation. For more details, see the API.
Table 1-47 @Temporal Attributes
Attribute Required Description
value
Set value to the TemporalType that corresponds to the database type you want a JPA persistence provider to use:
DATE - equivalent to java.sql.Date
TIME - equivalent to java.sql.Time
TIMESTAMP - equivalent to java.sql.Timestamp
Example 1-88 shows how to use this annotation to specify that a JPA persistence provider should persist java.util.Date field startDate as a DATE (java.sql.Date) database type.
Example 1-88 @Temporal
@Entity
public class Employee {
...
@Temporal(DATE) protected java.util.Date startDate;
...
}
@Transient
By default, a JPA persistence provider assumes that all the fields of an entity are persistent.
Use the @Transient annotation to specify a field or property of an entity that is not persistent, for example, a field or property that is used at run time but that is not part of the entity's state.
A JPA persistence provider will not persist (or create database schema) for a property or field annotated as @Transient.
This annotation can be used with @Entity, @MappedSuperclass, and @Embeddable.
This annotation has no attributes. For more details, see the API.
Example 1-89 shows how to use this annotation to specify Employee field currentSession as not persistent. A JPA persistence provider will not persist this field.
Example 1-89 @Transient
@Entitypublic class Employee { @Id int id; @Transient Session currentSession; ...}
@UniqueConstraint
By default, a JPA persistence provider assumes that all columns may contain duplicate values.
Use the @UniqueConstraint annotation to specify that a unique constraint is to be included in the generated DDL for a primary or secondary table. Alternatively, you can specify unique constraints at the column level (see @Column).
Table 1-48 lists the attributes of this annotation. For more details, see the API.
Table 1-48 @UniqueConstraint Attributes
Attribute Required Description
columnNames
If any columns have a unique constraint, set columnNames to the array of String column names.
Example 1-90 shows how to use this annotation to specify a unique constraint on columns EMP_ID and EMP_NAME in primary table EMP.
Example 1-90 @Table with Unique Constraints
@Entity
@Table(
name="EMP",
uniqueConstraints={@UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})}
)
public class Employee implements Serializable {
...
}
@Version
By default, a JPA persistence provider assumes that the application is responsible for data consistency.
Use the @Version annotation to enable JPA-managed optimistic locking by specifying the version field or property of an entity class that serves as its optimistic lock value (recommended).
When choosing a version field or property, ensure that:
there is only one version field or property per entity
you choose a property or field persisted to the primary table (see @Table)
your application does not modify the version property or field
This annotation has no attributes. For more details, see the API.
Example 1-91 shows how to use this annotation to specify property getVersionNum as the optimistic lock value. In this example, the column name for this property is set to OPTLOCK (see @Column) instead of the default column name for the property.
Example 1-91 @Version
@Entity
public class Employee implements Serializable {
...
@Version
@Column(name="OPTLOCK")
protected int getVersionNum() {
return versionNum;
}
...
}
Lifecycle Event Annotations
Use the following lifecycle event annotations to associate a lifecycle event with a callback method if you need to execute custom logic during a lifecycle event:
@PostLoad
@PostPersist
@PostRemove
@PostUpdate
@PrePersist
@PreRemove
@PreUpdate
Figure 1-1 illustrates the relationship amongst the entity lifecycle events that JPA supports.
You can annotate an entity method directly or you can specify one or more entity listener classes (see @EntityListeners).
If you annotate an entity method directly, then that entity method must meet the following requirements:
The entity class method must have the following signature:
public int <MethodName>()
The entity class method can have any method name as long as it does not begin with ejb.
Figure 1-1 JPA Entity LIfecycle Callback Event Annotations
Description of "Figure 1-1 JPA Entity LIfecycle Callback Event Annotations"
@PostLoad
The @PostLoad method for an entity is invoked after the entity has been loaded into the current persistence context from the database or after the refresh operation has been applied to it. This method is invoked before a query result is returned or accessed or before an association is traversed.
Use the @PostLoad annotation if you need to invoke custom logic at this point during the entity lifecycle.
This annotation has no attributes. For more details, see the API.
@PostPersist
The @PostPersist callback method is invoked for an entity after the entity has been persistent. This method is invoked on all entities to which this operation is cascaded. This method is invoked after the database insert operations. These database operations may occur directly after the persist operations have been invoked or they may occur directly after a flush operation has occurred (which may be at the end of the transaction). Generated primary key values are available in the PostPersist method.
Use the @PostPersist annotation to notify any dependent objects or to update information not accessible until the object has been inserted.
This annotation has no attributes. For more details, see the API.
@PostRemove
The @PostRemove callback method is invoked for an entity after the entity has been removed. This method is invoked on all entities to which this operation is cascaded. This method is invoked after the database delete operations. These database operations may occur directly after the remove operations have been invoked or they may occur directly after a flush operation has occurred (which may be at the end of the transaction).
Use the @PostRemove annotation to notify any dependent objects.
This annotation has no attributes. For more details, see the API.
@PostUpdate
The @PostUpdate callback method is invoked for an entity after the database update operations to entity data. These database operations may occur at the time the entity state is updated or they may occur at the time state is flushed to the database (which may be at the end of the transaction). Note that it is implementation-dependent as to whether this callback occurs when an entity is persisted and subsequently modified in a single transaction or when an entity is modified and subsequently removed within a single transaction. Portable applications should not rely on such behavior.
Use the @PostUpdate annotation if you need to invoke custom logic at this point during the entity lifecycle.
This annotation has no attributes. For more details, see the API.
@PrePersist
The @PrePersist callback method is invoked for a given entity before the respective EntityManager persist operations for that entity are executed. For entities to which the merge operation has been applied and causes the creation of newly managed instances, this method is invoked for the managed instance after the entity state has been copied to it. This method is invoked on all entities to which this operation is cascaded.
Use the @PrePersist annotation if you need to invoke custom logic at this point during the entity lifecycle.
This annotation has no attributes. For more details, see the API.
@PreRemove
The @PreRemove callback method is invoked for a given entity before the respective EntityManager remove operations for that entity are executed. This method is invoked on all entities to which this operation is cascaded.
Use the @PreRemove annotation if you need to invoke custom logic at this point during the entity lifecycle.
This annotation has no attributes. For more details, see the API.
@PreUpdate
The @PreUpdate callback method is invoked for an entity before the database update operations to entity data. These database operations may occur at the time the entity state is updated or they may occur at the time state is flushed to the database (which may be at the end of the transaction). Note that it is implementation-dependent as to whether this callback occurs when an entity is persisted and subsequently modified in a single transaction. Portable applications should not rely on such behavior.
Use the @PreUpdate annotation if you need to invoke custom logic at this point during the entity lifecycle.
This annotation has no attributes. For more details, see the API.
Index of Annotations
A
@AssociationOverride
@AssociationOverrides
@AttributeOverride
@AttributeOverrides
B
@Basic
C
@Column
@ColumnResult
D
@DiscriminatorColumn
@DiscriminatorValue
E
@Embeddable
@Embedded
@EmbeddedId
@Entity
@EntityListeners
@EntityResult
@Enumerated
@ExcludeDefaultListeners
@ExcludeSuperclassListeners
F
@FieldResult
G
@GeneratedValue
I
@Id
@IdClass
@Inheritance
J
@JoinColumn
@JoinColumns
@JoinTable
L
@Lob
M
@ManyToMany
@ManyToOne
@MapKey
@MappedSuperclass
N
@NamedNativeQueries
@NamedNativeQuery
@NamedQueries
@NamedQuery
O
@OneToMany
@OneToOne
@OrderBy
P
@PersistenceContext
@PersistenceContexts
@PersistenceProperty
@PersistenceUnit
@PersistenceUnits
@PrimaryKeyJoinColumn
@PrimaryKeyJoinColumns
Q
@QueryHint
S
@SecondaryTable
@SecondaryTables
@SequenceGenerator
@SqlResultSetMapping
@SqlResultSetMappings
T
@Table
@TableGenerator
@Temporal
@Transient
U
@UniqueConstraint
V
@Version
JPA Annotation Reference
http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html
jpa javadoc Reference
http://java.sun.com/javaee/5/docs/api/index.html?javax/persistence/package-summary.html
浙公网安备 33010602011771号