Note the auto apply flag set to true. This flag indicates that this converter should be applied to every attribute within the persistence unit of type Long. Without this setting, converters must be explicitly set with a Convert specification. E.g.

Note the auto apply flag set to true. This flag indicates that this converter should be applied to every attribute within the persistence unit of type Long. Without this setting, converters must be explicitly set with a Convert specification. E.g.

−

Annotation example:

+

===A Basic annotation example===

@Convert(converter = LongToStringConverter.class)

@Convert(converter = LongToStringConverter.class)

protected Long salary;

protected Long salary;

−

XML example:

+

===A Basic xml example===

<basic name="salary">

<basic name="salary">

Line 414:

Line 438:

<convert disable-conversion="true"/>

<convert disable-conversion="true"/>

</basic>

</basic>

+

+

===More complex usage===

+

Converters can be applied at several levels. The simplest, described above, allows a single converter on a single attribute. Multiple converters can be applied through the use of Converts metadata which is of value for embedded attributes and when converters are needed on a mapped superclass on a per entity basis.

** specifies whether the persistence provider is to create the database schema(s) in addition to creating database objects such as tables, sequences, constraints, etc.

+

* '''javax.persistence.schema-generation.scripts.create-target'''

+

** specifies a java.IO.Writer configured for use by the persistence provider for output of the DDL script or a string specifying the file URL for the DDL script.

+

* '''javax.persistence.schema-generation.scripts.drop-target'''

+

** specifies a java.IO.Writer configured for use by the persistence provider for output of the DDL script or a string specifying the file URL for the DDL script.

+

* '''javax.persistence.database-product-name'''

+

** specified if scripts are to be generated by the persistence provider and a connection to the target database is not supplied.

+

** The value of this property should be the value returned for the target database by the JDBC DatabaseMetaData method getDatabaseProductName.

+

* '''javax.persistence.database-major-version'''

+

** specified if sufficient database version information is not included from the JDBC DatabaseMetaData method getDatabaseProductName.

+

** This value of this property should contain the value returned by the JDBC getDatabaseMajor-Version method.

+

* '''javax.persistence.database-minor-version'''

+

** specified if sufficient database version information is not included from the JDBC DatabaseMetaData method getDatabaseProductName.

+

** This value of this property should contain the value returned by the JDBC getDatabaseMinor-Version method.

+

* '''javax.persistence.schema-generation.create-script-source'''

+

** specifies a java.IO.Reader configured for reading of the DDL script or a string designating a file URL for the DDL script.

+

* '''javax.persistence.schema-generation.drop-script-source'''

+

** specifies a java.IO.Reader configured for reading of the DDL script or a string designating a file URL for the DDL script.

+

* '''javax.persistence.schema-generation.connection'''

+

** specifies the JDBC connection to be used for schema generation. This is intended for use in Java EE environments, where the platform provider may want to control the database privileges that are available to the persistence provider.

+

* '''javax.persistence.sql-load-script-source'''

+

** specifies a java.IO.Reader configured for reading of the SQL load script for database initialization or a string designating a file URL for the script.

+

+

===Usage examples===

+

Any combination of those properties can be passed through a Persistence.generateSchema() call, through a Persistence.createEntityManagerFactory() call or directly in the persistence unit definition in the persistence.xml.

When working with JTA EntityManagers in previous versions of the Java Persistence API the entity manager and persistence context was automatically synchronized with the transaction and any changes to entities managed by the persistence context would be written to the database when the transaction was committed. With Java Persistence API 2.1 a new synchronization type ''@PersistenceContext(synchronization=SynchronizationType.UNSYNCHRONIZED)'' has been added to the persistence context to allow it to propagate along with the active JTA transaction but not be synchronized to it. For any unsynchronized persistence context the changes within the managed entities will not be written to the database unless the persistence context has been explicitly joined to the transaction by the application through the ''EntityManager.joinTransaction()'' call. This can be useful when an application may need access to transactional resources but does not wish to write to the database until some later point perhaps multiple transactions have completed.

EclipseLink JPA 2.1

This page contains a summary of the major features supported in EclipseLink that implements the JPA 2.1 (JSR 338) specification requirements. The features and examples on this page do not represent a complete list. For more information, please see: the JSR 338 page.

Bulk Update

Until JPA 2.1, performing deletes or updates was not available using the Criteria API. Through the
addition of CriteriaUpdate/CriteriaDelete classes, support for bulkupdate/delete queries has now been added.

Update Example

The following example will update the salary and status, of all Employees who make less than 10000$, and give them a raise.

The following Java Persistence query language delete statement is equivalent.

DELETE FROM PhoneNumber p
WHERE p.status = 'out_of_service'

Stored Procedures

JPA specification 2.1 has introduced support for executing Stored Procedure calls. This includes a new
StoredProcedureQuery API and Named Stored Procedure Queries (pre-existing portions of code on the database).

All the stored procedure examples below assume stored procedures already exist on the DB. Stored procedure creation is performed differently on different Databases. All the following example Stored procedure creation is using MySQL syntax (unless otherwise specified).

Alternatively, users can call spq.execute() directly (which is what getResultList() will call behind the scenes). The execute method will return a boolean indicating true if a result set is returned and false otherwise.

boolean result = spq.execute();
if (result == true) {
customers = spq.getResultList();
} else {
// Handle the false for no result set returned, e.g.
throw new RuntimeException("No result set(s) returned from the stored procedure");
}

boolean resultSet = query.setParameter("address_id_v", "1").execute();
if (resultSet) {
// Result sets must be processed first through getResultList() calls.
}
// Once the result sets and update counts have been processed, output parameters are available for processing.
String city = (String) query.getOutputParameterValue("city_v");

Ref cursor Example

Stored procedure definition on Oracle:

CREATE PROCEDURE Read_Using_Sys_Cursor (f_name_v VARCHAR2, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR SELECT EMP_ID, F_NAME FROM EMPLOYEE WHERE F_NAME = f_name_v ORDER BY EMP_ID;
END;

This is one example (of many) on how to configure such a query. Queries and result set mappings can be defined solely in annotations or xml or a mix of both. All the metadata can be defined on a single class or split up across many.

JPQL function

The SQL spec and many databases have SQL functions that are not covered by the JPA specification. With the latest JPA
specification the ability to call generic SQL functions was added to the JPQL syntax. The function keyword may be used to invoke
predefined functions or used defined functions.

CDI Entity Listeners

Entity Listeners now support the Contexts and Dependency Injection API (CDI) when used inside a Java EE container. This support allows entity listeners to use CDI to inject objects and also provides support for @PostConstruct and @PreDestroy method calls.

CDI Example

The following example shows how a SessionBean can be injected into an EntityListener

Converters

Provides control over the conversion from an attribute type and value to the corresponding database type and value

Users must first define a class to the a converter. To do so, the class must implement the javax.persistence.AttributeConverter interface.

public interface AttributeConverter<X,Y> {
/**
* Converts the value stored in the entity attribute into the
* data representation to be stored in the database.
*
* @param attribute the entity attribute value to be converted
* @return the converted data to be stored in the database
* column
*/
public Y convertToDatabaseColumn (X attribute);
/**
* Converts the data stored in the database column into the
* value to be stored in the entity attribute.
* Note that it is the responsibility of the converter writer to
* specify the correct dbData type for the corresponding
* column for use by the JDBC driver: i.e., persistence providers are
* not expected to do such type conversion.
*
* @param dbData the data from the database column to be
* converted
* @return the converted value to be stored in the entity
* attribute
*/
public X convertToEntityAttribute (Y dbData);
}

The class must be then marked as a Converter class through an annotation or xml declaration.

A Converter xml example

Note the auto apply flag set to true. This flag indicates that this converter should be applied to every attribute within the persistence unit of type Long. Without this setting, converters must be explicitly set with a Convert specification. E.g.

A Basic annotation example

A Basic xml example

Alternatively, an auto apply setting can also be turned using the Convert metadata for individuals attributes that wish to not use the Converter.

Annotation example:

@Convert(disableConversion = true)
protected Long salary;

XML example:

<basic name="salary">
<convert disable-conversion="true"/>
</basic>

More complex usage

Converters can be applied at several levels. The simplest, described above, allows a single converter on a single attribute. Multiple converters can be applied through the use of Converts metadata which is of value for embedded attributes and when converters are needed on a mapped superclass on a per entity basis.

specifies whether the persistence provider is to create the database schema(s) in addition to creating database objects such as tables, sequences, constraints, etc.

javax.persistence.schema-generation.scripts.create-target

specifies a java.IO.Writer configured for use by the persistence provider for output of the DDL script or a string specifying the file URL for the DDL script.

javax.persistence.schema-generation.scripts.drop-target

specifies a java.IO.Writer configured for use by the persistence provider for output of the DDL script or a string specifying the file URL for the DDL script.

javax.persistence.database-product-name

specified if scripts are to be generated by the persistence provider and a connection to the target database is not supplied.

The value of this property should be the value returned for the target database by the JDBC DatabaseMetaData method getDatabaseProductName.

javax.persistence.database-major-version

specified if sufficient database version information is not included from the JDBC DatabaseMetaData method getDatabaseProductName.

This value of this property should contain the value returned by the JDBC getDatabaseMajor-Version method.

javax.persistence.database-minor-version

specified if sufficient database version information is not included from the JDBC DatabaseMetaData method getDatabaseProductName.

This value of this property should contain the value returned by the JDBC getDatabaseMinor-Version method.

javax.persistence.schema-generation.create-script-source

specifies a java.IO.Reader configured for reading of the DDL script or a string designating a file URL for the DDL script.

javax.persistence.schema-generation.drop-script-source

specifies a java.IO.Reader configured for reading of the DDL script or a string designating a file URL for the DDL script.

javax.persistence.schema-generation.connection

specifies the JDBC connection to be used for schema generation. This is intended for use in Java EE environments, where the platform provider may want to control the database privileges that are available to the persistence provider.

javax.persistence.sql-load-script-source

specifies a java.IO.Reader configured for reading of the SQL load script for database initialization or a string designating a file URL for the script.

Usage examples

Any combination of those properties can be passed through a Persistence.generateSchema() call, through a Persistence.createEntityManagerFactory() call or directly in the persistence unit definition in the persistence.xml.

Add Named Query

Dynamic queries can now be added to the Peristence Unit through the EntityManagerFactory.addNamedQuery(String name, Query query) as named queries and can be retrieved through EntityManager.createNamedQuery(...). Configuration elements of the query like query hints, flush mode, lock mode, etc. are retained in the named query as configured at the point of adding the named query but parameter values are not retained. If a named query of the same name is already registered it will be replaced by the newly added query.
Once retrieved any configuration changes to a named query will not be reflected in subsequent retrievals unless the named query is updated through addNamedQuery(...)

Entity Graphs

Entity graphs are a means to specify the structure of a graph of entities using entity model metadata. This entity graph consists of representations of attributes and in the case of multi-node entity graphs additional entity graphs to represent the related entities. An entity graph can be specified through annotations:

Once constructed or retrieved the entity graphs can then be used as templates for certain EntityManager operations like load and fetch. For instance applying the entity graph as a fetch graph through a query hint will cause EclipseLink to only load those attributes present in the entity graph and unlisted attributes would become fetchType=LAZY.

The entity graph can also be used to force and entity subgraph to be loaded at query time with the query hint "javax.persistence.loadgraph" . When a load graph is applied all listed attributes will be loaded by the query and any unlisted attributes will be loaded based on their mapping fetchType settings.

Unsynchronized Persistence Contexts

When working with JTA EntityManagers in previous versions of the Java Persistence API the entity manager and persistence context was automatically synchronized with the transaction and any changes to entities managed by the persistence context would be written to the database when the transaction was committed. With Java Persistence API 2.1 a new synchronization type @PersistenceContext(synchronization=SynchronizationType.UNSYNCHRONIZED) has been added to the persistence context to allow it to propagate along with the active JTA transaction but not be synchronized to it. For any unsynchronized persistence context the changes within the managed entities will not be written to the database unless the persistence context has been explicitly joined to the transaction by the application through the EntityManager.joinTransaction() call. This can be useful when an application may need access to transactional resources but does not wish to write to the database until some later point perhaps multiple transactions have completed.