The Java Persistence API (JPA), part of the Java Enterprise Edition 5 (Java EE 5) Enterprise JavaBeans (EJB) 3.0 specification, greatly simplifies Java 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.
When using TopLink JPA, you can configure the JPA behavior of your entities using annotations. An annotation is 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 TopLink JPA 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.
This reference quotes extensively from the JSR-220 Enterprise JavaBeans v.3.0 Java Persistence API 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:
Oracle Fusion Middleware Java API Reference for Oracle TopLink
Table 1-1 JPA Annotations by Category
| Category | Description | Annotations |
|---|---|---|
|
Entity |
By default, TopLink JPA 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 |
|
|
Database Schema Attributes |
By default, TopLink JPA 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. |
|
|
Identity |
By default, TopLink JPA 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:
You can also use these annotations to fine-tune how your database maintains the identity of your entities. |
|
|
Direct Mappings |
By default, TopLink JPA automatically configures a Use these annotations to fine-tune how your database implements these mappings. |
|
|
Relationship Mappings |
TopLink JPA requires that you map relationships explicitly, but TopLink allows some defaulting. Use these annotations to specify the type and characteristics of entity relationships to fine-tune how your database implements these relationships. |
|
|
Composition |
Some objects cannot exist on their own, but can only be embedded within owning entities. Use these annotations to specify objects that are embedded and to override how they are mapped in the owning entity's table. |
|
|
Inheritance |
By default, TopLink JPA 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. |
|
|
Locking |
By default, TopLink JPA assumes that the application is responsible for data consistency. It is recommended that you use this annotation to enable TopLink JPA-managed optimistic locking. |
|
|
Lifecycle Callback Events |
By default, TopLink JPA handles all persistence operations. Use these annotations to associate 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. |
|
|
Entity Manager |
In an application that uses TopLink JPA, you perform all persistence operations (create, read, update, and delete) using an instance of Use these annotations to declare or inject an entity manager or entity manager factory. |
|
|
Queries |
In an application that uses TopLink JPA, 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. |
|
By default, TopLink JPA 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 in an @Embeddable to change the @JoinColumn associated with the existing field or property.
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-2 lists the attributes of this annotation. For more details, see the API.
Table 1-2 @AssociationOverride Attributes
| Attribute | Required | Description |
|---|---|---|
|
|
|
The name of the field or property defined in the embedded object or mapped superclass. |
|
|
|
To specify the join columns that are being mapped to the persistent attribute, set The mapping type will remain the same as is defined in the embeddable class or mapped superclass. |
Example 1-1 shows a @MappedSuperclass that the entity in Example 1-2 extends. Example 1-2 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 @AssociationOverride, the PartTimeEmployee table would have the Address relationship mapped to the ADDR_ID column. Other entity subclasses of Employee would inherit the default mapping to the ADDRESS_ID column, assuming that the primary key column of Address is ID.
If you need to specify more than one @AssociationOverride, you must specify all your association overrides using a single @AssociationOverrides annotation.
Table 1-3 lists the attributes of this annotation. For more details, see the API.
Table 1-3 @AssociationOverrides Attributes
| Attribute | Required | Description |
|---|---|---|
|
|
|
To specify two or more association overrides, set |
Example 1-3 shows how to use this annotation to specify two association overrides.
By default, TopLink JPA automatically assumes that a subclass inherits both persistent properties and their basic mappings as defined in a mapped superclass.
Use the @AttributeOverride annotation to customize a basic mapping inherited from a @MappedSuperclass or in an @Embeddable to change the @Column associated with the field or property.
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 |
|---|---|---|
|
|
|
The name of the field or property defined in the embedded object or mapped superclass. |
|
|
|
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. |
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 id.
With the @AttributeOverride annotation, the PartTimeEmployee table would have the id attribute mapped to the PTEMP_ID column. Other entity subclasses of Employee would inherit the default mapping to the ID column.
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 |
|---|---|---|
|
|
|
To specify two or more attribute overrides, set |
Example 1-6 shows how to use this annotation to specify two attribute overrides.
By default, TopLink JPA 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.
Table 1-6 lists the attributes of this annotation. For more details, see the API.
Table 1-6 @Basic Attributes
| Attribute | Required | Description |
|---|---|---|
|
|
|
Default: By default, TopLink JPA uses a fetch type of If this is inappropriate for your application or a particular persistent field, set |
Example 1-7 shows how to use this annotation to specify a fetch type of LAZY for a basic mapping.
By default, TopLink JPA assumes that each of an entity's persistent attributes is stored in a database table column whose name matches that of the persistent field or property.
Use the @Column annotation:
to associate a persistent attribute 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 attribute 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 |
|---|---|---|
|
|
|
Default: TopLink JPA assumes that each of an entity's persistent attributes is stored in a database table column whose name matches that of the persistent field or property. To specify an alternative column name, set |
|
|
|
Default: By default, TopLink JPA assumes that all non-primary key columns are allowed to contain duplicate values. If this column is not allowed to contain duplicate values, set |
|
|
|
Default: By default, TopLink JPA assumes that all columns are allowed to contain a null value. If this column is not allowed to contain a null value, set |
|
|
|
Default: By default, TopLink JPA assumes that all columns are always included in If this column should not be included in these statements, set |
|
|
|
Default: By default, TopLink JPA assumes that a column is always included in If this column should not be included in these statements, set |
|
|
|
Default: empty By default, TopLink JPA creates a database table column with minimal SQL. If you want the column created with more specialized options, set |
|
|
|
Default: TopLink JPA assumes that all the persistent attributes of an entity are stored in a single database table whose name is the entity name or is specified by If this column is associated with a secondary table (see @SecondaryTable), set |
|
|
|
Default: 255 By default, TopLink JPA assumes that all columns have a maximum length of 255 characters when used to hold a If this column width is inappropriate for your application or database, set the |
|
|
|
Default: 0. By default, TopLink JPA 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 |
|
|
|
Default: 0. By default, TopLink JPA 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 |
Example 1-8 shows how to use this annotation to make TopLink JPA persist salary to column SAL in secondary table EMP_SAL. By default, TopLink JPA persists salary to column salary in primary table EMPLOYEE.
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 |
|---|---|---|
|
|
|
Set |
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;
@ManyToOne(fetch=LAZY)
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"], ...}
By default, when @Inheritance attribute strategy is InheritanceType.SINGLE_TABLE or JOINED, TopLink JPA 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 |
|---|---|---|
|
|
|
Default: TopLink JPA assumes that the discriminator column is named " To specify an alternative column name, set |
|
|
|
Default: By default, TopLink JPA assumes that the discriminator type is a If you want to use a different type, set Your @DiscriminatorValue must conform to this type. |
|
|
|
Default: empty By default, TopLink JPA creates a database table column with minimal SQL. If you want the column created with more specialized options, set |
|
|
|
Default: 31 By default, TopLink JPA assumes that the discriminator column has a maximum length of 31 characters when used to hold a If this column width is inappropriate for your application or database, set the Your @DiscriminatorValue must conform to this length. |
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 ValuedCustomer subclass 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
@Entity
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
@DiscriminatorValue(value-"CUST")
public class Customer {
...
}
@Entity
@DiscriminatorValue("VIP")
public class ValuedCustomer extends Customer {
...
}
By default, when @Inheritance attribute strategy is InheritanceType.SINGLE_TABLE or JOINED, TopLink JPA uses the entity name as a @DiscriminatorValue to differentiate classes in the inheritance hierarchy (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 |
|---|---|---|
|
|
|
Set |
Example 1-13 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 ValuedCustomer subclass 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-13 @DiscriminatorColumn and @DiscriminatorValue
@Entity
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
@DiscriminatorValue("CUST")
public class Customer {
...
}
@Entity
@DiscriminatorValue("VIP")
public class ValuedCustomer extends Customer {
...
}
By default, TopLink JPA 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-14 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-15).
By default, TopLink JPA 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 default, column definitions (see @Column) specified in the @Embeddable class apply to the table of the owning entity. If you want to override these column definitions, use @AttributeOverride.
This annotation has no attributes. For more details, see the API.
Example 1-15 shows how to use this annotation to specify that @Embeddable class EmploymentPeriod (see Example 1-14) 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: TopLink JPA will infer that EmploymentPeriod is embedded from its @Embeddable annotation.
Example 1-15 @Embedded
@Entity
public class Employee implements Serializable {
...
@Embedded
@AttributeOverrides({
@AttributeOverride(name="startDate", column=@Column(name="EMP_START")),
@AttributeOverride(name="endDate", column=@Column(name="EMP_END"))
)
public EmploymentPeriod getEmploymentPeriod() {
...
}
...
}
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-16 shows a typical composite primary key class, annotated as @Embeddable. Example 1-17 shows how to configure an entity with this embeddable composite primary key class using the @EmbeddedId annotation.
Example 1-16 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 == null) return false;
if (!(obj instanceof EmployeePK)) return false;
EmployeePK pk = (EmployeePK) obj;
return pk.id == id && pk.name.equals(name);
}
}
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 |
|---|---|---|
|
|
|
Default: TopLink JPA assumes that the name of the entity is the unqualified name of the entity class. In Example 1-18, the default 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 |
Example 1-18 shows how to use this annotation.
You can use lifecycle annotations (see Lifecycle Event Annotations) to designate methods 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, TopLink JPA 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 |
|---|---|---|
|
|
|
To specify the list of entity listener classes for an @Entity or @MappedSuperclass, set |
Example 1-19 shows how to use this annotation to associate entity listener classes EmployeePersistListener (see Example 1-20) and EmployeeRemoveListener (see Example 1-21) with the entity Employee. Example 1-21 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-19 @EntityListeners
@Entity
@EntityListeners({EmployeePersistListener.class, EmployeeRemoveListener.class})
public class Employee implements Serializable {
...
}
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-13 lists the attributes of this annotation. For more details, see the API.
Table 1-13 @EntityResult Attributes
| Attribute | Required | Description |
|---|---|---|
|
|
|
Set |
|
|
|
Default: empty By default, TopLink JPA assumes that the 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 ( |
|
|
|
Default: empty By default, TopLink JPA assumes that a discriminator column (see @Inheritance) is not included in the If you use a discriminator column in your |
Example 1-22 shows how to use this annotation to include both Order and Item (see Example 1-23) entities in the result list (see Example 1-24). In this case, the result list would be a List of Object arrays like: {[Order, Item], [Order, Item], ...}.
Example 1-22 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;
@ManyToOne
protected Item item;
...
}
Example 1-23 Item Entity
@Entity
public class Item {
@Id
protected int id;
protected String name;
...
}
Example 1-24 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], ...}
By default, TopLink JPA persists the ordinal values of enumerated constants.
Use the @Enumerated annotation to specify whether TopLink JPA 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 |
|---|---|---|
|
|
|
Default: By default, TopLink JPA assumes that for a property or field mapped to an enumerated constant, the ordinal value should be persisted. In Example 1-26, the ordinal value of If you want the String value of the enumerated constant persisted, set |
Given the enumerated constants in Example 1-25, Example 1-26 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.
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). TopLink JPA 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-27 shows how to use this annotation to specify that default listeners should not be executed for the Employee entity.
If the @Entity and @MappedSuperclass classes in an inheritance hierarchy define @EntityListeners, by default, TopLink JPA 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-28 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.
When you execute a @NamedNativeQuery, it can return entities (including entities of different types), scalar values, or a combination of both.
By default, TopLink JPA 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 |
|---|---|---|
|
|
|
Set |
|
|
|
Set |
Example 1-30 shows how to use this annotation to include both Order and Item (see Example 1-31) entities in the result list (see Example 1-32). In this case, the result list would be a List of Object arrays like: {[Order, Item], [Order, Item], ...}.
Example 1-30 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;
@ManyToOne
protected Item item;
...
}
Example 1-31 Item Entity
@Entity
public class Item {
@Id
protected int id;
protected String name;
...
}
Example 1-32 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], ...}
By default, the application is responsible for supplying and setting entity identifiers (see @Id).
Use the @GeneratedValue annotation if you want TopLink JPA to provide and manage entity identifiers.
Table 1-16 lists the attributes of this annotation. For more details, see the API.
Table 1-16 @GeneratedValue Attributes
| Attribute | Required | Description |
|---|---|---|
|
|
|
Default: By default, TopLink JPA 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
|
|
|
|
Default: TopLink JPA 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 |
Example 1-33 shows how to use this annotation to tell TopLink JPA to use a primary key generator of type GeneratorType.SEQUENCE named CUST_SEQ.
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.
Example 1-34 shows how to use this annotation to designate persistent field empID as the primary key of the Employee table.
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 |
|---|---|---|
|
|
|
To specify a composite primary key class, set |
Example 1-35 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-36 shows how to configure a JPA 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-35 Non-Embedded Composite Primary Key Class
public class EmployeePK implements Serializable
{
private String empName;
private Date birthDay;
public EmployeePK() { }
public String getEmpName() {
return empName;
}
public void setEmpName(String name) {
empName = name;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date date) {
birthDay = date;
}
public int hashCode() {
return (int) empName.hashCode();
}
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null) return false;
if (!(obj instanceof EmployeePK)) return false;
EmployeePK pk = (EmployeePK) obj;
return pk.birthDay == birthDay && pk.empName.equals(empName);
}
}
By default, TopLink JPA automatically manages the persistence of entities in an inheritance hierarchy.
Use the @Inheritance annotation to customize the TopLink JPA 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 |
|---|---|---|
|
|
|
Default: By default, TopLink JPA 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
|
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-37 shows how to use this annotation to specify that all subclasses of Customer will use InheritanceType.JOINED. The subclass in Example 1-38 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-37 @Inheritance - Root Class Using JOINED
@Entity@Inheritance(strategy=JOINED)public class Customer {
@Id
private int customerId;
...
}
Example 1-38 @Inheritance - Subclass Using JOINED
@Entity
public class ValuedCustomer extends Customer {
...
}
In Example 1-39, by default, InheritanceType.SINGLE_TABLE applies to Customer and all its subclasses. In this example, the default discriminator column DTYPE (see @DiscriminatorColumn) is specified as having a discriminator type of INTEGER and the @DiscriminatorValue for Customer is specified as 1. Example 1-40 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.
By default, in an entity association, TopLink JPA 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 |
|---|---|---|
|
|
|
Default: if you are using a single join column, TopLink JPA assumes that the name of the foreign key column is the name of the referencing relationship field or property + "_" + the name of the referenced primary key column. If join columns are being used in a join table (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. 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 |
|
|
|
Default: if you are using a single join column, TopLink JPA 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 |
|
|
|
Default: By default, TopLink JPA assumes that join columns are allowed to contain duplicate values. If this column is not allowed to contain duplicate values, set |
|
|
|
Default: By default, TopLink JPA assumes that all columns are allowed to contain a null value. If this column is not allowed to contain a null value, set |
|
|
|
Default: By default, TopLink JPA assumes that it can insert into all table columns. If this column is read-only, set |
|
|
|
Default: By default, TopLink JPA assumes that it can update all table columns. If this column is read-only, set |
|
|
|
Default: empty TopLink JPA creates a database table column with minimal SQL. If you want the column created with more specialized options, set |
|
|
|
Default: TopLink JPA assumes that join columns of one-to-one and many-to-one relationships 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 |
Example 1-41 shows how to use this annotation to make TopLink JPA use database table Employee column ADDR_ID as the join column.
By default, in an entity association, TopLink JPA 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 |
|---|---|---|
|
|
|
To specify two or more join columns, set |
Example 1-42 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.
By default, TopLink JPA uses a 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 TopLink JPA assumes that there is a join column for the primary key column of each of the entities in 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 |
|---|---|---|
|
|
|
Default: TopLink JPA 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 |
|
|
|
Default: By default, TopLink JPA uses whatever the default catalog is for your database. If the default catalog is inappropriate for your application, set the |
|
|
|
Default: By default, TopLink JPA uses whatever the default schema is for your database.empty. If the default schema is inappropriate for your application, set the |
|
|
|
Default: By default, TopLink JPA assumes that there is a single join column for the owning entity's primary key column. TopLink JPA names the column 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 |
|
|
|
Default: By default, TopLink JPA assumes that there is a single join column on the inverse side of the association. TopLink 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 |
|
|
|
Default: empty array of By default, TopLink JPA 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 |
Example 1-43 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-43 @JoinTable
@Entity
public class Employee implements Serializable {
...
@ManyToMany
@JoinTable(
name="PROJ_EMP",
joinColumns=@JoinColumn(name="EMP_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="PROJ_ID", referencedColumnName="ID")
)
public Collection getProjects() {
return projects;
}
...
}
By default, TopLink JPA assumes that all persistent data can be represented as typical database data types.
Use the @Lob annotation with a 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. TopLink JPA 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-44 shows how to use this annotation to specify that persistent field pic should be persisted as a Blob.
By default, TopLink JPA automatically defines a @ManyToMany mapping for a many-valued association with many-to-many multiplicity.
Use the @ManyToMany annotation to:
declare the cardinality of the relationship
configure the fetch type to EAGER
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
Table 1-22 lists the attributes of this annotation. For more details, see the API.
Table 1-22 @ManyToMany Attributes
| Attribute | Required | Description |
|---|---|---|
|
|
|
Default: the parameterized type of the By default, if you are using a If your |
|
|
|
Default: empty array of By default, TopLink 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
|