NPersistence Reference Guide
 

Types

            
 All Types  Classes   Interfaces  Enumerations 
 NameDescription
Access
Used to specify an access type to be applied to an entity class, mapped superclass, or embeddable class, or to a specific attribute of such a class.
AccessType
Is used with the Access annotation to specify an access type to be applied to an entity class, mapped superclass, or embeddable class, or to a specific attribute of such a class.
AssociationOverride
Used to override a mapping for an entity relationship.

May be applied to an entity that extends a mapped superclass to override a relationship mapping defined by the mapped superclass. If not specified, the association is mapped the same as in the original mapping. When used to override a mapping defined by a mapped superclass, AssociationOverride is applied to the entity class.

May be used to override a relationship mapping from an embeddable within an entity to another entity when the embeddable is on the owning side of the relationship. When used to override a relationship mapping defined by an embeddable class (including an embeddable class embedded within another embeddable class), AssociationOverride is applied to the field or property containing the embeddable.

When AssociationOverride is used to override a relationship mapping from an embeddable class, the name element specifies the referencing relationship field or property within the embeddable class. To override mappings at multiple levels of embedding, a dot (".") notation syntax must be used in the name element to indicate an attribute within an embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.

When AssociationOverride is applied to override the mappings of an embeddable class used as a map value, "value." must be used to prefix the name of the attribute within the embeddable class that is being overridden in order to specify it as part of the map value.

If the relationship mapping is a foreign key mapping, the joinColumn elements are used. If the relationship mapping uses a join table, the joinTable element must be specified to override the mapping of the join table and/or its join columns.

Examples

CopyC#
Example 1: Overriding the mapping of a relationship defined by a mapped superclass

[MappedSuperclass]
public class Employee {
    ...
    [ManyToOne]
    protected Address address;
    ...
}

[Entity] 
    [AssociationOverride(Name="address")]
    [JoinColumn(AttibuteRef="address",Name="ADDR_ID")]
    // address field mapping overridden to ADDR_ID foreign key
public class PartTimeEmployee extends Employee {
    ...
}

Examples

CopyC#
Example 2: Overriding the mapping for phoneNumbers defined in the ContactInfo class

  [Entity]
 public class Employee {
     [Id]
     public virtual int id { get; set; }
     [AssociationOverride(Name="phoneNumbers")]
     [JoinTable(Name="EMPPHONES", AssociationOverrideRef="phoneNumbers")]
     [JoinColumn(AttributeRef="EMPPHONES", Name="EMP")]
     [JoinColumn(AttributeRef="EMPPHONES",Name="PHONE", Inverse=true)]
     [Embedded]
     public virtual ContactInfo contactInfo { get; set; }
 }

 [Embeddable]
 public class ContactInfo {
     [ManyToOne] Address address; // Unidirectional
     [ManyToMany(TargetEntity=typeof(PhoneNumber))]
     public virtual IList phoneNumbers { get; set; }
  }

[Entity]
 public class PhoneNumber {
     [Id]
     public virtual int number { get; set; }
     [ManyToMany(MappedBy="contactInfo.phoneNumbers")]
     public virtual Collection<Employee> employees { get; set; }
 }
AttributeOverride
Used to override the mapping of a Basic (whether explicit or default) property or field or Id property or field.

May be applied to an entity that extends a mapped superclass or to an embedded field or property to override a basic mapping or id mapping defined by the mapped superclass or embeddable class (or embeddable class of one of its attributes).

May be applied to an element collection containing instances of an embeddable class or to a map collection whose key and/or value is an embeddable class. When AttributeOverride is applied to a map, "key." or "value." must be used to prefix the name of the attribute that is being overridden in order to specify it as part of the map key or map value.

To override mappings at multiple levels of embedding, a dot (".") notation form must be used in the name element to indicate an attribute within an embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.

If AttributeOverride is not specified, the column is mapped the same as in the original mapping.

Examples

CopyC#
 Example 1:

 [MappedSuperclass]
 public class Employee {
     [Id] protected Integer id;
     [Version] protected Integer version;
     protected String address;
     public Integer getId() { ... }
     public void setId(Integer id) { ... }
     public String getAddress() { ... }
     public void setAddress(String address) { ... }
 }

 [Entity]
 [AttributeOverride(PropertyName="address", Name="ADDR"))]
 public class PartTimeEmployee extends Employee {
     // address field mapping overridden to ADDR
     protected Float wage();
     public Float getHourlyWage() { ... }
     public void setHourlyWage(Float wage) { ... }
 }


 Example 2:

 [Embeddable] public class Address {
     protected String street;
     protected String city;
     protected String state;
     [Embedded] protected Zipcode zipcode;
 }

 [Embeddable] public class Zipcode {
     protected String zip;
     protected String plusFour;
 }

 [Entity] public class Customer {
     [Id] protected Integer id;
     protected String name;
     [AttributeOverride(PropertyName="state", Name="ADDR_STATE")]
     [AttributeOverride(PropertyName="zipcode.zip", Name="ADDR_ZIP")]
     })
     [Embedded] protected Address address;
     ...
 }


 Example 3:

 [Entity] public class PropertyRecord {
     [Embedded]Id PropertyOwner owner;
     [AttributeOverride(PropertyName="key.street", Name="STREET_NAME")]
     [AttributeOverride(PropertyName="value.size", Name="SQUARE_FEET")]
     [AttributeOverride(PropertyName="value.tax", Name="ASSESSMENT")]

    [ElementCollection]
    Dictionary<Address, PropertyInfo> parcels;
 }

[Embeddable] public class PropertyInfo {
    Integer parcelNumber;
    Integer size;
    BigDecimal tax;
}
Basic
The simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types:

primitive types, wrappers of the primitive types, String,

System.Numerics.BigInteger,

System.Decimal,

System.DateTime,

System.Data.DbType.Date,

System.Data.DbType.Time,

System.Data.DbType.Timestamp, byte[], Byte[],

char[], Character[], enums, and any other type that implements System.Runtime.Serialization.ISerializable.

The use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

Examples

CopyC#
Example 1:

[Basic]
protected String name;

Example 2:

[Basic(fetch=LAZY)]
protected String getName() { return name; }
Cache
Interface used to interact with the second-level cache. If a cache is not in use, the methods of this interface have no effect, except for contains, which returns false.
Cacheable
Specifies whether an entity should be cached if caching is enabled when the value of the persistence.xml caching element is ENABLE_SELECTIVE or DISABLE_SELECTIVE. The value of the Cacheable annotation is inherited by subclasses; it can be overridden by specifying Cacheable on a subclass.

Cacheable(false) means that the entity and its state must not be cached by the provider.

CacheRetrieveMode
Used as the value of the NPersistence.cache.retrieveMode property to specify the behavior when data is retrieved by the find methods and by queries.
CacheStoreMode
Used as the value of the NPersistence.cache.storeMode property to specify the behavior when data is read from the database and when data is committed into the database.
CascadeType
Defines the set of cascadable operations that are propagated to the associated entity. The value cascade=ALL is equivalent to cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}.
CollectionTable
Specifies the table that is used for the mapping of collections of basic or embeddable types. Applied to the collection-valued field or property.

By default, the columns of the collection table that correspond to the embeddable class or basic type are derived from the attributes of the embeddable class or from the basic type according to the default values of the Column annotation. In the case of a basic type, the column name is derived from the name of the collection-valued field or property. In the case of an embeddable class, the column names are derived from the field or property names of the embeddable class.

  • To override the default properties of the column used for a basic type, the Column annotation is used on the collection-valued attribute in addition to the ElementCollection annotation.
  • To override these defaults for an embeddable class, the AttributeOverride annotations can be used in addition to the ElementCollection annotation. If the embeddable class contains references to other entities, the default values for the columns corresponding to those references may be overridden by means of the AssociationOverride annotations.
If the CollectionTable annotation is missing, the default values of the CollectionTable annotation elements apply.

Examples

CopyC#
Example:

[Embeddable] public class Address {
   protected String street;
   protected String city;
   protected String state;
   ... 
 }

[Entity] public class Person {
   [Id] protected String ssn;
   protected String name;
   protected Address home;
   ...
   [ElementCollection]  // use default table (PERSON_NICKNAMES)
   [Column(name="name", length=50)]
   protected Set<String> nickNames = new HashSet();
   ...
}

[Entity] public class WealthyPerson extends Person {
   [ElementCollection]
   [CollectionTable(name="HOMES")] // use default join column name
      [AttributeOverride(PropertyName="street", Name="HOME_STREET")]
      [AttributeOverride(PropertyName="city", Name="HOME_CITY")]
      [AttributeOverride(PropertyName="state", Name="HOME_STATE")]
      [UniqueConstraint(TableRef = "HOMES", Name = "unique1", ColumnNames = new String[] { "HOME_STREET", "HOME_CITY" })]
   protected Set<Address> vacationHomes = new HashSet();
   ...
}
Column
Is used to specify the mapped column for a persistent property or field. If no Column annotation is specified, the default values apply.

Examples

CopyC#
Example 1:

[Column(name="DESC", nullable=false, length=512)]
public String getDescription() { return description; }

Example 2:

[Column(name="DESC",
        columnDefinition="CLOB NOT NULL",
        table="EMP_DETAIL")]
[Lob]
public String getDescription() { return description; }

Example 3:

[Column(name="ORDER_COST", updatable=false, precision=12, scale=2) ]
public BigDecimal getCost() { return cost; }
ColumnResult
References name of a column in the SELECT clause of a SQL query - i.e., column alias, if applicable. Scalar result types can be included in the query result by specifying this annotation in the metadata.

Examples

CopyC#
Example:
  Query q = em.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");

  [SqlResultSetMapping(name="OrderResults")]
          [EntityResult(ResultSetRef = "OrderResults", Name="OrderEntityResult", EntityClass=com.acme.Order.class)]
              [FieldResult(EntityRef = "OrderEntityResult", Name="id", Column="ordeR_ID")]
              [FieldResult(EntityRef = "OrderEntityResult", Name="quantity", Column="order_quantity")]
              [FieldResult(EntityRef = "OrderEntityResult", Name="item", Column="order_item")]
          [ColumnResult(ResultSetRef = "OrderResults", Name="item_name", Type = "String")]
ConfigurationSectionHandler
This interface is used for configuring NPersistence inside a web application. Inside a web application the NPersistence configuration is done as follows:
  • The 'persistence-unit' xml tag that configures NPersistence (which is usualy placed inside the persistence.xml file), should be placed in the 'Web.config' file.
  • The 'configSections' tag inside the Web.config file should mention 'NPersistence.ConfigurationSectionHandler' as one of the sections.

Examples

CopyC#
<configuration>
...
  <configSections>
    <section name="persistence-unit"
             type="NPersistence.ConfigurationSectionHandler, NPersistence" />
  </configSections>
...
     <persistence-unit name="examplePersistenceUnit">
   <provider>NPersistence.NHibernate.NHibernatePersistence</provider>
     <class>tests.Employee</class>
   <properties>
     <property name="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
     <property name="dialect" value="NHibernate.Dialect.MySQL5Dialect"/>
     <property name="connection.driver_class" value="NHibernate.Driver.MySqlDataDriver"/>
     <property name="connection.connection_string" value="server=srvName; user id=usrName; password=pass; database=test"/>
   </properties>
 </persistence-unit>
DiscriminatorColumn
Specifies the discriminator column for the

SINGLE_TABLE and

JOINED Inheritance mapping strategies.

The strategy and the discriminator column are only specified in the root of an entity class hierarchy or subhierarchy in which a different inheritance strategy is applied

If the DiscriminatorColumn annotation is missing, and a discriminator column is required, the name of the discriminator column defaults to "DTYPE" and the discriminator type to STRING()()()().

Examples

CopyC#
Example:

[Entity]
[Table(name="CUST")]
[Inheritance(strategy=SINGLE_TABLE)]
[DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)]
public class Customer { ... }

[Entity]
public class ValuedCustomer extends Customer { ... }
DiscriminatorType
Defines supported types of the discriminator column.
DiscriminatorValue
Specifies the value of the discriminator column for entities of the given type.

The DiscriminatorValue annotation can only be specified on a concrete entity class.

If the DiscriminatorValue annotation is not specified and a discriminator column is used, a provider-specific function will be used to generate a value representing the entity type. If the DiscriminatorType is STRING, the discriminator value default is the entity name.

The inheritance strategy and the discriminator column are only specified in the root of an entity class hierarchy or subhierarchy in which a different inheritance strategy is applied. The discriminator value, if not defaulted, should be specified for each entity class in the hierarchy.

Examples

CopyC#
Example:

[Entity]
[Table(name="CUST")]
[Inheritance(strategy=SINGLE_TABLE)]
[DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)]
[DiscriminatorValue("CUSTOMER")]
public class Customer { ... }

[Entity]
[DiscriminatorValue("VCUSTOMER")]
public class ValuedCustomer extends Customer { ... }
ElementCollection
Defines a collection of instances of a basic type or embeddable class. Must be specified if the collection is to be mapped by means of a collection table.

Examples

CopyC#
Example:

[Entity] public class Person {
   [Id] protected String ssn;
   protected String name;
   ...
   [ElementCollection]  
   protected Set<String> nickNames = new HashSet();
     ...
}
Embeddable
Defines 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.

Note that the Transient annotation may be used to designate the non-persistent state of an embeddable class.

Examples

CopyC#
Example 1:

[Embeddable] public class EmploymentPeriod { 
   [Temporal(DATE)] System.DateTime startDate;
   [Temporal(DATE)] System.DateTime endDate;
  ... 
}

Example 2:

[Embeddable] public class PhoneNumber {
    protected String areaCode;
    protected String localNumber;
    [ManyToOne] PhoneServiceProvider provider;
    ...
 }

[Entity] public class PhoneServiceProvider {
    [Id] protected String name;
     ...
 }

Example 3:

[Embeddable] public class Address {
   protected String street;
   protected String city;
   protected String state;
   [Embedded] protected Zipcode zipcode;
}

[Embeddable] public class Zipcode {
   protected String zip;
   protected String plusFour;
 }
Embedded
Specifies a persistent field or property of an entity whose value is an instance of an embeddable class. The embeddable class must be annotated as Embeddable.

The AttributeOverride and AssociationOverride annotations may be used to override mappings declared or defaulted by the embeddable class.

Examples

CopyC#
Example:

[Embedded]
[AttributeOverride(PropertyName="startDate", Name="EMP_START")]
[AttributeOverride(PropertyName="endDate", Name="EMP_END")]
public EmploymentPeriod getEmploymentPeriod() { ... }
EmbeddedId
Applied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. The embeddable class must be annotated as Embeddable.

There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.

The AttributeOverride annotation may be used to override the column mappings declared within the embeddable class.

The MapsId annotation may be used in conjunction with the EmbeddedId annotation to specify a derived primary key.

If the entity has a derived primary key, the AttributeOverride annotation may only be used to override those attributes of the embedded id that do not correspond to the relationship to the parent entity.

Relationship mappings defined within an embedded id class are not supported.

Examples

CopyC#
Example 1:

[EmbeddedId]
protected EmployeePK empPK;


Example 2:

[Embeddable]
public class DependentId {
   String name;
   EmployeeId empPK;   // corresponds to primary key type of Employee
}

[Entity]
public class Dependent {
   // default column name for "name" attribute is overridden
   [AttributeOverride(PropertyName="name", Name="dep_name")]
   [EmbeddedId] DependentId id;
   ...
   [MapsId("empPK")]
   [ManyToOne] Employee emp;
}
Entity
Specifies that the class is an entity. This annotation is applied to the entity class.
EntityExistsException
Thrown by the persistence provider when Persist(Object) is called and the entity already exists. The current transaction, if one is active, will be marked for rollback.

If the entity already exists, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time. The current transaction, if one is active, will be marked for rollback.

EntityListeners
Specifies the callback listener classes to be used for an entity or mapped superclass. This annotation may be applied to an entity class or mapped superclass.
EntityManager
Interface used to interact with the persistence context.

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.

The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.

EntityManagerFactory
Interface used to interact with the entity manager factory for the persistence unit.

When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory. Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state.

EntityNotFoundException
Thrown by the persistence provider when an entity reference obtained by GetReference<(Of <<'(T>)>>)(Type, Object) is accessed but the entity does not exist.

Thrown when Refresh(Object) is called and the object no longer exists in the database.

Thrown when Lock(Object, LockModeType) is used with pessimistic locking is used and the entity no longer exists in the database. The current transaction, if one is active, will be marked for rollback.

EntityResult
Used to map the SELECT clause of a SQL query to an entity result. If this annotation is used, the SQL statement should select all of the columns that are mapped to the entity object.

This should include foreign key columns to related entities. The results obtained when insufficient data is available are undefined.

Examples

CopyC#
Example:

Query q = em.createNativeQuery(
    "SELECT o.id, o.quantity, o.item, i.id, i.name, i.description "+
        "FROM Order o, Item i " +
        "WHERE (o.quantity > 25) AND (o.item = i.id)",
    "OrderItemResults");
[SqlResultSetMapping(name="OrderItemResults")]
        [EntityResult(ResultSetRef = "OrderItemResults", entityClass=com.acme.Order.class)]
        [EntityResult(ResultSetRef = "OrderItemResults", entityClass=com.acme.Item.class)]
EntityTransaction
Interface used to control transactions on resource-local entity managers. The GetTransaction()()()() method returns the EntityTransaction interface.
Enumerated
Specifies that a persistent property or field should be persisted as a enumerated type. The Enumerated annotation may be used in conjunction with the Basic annotation, or in conjunction with the ElementCollection annotation when the element collection value is of basic type.

If the enumerated type is not specified or the Enumerated annotation is not used, the EnumType value is assumed to be ORDINAL.

Examples

CopyC#
Example:

public enum EmployeeStatus {FULL_TIME, PART_TIME, CONTRACT}

public enum SalaryRate {JUNIOR, SENIOR, MANAGER, EXECUTIVE}

[Entity] public class Employee {
    public EmployeeStatus getStatus() {...}
    ...
    [Enumerated(STRING)]
    public SalaryRate getPayScale() {...}
    ...
}
EnumType
Defines mapping for enumerated types. The constants of this enumerated type specify how a persistent property or field of an enumerated type should be persisted.
ExcludeDefaultListeners
Specifies that the invocation of default listeners is to be excluded for the entity class (or mapped superclass) and its subclasses.
ExcludeSuperclassListeners
Specifies that the invocation of superclass listeners is to be excluded for the entity class (or mapped superclass) and its subclasses.
FetchType
Defines strategies for fetching data from the database.

The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched.

The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed.

The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified.

Examples

CopyC#
Example:
[Basic(fetch=LAZY)]
protected String getName() { return name; }
FieldResult
Is used to map the columns specified in the SELECT list of the query to the properties or fields of the entity class.

Examples

CopyC#
Example:
  Query q = em.createNativeQuery(
      "SELECT o.id AS order_id, " +
          "o.quantity AS order_quantity, " +
          "o.item AS order_item, " +
        "FROM Order o, Item i " +
        "WHERE (order_quantity > 25) AND (order_item = i.id)",
      "OrderResults");

  [SqlResultSetMapping(name="OrderResults")]
          [EntityResult(ResultSetRef = "OrderResults", Name="OrderEntityResult", EntityClass=com.acme.Order.class)]
              [FieldResult(EntityRef = "OrderEntityResult", Name="id", Column="ordeR_ID")]
              [FieldResult(EntityRef = "OrderEntityResult", Name="quantity", Column="order_quantity")]
              [FieldResult(EntityRef = "OrderEntityResult", Name="item", Column="order_item")]
FlushModeType
Flush mode setting.

When queries are executed within a transaction, if FlushModeType.AUTO is set on the Query or TypedQuery<(Of <(<'X>)>)> object, or if the flush mode setting for the persistence context is AUTO (the default) and a flush mode setting has not been specified for the Query or TypedQuery object, the persistence provider is responsible for ensuring that all updates to the state of all entities in the persistence context which could potentially affect the result of the query are visible to the processing of the query.

The persistence provider implementation may achieve this by flushing those entities to the database or by some other means. If FlushModeType.COMMIT is set, the effect of updates made to entities in the persistence context upon queries is unspecified.

If there is no transaction active, the persistence provider must not flush to the database.

GeneratedValue
Provides for the specification of generation strategies for the values of primary keys.

The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation. The use of the GeneratedValue annotation is only required to be supported for simple primary keys. Use of the

GeneratedValue annotation is not supported for derived primary keys.

Examples

CopyC#
Example 1:

[Id]
[GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")]
[Column(name="CUST_ID")]
public Long getId() { return id; }

Example 2:

[Id]
[GeneratedValue(strategy=TABLE, generator="CUST_GEN")]
[Column(name="CUST_ID")]
Long id;
GenerationType
Defines the types of primary key generation strategies.
Id
Specifies the primary key of an entity.

The field or property to which the Id annotation is applied should be one of the following types:

any primitive type;

any primitive wrapper type;

String;

System.DateTime;

System.Data.DbType.Date;

System.Decimal;

System.Numerics.BigInteger.

The mapped column for the primary key of the entity is assumed to be the primary key of the primary table. If no Column annotation is specified, the primary key column name is assumed to be the name of the primary key property or field.

Examples

CopyC#
Example:

[Id]
public Long getId() { return id; }
IdClass
Specifies a composite primary key class that is mapped to multiple fields or properties of the entity.

The names of the fields or properties in the primary key class and the primary key fields or properties of the entity must correspond and their types must be the same.

Examples

CopyC#
Example:

[IdClass(com.acme.EmployeePK.class)]
[Entity]
public class Employee {
   [Id] String empName;
   [Id] Date birthDay;
   ...
}
Inheritance
Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.

If the Inheritance annotation is not specified or if no inheritance type is specified for an entity class hierarchy, the SINGLE_TABLE mapping strategy is used.

Examples

CopyC#
Example:

[Entity]
[Inheritance(strategy=JOINED)]
public class Customer { ... }

[Entity]
public class ValuedCustomer extends Customer { ... }
InheritanceType
Defines inheritance strategy options.
JoinColumn
Specifies a column for joining an entity association or element collection.

If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

Examples

CopyC#
Example:

[ManyToOne]
[JoinColumn(name="ADDR_ID")]
public Address getAddress() { return address; }


Example: unidirectional one-to-many association using a foreign key mapping

// In Customer class
[OneToMany]
[JoinColumn(name="CUST_ID")] // join column is in table for Order
public Set<Order> getOrders() {return orders;}
JoinTable
Used in the mapping of associations. It is specified on the owning side of an association.

A join table is typically used in the mapping of many-to-many and unidirectional one-to-many associations. It may also be used to map bidirectional many-to-one/one-to-many associations, unidirectional many-to-one relationships, and one-to-one associations (both bidirectional and unidirectional).

When a join table is used in mapping a relationship with an embeddable class on the owning side of the relationship, the containing entity rather than the embeddable class is considered the owner of the relationship.

If the JoinTable annotation is missing, the default values of the annotation elements apply. The name of the join table is assumed to be the table names of the associated primary tables concatenated together (owning side first) using an underscore.

Examples

CopyC#
Example:

[JoinTable(name="CUST_PHONE")]
   [JoinColumn(AttributeRef="CUST_PHONE",name="CUST_ID", referencedColumnName="ID")]
   [JoinColumn(AttributeRef="CUST_PHONE",name="PHONE_ID", referencedColumnName="ID", Inverse=true)]
)
Lob
Specifies that a persistent property or field should be persisted as a large object to a database-supported large object type.

Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation or the ElementCollection annotation when the element collection value is of basic type. A Lob may be either a binary or character type.

The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.

Examples

CopyC#
Example 1:

[Lob] [Basic(fetch=LAZY)
[Column(name="REPORT")
protected String report;

Example 2:

[Lob] [Basic(fetch=LAZY)]
[Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")]
protected byte[] pic;
LockModeType
Lock modes can be specified by means of passing a LockModeType argument to one of the EntityManager methods that take locks (lock, find, or refresh) or to the SetLockMode(LockModeType) or SetLockMode()()()() method.

Lock modes can be used to specify either optimistic or pessimistic locks.

Optimistic locks are specified using OPTIMISTIC and OPTIMISTIC_FORCE_INCREMENT.

The lock mode type values READ and WRITE are synonyms of OPTIMISTIC and OPTIMISTIC_FORCE_INCREMENT respectively.

The latter are to be preferred for new applications.

The semantics of requesting locks of type LockModeType.OPTIMISTIC and LockModeType.OPTIMISTIC_FORCE_INCREMENT are the following.

If transaction T1 calls for a lock of type LockModeType.OPTIMISTIC on a versioned object, the entity manager must ensure that neither of the following phenomena can occur:

  • P1 (Dirty read): Transaction T1 modifies a row. Another transaction T2 then reads that row and obtains the modified value, before T1 has committed or rolled back. Transaction T2 eventually commits successfully; it does not matter whether T1 commits or rolls back and whether it does so before or after T2 commits.
  • P2 (Non-repeatable read): Transaction T1 reads a row. Another transaction T2 then modifies or deletes that row, before T1 has committed. Both transactions eventually commit successfully.

Lock modes must always prevent the phenomena P1 and P2.

In addition, calling a lock of type LockModeType.OPTIMISTIC_FORCE_INCREMENT on a versioned object, will also force an update (increment) to the entity's version column.

The persistence implementation is not required to support the use of optimistic lock modes on non-versioned objects. When it cannot support a such lock call, it must throw the PersistenceException.

The lock modes PESSIMISTIC_READ()()()(), PESSIMISTIC_WRITE()()()(), and PESSIMISTIC_FORCE_INCREMENT are used to immediately obtain long-term database locks.

The semantics of requesting locks of type LockModeType.PESSIMISTIC_READ, LockModeType.PESSIMISTIC_WRITE, and LockModeType.PESSIMISTIC_FORCE_INCREMENT are the following.

If transaction T1 calls for a lock of type LockModeType.PESSIMISTIC_READ or LockModeType.PESSIMISTIC_WRITE on an object, the entity manager must ensure that neither of the following phenomena can occur:

  • P1 (Dirty read): Transaction T1 modifies a row. Another transaction T2 then reads that row and obtains the modified value, before T1 has committed or rolled back.
  • P2 (Non-repeatable read): Transaction T1 reads a row. Another transaction T2 then modifies or deletes that row, before T1 has committed or rolled back.

A lock with LockModeType.PESSIMISTIC_WRITE can be obtained on an entity instance to force serialization among transactions attempting to update the entity data. A lock with LockModeType.PESSIMISTIC_READ can be used to query data using repeatable-read semantics without the need to reread the data at the end of the transaction to obtain a lock, and without blocking other transactions reading the data. A lock with LockModeType.PESSIMISTIC_WRITE can be used when querying data and there is a high likelihood of deadlock or update failure among concurrent updating transactions.

The persistence implementation must support use of locks of type LockModeType.PESSIMISTIC_READLockModeType.PESSIMISTIC_WRITE on a non-versioned entity as well as on a versioned entity.

When the lock cannot be obtained, and the database locking failure results in transaction-level rollback, the provider must throw the PessimisticLockException and ensure that the JTA transaction or EntityTransaction has been marked for rollback.

When the lock cannot be obtained, and the database locking failure results in only statement-level rollback, the provider must throw the LockTimeoutException (and must not mark the transaction for rollback).

LockTimeoutException
Thrown by the persistence provider when an pessimistic locking conflict occurs that does not result in transaction rollback. This exception may be thrown as part of an API call, at, flush or at commit time. The current transaction, if one is active, will be not be marked for rollback.
ManyToMany
Defines a many-valued association with many-to-many multiplicity.

Every many-to-many association has two sides, the owning side and the non-owning, or inverse, side. The join table is specified on the owning side. If the association is bidirectional, either side may be designated as the owning side. If the relationship is bidirectional, the non-owning side must use the mappedBy element of the ManyToMany annotation to specify the relationship field or property of the owning side.

The join table for the relationship, if not defaulted, is specified on the owning side.

The ManyToMany annotation may be used within an embeddable class contained within an entity class to specify a relationship to a collection of entities. If the relationship is bidirectional and the entity containing the embeddable class is the owner of the relationship, the non-owning side must use the mappedBy element of the ManyToMany annotation to specify the relationship field or property of the embeddable class. The dot (".") notation syntax must be used in the mappedBy element to indicate the relationship attribute within the embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.

Examples

CopyC#
Example 1:

// In Customer class:

[ManyToMany] 
[JoinTable(name="CUST_PHONES")]
public Set<PhoneNumber> getPhones() { return phones; }

// In PhoneNumber class:

[ManyToMany(mappedBy="phones")]
public Set<Customer> getCustomers() { return customers; }

Example 2:

// In Customer class:

[ManyToMany(targetEntity=com.acme.PhoneNumber.class)]
public Set getPhones() { return phones; }

// In PhoneNumber class:

[ManyToMany(targetEntity=com.acme.Customer.class, mappedBy="phones")]
public Set getCustomers() { return customers; }

Example 3:

// In Customer class:

[ManyToMany]
[JoinTable(name="CUST_PHONE")]
        [JoinColumn(AttributeRef="CUST_PHONE",name="CUST_ID", referencedColumnName="ID")]
        [JoinColumn(AttributeRef="CUST_PHONE",name="PHONE_ID", referencedColumnName="ID", Inverse=true)]
    )
public Set<PhoneNumber> getPhones() { return phones; }

// In PhoneNumberClass:

[ManyToMany(mappedBy="phones")]
public Set<Customer> getCustomers() { return customers; }
ManyToOne
Defines a single-valued association to another entity class that has many-to-one multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced.

If the relationship is bidirectional, the non-owning OneToMany entity side must used the mappedBy element to specify the relationship field or property of the entity that is the owner of the relationship.

The ManyToOne annotation may be used within an embeddable class to specify a relationship from the embeddable class to an entity class. If the relationship is bidirectional, the non-owning OneToMany entity side must use the mappedBy element of the OneToMany annotation to specify the relationship field or property of the embeddable field or property on the owning side of the relationship. The dot (".") notation syntax must be used in the mappedBy element to indicate the relationship attribute within the embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.

Examples

CopyC#
Example 1:

[ManyToOne(optional=false)]
[JoinColumn(name="CUST_ID", nullable=false, updatable=false)]
public Customer getCustomer() { return customer; }


Example 2:

[Entity]
   public class Employee {
   [Id] int id;
   [Embedded] JobInfo jobInfo;
   ...
}

[Embeddable]
   public class JobInfo {
   String jobDescription; 
   [ManyToOne] ProgramManager pm; // Bidirectional
}

[Entity]
   public class ProgramManager {
   [Id] int id;
   [OneToMany(mappedBy="jobInfo.pm")]
   Collection<Employee> manages;
}
MapKey
Specifies the map key for associations of type Dictionary<(Of <(<'TKey, TValue>)>)> when the map key is itself the primary key or a persistent field or property of the entity that is the value of the map.

If a persistent field or property other than the primary key is used as a map key then it is expected to have a uniqueness constraint associated with it.

The MapKeyClass annotation is not used when MapKey is specified and vice versa.

Examples

CopyC#
Example 1:

[Entity]
public class Department {
    ...
    [OneToMany(mappedBy="department")]
    [MapKey]  // map key is primary key
    public Dictionary<Integer, Employee> getEmployees() {... }
    ...
}

[Entity]
public class Employee {
    ...
    [Id] Integer getEmpId() { ... }
    [ManyToOne]
    [JoinColumn(name="dept_id")]
    public Department getDepartment() { ... }
    ...
}

Example 2:

[Entity]
    public class Department {
    ...
    [OneToMany(mappedBy="department")]
    [MapKey(name="name")]
    public Dictionary<String, Employee> getEmployees() {... }
    ...
}

[Entity]
    public class Employee {
    [Id] public Integer getEmpId() { ... }
    ...
    [ManyToOne]
    [JoinColumn(name="dept_id")]
    public Department getDepartment() { ... }
    ...
}
MapKeyClass
Specifies the type of the map key for associations of type System.Collections.Generic.Dictionary.

The map key can be a basic type, an embeddable class, or an entity. If the map is specified using generics, the MapKeyClass annotation and associated type need not be specified; otherwise they must be specified.

The MapKeyClass annotation is used in conjunction with ElementCollection or one of the collection-valued relationship annotations (OneToMany or ManyToMany). The MapKey annotation is not used when MapKeyClass is specified and vice versa.

Examples

CopyC#
Example 1:

[Entity]
public class Item {
   [Id] int id;
   ...
   [ElementCollection(targetClass=String.class)]
   [MapKeyClass(String.class)]
   Dictionary images;  // map from image name to image filename
   ...
}

Example 2:

// MapKeyClass and target type of relationship can be defaulted

[Entity]
public class Item {
   [Id] int id;
   ...
   [ElementCollection]
   Dictionary<String, String> images; 
    ...
 }

 Example 3:

 [Entity]
 public class Company {
    [Id] int id;
    ...
    [OneToMany(targetEntity=com.example.VicePresident.class)]
    [MapKeyClass(com.example.Division.class)]
    Dictionary organization;
 }

 Example 4:

 // MapKeyClass and target type of relationship are defaulted

 [Entity]
 public class Company {
    [Id] int id;
    ...
    [OneToMany]
    Dictionary<Division, VicePresident> organization;
 }
MapKeyColumn
Specifies the mapping for the key column of a map whose map key is a basic type.

If the name element is not specified, it defaults to the concatenation of the following: the name of the referencing relationship field or property; "_"; "KEY".

Examples

CopyC#
Example:

[Entity]
public class Item {
   [Id] int id;
   ...
   [ElementCollection]
   [MapKeyColumn(name="IMAGE_NAME")]
   [Column(name="IMAGE_FILENAME")]
   [CollectionTable(name="IMAGE_MAPPING")]
   Dictionary<String, String> images;  // map from image name to filename
   ...
}
MapKeyEnumerated
Specifies the enum type for a map key whose basic type is an enumerated type.

The MapKeyEnumerated annotation can be applied to an element collection or relationship of type System.Collections.Generic.Dictionary, in conjunction with the ElementCollection, OneToMany, or ManyToMany annotation.

If the enumerated type is not specified or the MapKeyEnumerated annotation is not used, the enumerated type is assumed to be ORDINAL.

Examples

CopyC#
Example:

public enum ProjectStatus {COMPLETE, DELAYED, CANCELLED, IN_PROGRESS}

public enum SalaryRate {JUNIOR, SENIOR, MANAGER, EXECUTIVE}

[Entity] public class Employee {
    [ManyToMany] 
    public Projects<ProjectStatus, Project> getProjects() {...}

    [OneToMany]
    [MapKeyEnumerated(STRING)]
    public Dictionary<SalaryRate, Employee> getEmployees() {...}
    ...
}
MapKeyJoinColumn
Specifies a mapping to an entity that is a map key.

The map key join column is in the collection table, join table, or table of the target entity that is used to represent the map. If no MapKeyJoinColumn annotation is specified, a single join column is assumed and the default values apply.

Examples

CopyC#
Example 1:

[Entity]
public class Company {
   [Id] int id;
   ...
   [OneToMany]   // unidirectional
   [JoinTable(name="COMPANY_ORGANIZATION")]
              [JoinColumn(AttributeRef="COMPANY_ORGANIZATION",name="COMPANY")]
              [JoinColumn(AttributeRef="COMPANY_ORGANIZATION",name="VICEPRESIDENT", Inverse=true)]
   [MapKeyJoinColumn(name="DIVISION")]
   Dictionary<Division, VicePresident> organization;
}

Example 2:

[Entity]
public class VideoStore {
   [Id] int id;
   String name;
   Address location;
   ...
   [ElementCollection]
   [CollectionTable(name="INVENTORY")]
              [JoinColumn(AttributeRef="INVENTORY",name="STORE")]
   [Column(name="COPIES_IN_STOCK")]
   [MapKeyJoinColumn(name="MOVIE", referencedColumnName="ID")]
   Dictionary<Movie, Integer> videoInventory;
   ...
 }

 [Entity]
 public class Movie {
    [Id] long id;
    String title;
    ...
 }

 Example 3:

 [Entity]
 public class Student {
    [Id] int studentId;
    ...
    [ManyToMany]  // students and courses are also many-many
    [JoinTable(name="ENROLLMENTS")]
               [JoinColumn(AttributeRef="ENROLLMENTS",name="STUDENT")]
               [JoinColumn(AttributeRef="ENROLLMENTS",name="SEMESTER", Inverse=true)]
    [MapKeyJoinColumn(name="COURSE")]
    Dictionary<Course, Semester>  enrollment;
    ...
 }
MapKeyTemporal
This annotation must be specified for persistent map keys of type DateTime.

It may only be specified for map keys of these types.

The MapKeyTemporal annotation can be applied to an element collection or relationship of type System.Collections.Generic.Dictionary in conjunction with the ElementCollection, OneToMany, or ManyToMany annotation.

Examples

CopyC#
Example:

[OneToMany]
[MapKeyTemporal(DATE)]
protected System.Collections.Generic.Dictionary<System.DateTime, Employee> employees;
MappedSuperclass
Designates a class whose mapping information is applied to the entities that inherit from it.

A mapped superclass has no separate table defined for it.

A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself.

When applied to the subclasses the inherited mappings will apply in the context of the subclass tables. Mapping information may be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations or corresponding XML elements.

Examples

CopyC#
Example: Concrete class as a mapped superclass

[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) { ... }
}

// Default table is FTEMPLOYEE table
[Entity]
public class FTEmployee extends Employee {

    // Inherited empId field mapped to FTEMPLOYEE.EMPID
    // Inherited version field mapped to FTEMPLOYEE.VERSION
    // Inherited address field mapped to FTEMPLOYEE.ADDR fk

    // Defaults to FTEMPLOYEE.SALARY
    protected Integer salary;

    public FTEmployee() {}

    public Integer getSalary() { ... }

    public void setSalary(Integer salary) { ... }
}

[Entity] [Table(name="PT_EMP")]
[AssociationOverride(Name="address")]
[JoinColumn(AttributeRef="address",Name="ADDR_ID")]
public class PartTimeEmployee extends Employee {

    // Inherited empId field mapped to PT_EMP.EMPID
    // Inherited version field mapped to PT_EMP.VERSION
    // address field mapping overridden to PT_EMP.ADDR_ID fk
    [Column(name="WAGE")]
    protected Float hourlyWage;

    public PartTimeEmployee() {}

    public Float getHourlyWage() { ... }
    public void setHourlyWage(Float wage) { ... }
}
MapsId
Designates a ManyToOne or OneToOne relationship attribute that provides the mapping for an EmbeddedId primary key, an attribute within an EmbeddedId primary key, or a simple primary key of the parent entity.

The value element specifies the attribute within a composite key to which the relationship attribute corresponds. If the entity's primary key is of the same type as the primary key of the entity referenced by the relationship, the value attribute is not specified.

Examples

CopyC#
Example:

// parent entity has simple primary key

[Entity]
public class Employee {
   [Id] long empId;
   String name;
   ...
} 

// dependent entity uses EmbeddedId for composite key

[Embeddable]
public class DependentId {
   String name;
   long empid;   // corresponds to primary key type of Employee
}

[Entity]
public class Dependent {
   [EmbeddedId] DependentId id;
    ...
   [MapsId("empid")]  //  maps the empid attribute of embedded id
   [ManyToOne] Employee emp;
}
NamedNativeQuery
Specifies a named native SQL query.

Query names are scoped to the persistence unit.

The NamedNativeQuery annotation can be applied to an entity or mapped superclass.

NamedQuery
Specifies a static, named query in the Java Persistence query language. Query names are scoped to the persistence unit.

The NamedQuery annotation can be applied to an entity or mapped superclass.

The following is an example of the definition of a named query in the Java Persistence query language:

Examples

CopyC#
[NamedQuery(
        name="findAllCustomersWithName",
        query="SELECT c FROM Customer c WHERE c.name LIKE :custName"]
)
The following is an example of the use of a named query:

Examples

CopyC#
[PersistenceContext]
public EntityManager em;
...
customers = em.createNamedQuery("findAllCustomersWithName")
        .setParameter("custName", "Smith")
        .getResultList();
NonUniqueResultException
Thrown by the persistence provider when GetSingleResult()()()()or GetSingleResult()()()() is executed on a query and there is more than one result from the query.

This exception will not cause the current transaction, if one is active, to be marked for rollback.

NoResultException
Thrown by the persistence provider when M:Query.getSingleResult or M:TypedQuery`1.getSingleResult is executed on a query and there is no result to return.

This exception will not cause the current transaction, if one is active, to be marked for rollback.

OneToMany
Defines a many-valued association with one-to-many multiplicity.

If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified. If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the owner of the relationship.

The OneToMany annotation may be used within an embeddable class contained within an entity class to specify a relationship to a collection of entities. If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the owner of the relationship.

When the collection is a System.Collections.Generic.Dictionary, the cascade element and the orphanRemoval element apply to the map value.

Examples

CopyC#
Example 1: One-to-Many association using generics

// In Customer class:

[OneToMany](cascade=ALL, mappedBy="cUSTOMER")]
public Set<Order> getOrders() { return orders; }

In Order class:

[ManyToOne]
[JoinColumn(name="CUST_ID", nullable=false)]
public Customer getCustomer() { return customer; }


Example 2: One-to-Many association without using generics

// In Customer class:

[OneToMany(targetEntity=com.acme.Order.class, cascade=ALL,
            mappedBy="cUSTOMER")]
public Set getOrders() { return orders; }

// In Order class:

[ManyToOne]
[JoinColumn(name="CUST_ID", nullable=false)]
public Customer getCustomer() { return customer; }


Example 3: Unidirectional One-to-Many association using a foreign key mapping

// In Customer class:

[OneToMany(orphanRemoval=true)]
[JoinColumn(name="CUST_ID")] // join column is in table for Order
public Set<Order> getOrders() {return orders;}
OneToOne
Defines a single-valued association to another entity that has one-to-one multiplicity.

It is not normally necessary to specify the associated target entity explicitly since it can usually be inferred from the type of the object being referenced.

If the relationship is bidirectional, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the owning side.

The OneToOne annotation may be used within an embeddable class to specify a relationship from the embeddable class to an entity class.

If the relationship is bidirectional and the entity containing the embeddable class is on the owning side of the relationship, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the embeddable class.

The dot (".") notation syntax must be used in the mappedBy element to indicate the relationship attribute within the embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.

Examples

CopyC#
Example 1: One-to-one association that maps a foreign key column

// On Customer class:

[OneToOne(optional=false)]
[JoinColumn(
    name="CUSTREC_ID", unique=true, nullable=false, updatable=false)]
public CustomerRecord getCustomerRecord() { return customerRecord; }

// On CustomerRecord class:

[OneToOne(optional=false, mappedBy="customerRecord")]
public Customer getCustomer() { return customer; }


Example 2: One-to-one association that assumes both the source and target share the same primary key values. 

// On Employee class:

[Entity]
public class Employee {
    [Id] Integer id;

    [OneToOne]MapsId
    EmployeeInfo info;
    ...
}

// On EmployeeInfo class:

[Entity]
public class EmployeeInfo {
    [Id] Integer id;
    ...
}


Example 3: One-to-one association from an embeddable class to another entity.

[Entity]
public class Employee {
   [Id] int id;
   [Embedded] LocationDetails location;
   ...
}

[Embeddable]
public class LocationDetails {
   int officeNumber;
   ]OneToOne ]ParkingSpot parkingSpot;
   ...
}

[Entity]
public class ParkingSpot {
   [Id] int id;
   String garage;
   [OneToOne(mappedBy="location.parkingSpot")] Employee assignedTo;
    ... 
}
OptimisticLockException
Thrown by the persistence provider when an optimistic locking conflict occurs. This exception may be thrown as part of an API call, a flush or at commit time. The current transaction, if one is active, will be marked for rollback.
OrderBy
Specifies the ordering of the elements of a collection valued association or element collection at the point when the association or collection is retrieved.

The syntax of the value ordering element is an orderby_list, as follows:

Examples

CopyC#
orderby_list::= orderby_item [,orderby_item]*
orderby_item::= [property_or_field_name] [ASC | DESC]

If ASC or DESC is not specified, ASC (ascending order) is assumed.

If the ordering element is not specified for an entity association, ordering by the primary key of the associated entity is assumed.

The property or field name must correspond to that of a persistent property or field of the associated class or embedded class within it.

The properties or fields used in the ordering must correspond to columns for which comparison operators are supported.

The dot (".") notation is used to refer to an attribute within an embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.

The OrderBy annotation may be applied to an element collection.

When OrderBy is applied to an element collection of basic type, the ordering will be by value of the basic objects and the property or field name is not used.

When specifying an ordering over an element collection of embeddable type, the dot notation must be used to specify the attribute or attributes that determine the ordering.

The OrderBy annotation is not used when an order column is specified.

Examples

CopyC#
Example 1:

[Entity] 
public class Course {
   ...
   [ManyToMany]
   [OrderBy("lastname ASC")]
   public List<Student> getStudents() {...};
   ...
}

Example 2:

[Entity] 
public class Student {
   ...
   [ManyToMany(mappedBy="students")]
   // ordering by primary key is assumed
   public List<Course> getCourses() {...};
   ...
}

Example 3: 

[Entity] 
public class Person {
     ...
   [ElementCollection]
   [OrderBy("zipcode.zip, zipcode.plusFour")]
   public Set<Address> getResidences() {...};
   ...
}

[Embeddable] 
public class Address {
   protected String street;
   protected String city;
   protected String state;
   [Embedded] protected Zipcode zipcode;
}

[Embeddable] 
public class Zipcode {
   protected String zip;
   protected String plusFour;
}
OrderColumn
Specifies a column that is used to maintain the persistent order of a list.

The persistence provider is responsible for maintaining the order upon retrieval and in the database.

The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list.

The OrderColumn annotation is specified on a OneToMany or ManyToMany relationship or on an element collection.

The OrderColumn annotation is specified on the side of the relationship that references the collection that is to be ordered.

The order column is not visible as part of the state of the entity or embeddable class.

The OrderBy annotation should be used for ordering that is visible as persistent state and maintained by the application.

The OrderBy annotation is not used when OrderColumn is specified.

The order column must be of integral type.

The persistence provider maintains a contiguous (non-sparse) ordering of the values of the order column when updating the association or element collection.

The order column value for the first element is 0.

Examples

CopyC#
Example:

[Entity]
public class CreditCard {

   [Id] long ccNumber;

   [OneToMany]  // unidirectional
   [OrderColumn]
   List<CardTransaction> transactionHistory;
   ...
}
Parameter<(Of <(<'T>)>)>
Type for query parameter objects. the type of the parameter
Persistence
Bootstrap class that is used to obtain an EntityManagerFactory in .NET environments.

The Persistence class is also used to obtain a PersistenceUtil instance.

PersistenceContext
Expresses a dependency on a container-managed EntityManager and its associated persistence context.
PersistenceContextType
Specifies whether a transaction-scoped or extended persistence context is to be used in PersistenceContext. If not specified, a transaction-scoped persistence context is used.
PersistenceException
Thrown by the persistence provider when a problem occurs.

All instances of PersistenceException except for instances of NoResultException, NonUniqueResultException, LockTimeoutException, and QueryTimeoutException will cause the current transaction, if one is active, to be marked for rollback.

PersistenceProperty
Describes a single container or persistence provider property.

Used in PersistenceContext.

Vendor specific properties may be included in the set of properties, and are passed to the persistence provider by the container when the entity manager is created.

Properties that are not recognized by a vendor will be ignored.

PersistenceUnit
Expresses a dependency on an EntityManagerFactory and its associated persistence unit.
PersistenceUnitUtil
Utility interface between the application and the persistence provider managing the persistence unit.

The methods of this interface should only be invoked on entity instances obtained from or managed by entity managers for this persistence unit or on new entity instances.

PersistenceUtil
Utility interface between the application and the persistence provider(s).

The PersistenceUtil interface instance obtained from the Persistence class is used to determine the load state of an entity or entity attribute regardless of which persistence provider in the environment created the entity.

PessimisticLockException
Thrown by the persistence provider when an pessimistic locking conflict occurs.

This exception may be thrown as part of an API call, a flush or at commit time. The current transaction, if one is active, will be marked for rollback.

PessimisticLockScope
Defines the values of the NPersistence.lock.scope property for pessimistic locking.

This property may be passed as an argument to the methods of the EntityManager, Query, and TypedQuery interfaces that allow lock modes to be specified or used with the NamedQuery annotation.

PostLoad
Is used to specify callback methods for the corresponding lifecycle event.

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

PostPersist
Is used to specify callback methods for the corresponding lifecycle event.

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

PostRemove
Is used to specify callback methods for the corresponding lifecycle event.

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

PostUpdate
Is used to specify callback methods for the corresponding lifecycle event.

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

PrePersist
Is used to specify callback methods for the corresponding lifecycle event.

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

PreRemove
Is used to specify callback methods for the corresponding lifecycle event.

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

PreUpdate
Is used to specify callback methods for the corresponding lifecycle event.

This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class.

PrimaryKeyJoinColumn
Specifies a primary key column that is used as a foreign key to join to another table.

It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.

If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.

Examples

CopyC#
Example: Customer and ValuedCustomer subclass

[Entity]
[Table(name="CUST")]
[Inheritance(strategy=JOINED)]
[DiscriminatorValue("CUST")]
public class Customer { ... }

[Entity]
[Table(name="VCUST")]
[DiscriminatorValue("VCUST")]
[PrimaryKeyJoinColumn(name="CUST_ID")]
public class ValuedCustomer extends Customer { ... }
Query
Interface used to control query execution.
QueryHint
Used to supply a query property or hint to the NamedQuery or NamedNativeQuery annotation. Vendor-specific hints that are not recognized by a provider are ignored.
QueryTimeoutException
Thrown by the persistence provider when a query times out and only the statement is rolled back.

The current transaction, if one is active, will be not be marked for rollback.

RollbackException
Thrown by the persistence provider when Commit()()()() fails.
SecondaryTable
Specifies a secondary table for the annotated entity class.

Specifying one or more secondary tables indicates that the data for the entity class is stored across multiple tables.

If no SecondaryTable annotation is specified, it is assumed that all persistent fields or properties of the entity are mapped to the primary table.

If no primary key join columns are specified, the join columns are assumed to reference the primary key columns of the primary table, and have the same names and types as the referenced primary key columns of the primary table.

Examples

CopyC#
Example 1: Single secondary table with a single primary key column.

[Entity]
[Table(name="CUSTOMER")]
[SecondaryTable(name="CUST_DETAIL")]
    [PrimaryKeyJoinColumn(name="CUST_ID")]
public class Customer { ... } 


Example 2: Single secondary table with multiple primary key columns.

[Entity]
[Table(name="CUSTOMER")]
[SecondaryTable(name="CUST_DETAIL")]
        [PrimaryKeyJoinColumn(name="CUST_ID")]
        [PrimaryKeyJoinColumn(name="CUST_TYPE")]
public class Customer { ... }
SequenceGenerator
Defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation.

A sequence generator may be specified on the entity class or on the primary key field or property.

The scope of the generator name is global to the persistence unit (across all generator types).

Examples

CopyC#
Example:

[SequenceGenerator(name="EMP_SEQ", allocationSize=25)]
SharedCacheMode
Specifies how the provider must use a second-level cache for the persistence unit.

Corresponds to the value of the persistence.xmlshared-cache-mode element, and returned as the result of GetSharedCacheMode()()()().

SqlResultSetMapping
Specifies the mapping of the result of a native SQL query.

Examples

CopyC#
 Example:

 Query q = em.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");

[SqlResultSetMapping(name="OrderResults")]
        [EntityResult(ResultSetRef = "OrderResults", Name="OrderEntityResult", EntityClass=com.acme.Order.class)]
            [FieldResult(EntityRef = "OrderEntityResult", Name="id", Column="ordeR_ID")]
            [FieldResult(EntityRef = "OrderEntityResult", Name="quantity", Column="order_quantity")]
            [FieldResult(EntityRef = "OrderEntityResult", Name="item", Column="order_item")]
        [ColumnResult(ResultSetRef = "OrderResults", Name="item_name", Type = "String")]
Table
Specifies the primary table for the annotated entity.

Additional tables may be specified using SecondaryTable annotation.

If no Table annotation is specified for an entity class, the default values apply.

Examples

CopyC#
Example:

[Entity]
[Table(name="CUST", schema="RECORDS")]
public class Customer { ... }
TableGenerator
Defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation.

A table generator may be specified on the entity class or on the primary key field or property.

The scope of the generator name is global to the persistence unit (across all generator types).

Examples

CopyC#
Example 1:

[Entity] public class Employee {
    ...
    [TableGenerator(
        name="empGen", 
        table="ID_GEN", 
        pkColumnName="GEN_KEY", 
        valueColumnName="GEN_VALUE", 
        pkColumnValue="EMP_ID", 
        allocationSize=1)]
    [Id]
    [GeneratedValue(strategy=TABLE, generator="empGen")]
    int id;
    ...
}

Example 2:

[Entity] public class Address {
    ...
    [TableGenerator(
        name="addressGen", 
        table="ID_GEN", 
        pkColumnName="GEN_KEY", 
        valueColumnName="GEN_VALUE", 
        pkColumnValue="ADDR_ID")]]
    [Id]
    [GeneratedValue(strategy=TABLE, generator="addressGen")]
    int id;
    ...
}
Temporal
This annotation must be specified for persistent fields or properties of type System.DateTime and System.DateTime.

It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

Examples

CopyC#
Example:

[Temporal(DATE)]
protected System.DateTime endDate;
TemporalType
Type used to indicate a specific mapping of System.DateTime or System.DateTime.
TransactionRequiredException
Thrown by the persistence provider when a transaction is required but is not active.
Transient
Specifies that the property or field is not persistent. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class.

Examples

CopyC#
Example:

[Entity]
public class Employee {
    [Id] int id;
    [Transient] User currentUser;
    ...
}
Tuple
Interface for extracting the elements of a query result tuple.
TupleElement<(Of <(<'X>)>)>
The TupleElement interface defines an element that is returned in a query result tuple.

the type of the element

TypedQuery<(Of <(<'X>)>)>
Interface used to control the execution of typed queries.

query result type

UniqueConstraint
Specifies that a unique constraint is to be included in the generated DDL for a primary or secondary table.

Examples

CopyC#
Example:
[Entity]
[Table(Name="EMPLOYEE") ]
     [UniqueConstraint(TableRef = "EMPLOYEE", columnNames={"EMP_ID", "EMP_NAME"})]
)
public class Employee { ... }

Examples

CopyC#
Example2:

[JoinTable(name="CUST_PHONE")]
   [JoinColumn(AttributeRef="CUST_PHONE",name="CUST_ID", referencedColumnName="ID")]
   [JoinColumn(AttributeRef="CUST_PHONE",name="PHONE_ID", referencedColumnName="ID", Inverse=true)]
   [UniqueConstraint(TableRef = "CUST_PHONE", ColumnNames = new String[] { "CUST_ID", "PHONE_ID" })]
)
ValidationMode
The validation mode to be used by the provider for the persistence unit.
Version
Specifies the version field or property of an entity class that serves as its optimistic lock value.

The version is used to ensure integrity when performing the merge operation and for optimistic concurrency control.

Only a single Version property or field should be used per class; applications that use more than one Version property or field will not be portable.

The Version property should be mapped to the primary table for the entity class; applications that map the Version property to a table other than the primary table will not be portable.

The following types are supported for version properties:

int,

Integer,

short,

Short,

long,

Long,

System.Data.DbType.Timestamp.

Examples

CopyC#
Example:

[Version]
[Column(name="OPTLOCK")]
protected int getVersionNum() { return versionNum; }