DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. EclipseLink JPA
refcard cover
Refcard #144

EclipseLink JPA

An Advanced ORM Persistence Framework

Build your JPA knowledge with an advanced look at the EclipseLink Framework. This Refcard focuses on EclipseLinks object to relational mapping (ORM) functionality along with its extensions of JPA 2.0.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Gordon Yorke
Software Developer, Oracle
Table of Contents
► What is EclipseLink? ► EclipseLink JPA ► Caching ► Query Extensions ► Mappings ► Connections ► Other Popular Extensions ► Resources
Section 1

What is EclipseLink?

By Gordon Yorke

Focused on standards, EclipseLink delivers a comprehensive open source Java persistence solution with implementations of Java Persistence API (JPA), Java Architecture for XML Binding (JAXB), and Service Data Objects (SDO). EclipseLink also offers many advanced features to aid users with their applications.

Section 2

EclipseLink JPA

The focus of this Refcard is EclipseLink’s object to relational mapping functionality and its extensions of the Java Persistence API specification. This card assumes you are already familiar with the Java Persistence API.

EclipseLink has been JPA 1.0 (JSR 220) certified and is the reference implementation for JPA 2.0 (JSR 317). An offshoot of the code base called TopLink Essentials was the reference implementation for JPA 1.0 (JSR 220).

How Do I Get It?

Jars and Bundles

EclipseLink is available in two forms: a single eclipselink.jar file that contains all that is needed to use any of the EclipseLink functionality or OSGi bundles for each of the EclipseLink component modules.

Download these from: http://www.eclipse.org/eclipselink/downloads

Maven

There are many versions and component module bundles available in the EclipseLink maven repository. Each component module has its own artifactId. For a comprehensive view of what is available, see http://wiki.eclipse.org/. If you just want the eclipselink.jar file, here are example pom.xml entries:

​x
1
​
2
<dependencies>
3
  <dependency>
4
<groupId>org.eclipse.persistence</groupId>
5
<artifactId>eclipselink</artifactId>
6
<version>2.2.0</version>
7
<scope>compile</scope>
8
...
9
  </dependency>
10
</dependencies>
11
​
12
<repositories>
13
  <repository>
14
   <id>EclipseLink Repo</id>
15
 <url>http://download.eclipse.org/rt/eclipselink/maven.repo</url>
16
  </repository>
17
...
18
</repositories>
19
​

How to Use It

Java EE and SE

The eclipselink.jar file or combinations of the OSGi bundles can be treated like normal JAR files and placed in the class path of your application or server lib.

In a Java EE compliant server, the eclipselink.jar can be bundled in the WAR or EAR file if not already present within the server library.

It is a good practice to place the javax.persistence jar file with the EclipseLink jar.

OSGi Environments

To run in a true OSGi environment, the recommended approach is to download the bundles from the Gemini JPA project. These bundles include implementations of the OSGi specification that support dynamic access to the Persistence Providers.

Download the bundles from http://www.eclipse.org/gemini/jpa/. Within the download, there is a GettingStarted.txt file that will help you work through the details of deploying in an OSGi environment.

Weaving

When deployed within a Java EE server or other SPI supporting servers, EclipseLink has an opportunity to enhance the java classes automatically. This enhancement step, referred to as “weaving”, allows EclipseLink to provide many optimizations and improve functionality. For instance, EclipseLink can offer lazy OneToOne and ManyToOne relationships, on-the-fly change tracking and dynamic fetch groups with weaving.

If you are deploying EclipseLink in an environment where weaving is not automatic (as is the case in Java SE), there are two options for enabling weaving.

The first and easiest way to enable weaving is to use the -javaagent: Virtual Machine argument providing the location of the eclipselink.jar. With the java agent specified, EclipseLink will automatically handle weaving of the Entities.

3
1
​
2
java –javaagent:../lib/eclipselink.jar …
3
​

The second way to enable weaving is to use the “static weaver”. The static weaver is a compile time step that is useful in situations where runtime weaving is not available or not desirable.

4
1
​
2
java org.eclipse.persistence.tools.weaving.jpa.StaticWeave -classpath c:\my-pujar.
3
jar;<other classpath entries> c:\my-pu-jar.jar c:\my-pu-jar-woven.jar
4
​

The Static Weave tool can run against directories as well as jars. If the persistence.xml is in a non-standard location, the persistence infoo argument can be used to point to the persistence.xml file.

When using static weaving, the Persistence Unit property “eclipselink.weaving” should be set with a value of “static”.

Details on other advanced weaving properties can be found here: http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)

Canonical Metamodel

With Java Persistence API 2.0 came the Criteria API for dynamically defining queries. One of the components of the Criteria API is the Canonical Metamodel. The Canonical Metamodel is a collection of generated classes whose static attributes allow a query writer to reference strongly typed Entity metadata for the definition of strongly typed Criteria queries.

3
1
​
2
criteriaQuery.from(Employee.class).join(Employee_.phoneNumbers);
3
​

Many IDEs, including Eclipse through the Dali project, can generate a Canonical Metamodel for you. However, if this is unavailable, EclipseLink can easily generate these classes during compile time by simply adding the eclipselink-jpa-modelgen_<version>.jar to the javacclass pathh. For advanced or non-standard usage, the Canonical Metamodel generator has numerous options that are detailed in the EclipseLink user guide.

Feature Extensions

Many of EclipseLink’s extensions have been exposed through annotations and custom xml elements as well as through custom APIs. The classes org.eclipse.persistence.jpa.JpaQuery and org.eclipse.persistence.jpa.JpaEntityManager provide many of the API extensions. org.eclipse.persistence.jpa.JpaHelper has many static methods to help unwrap the Java Persistence API artifacts.

eclipselink-orm.xml

The eclipselink-orm.xml contains the Eclipselink annotation extensions mentioned in this document in xml format. This file is placed on the application class path at the same locations as the specification defined orm.xml. All Java Persistence API xml and EclipseLink extensions can be defined in this single file or a combination of orm.xml and eclipselink-orm.xml and annotations.

Hot Tip

All EclipseLink annotations have corresponding elements in the eclipselink-orm.xml file.
Section 3

Caching

Caching provides very efficient data retrieval and can greatly improve your application’s performance. Caching is a “first class” feature in EclipseLink and is an integral part of the product. By default, all Entities are cached as fully realized POJOs.

Hot Tip

When updating a bi-directional relationship (OneToMany/ManyToOne or ManyToMany), ensure both Entities are updated. Setting only the “owning” ManyToOne or ManyToMany mapping will result in Entities missing from the OneToMany collection when retrieved from the cache.

Configuring the Cache

Using the Java Persistence APIs, you can configure the cache at the Entity level with the @Cacheable annotation and corresponding XML. Using EclipseLink’s cache framework, you can finely configure each Entity using the @Cache annotation.

@Cache Attributes

type cache type.
isolation Degree to which cached instances are shared with other threads.
expiry Invalidates cache entries after a fixed number of milliseconds.
expiryTimeOfDay Invalidates cache entries at specific time of day.
alwaysRefresh Update cache with any data retrieved from the database. Generally used by queries that can not be executed against the cache.
refreshOnIyIfNewer Used with the above but only refresh if the database version is newer than the cached version.
disableHits This will force all queries to execute against the database but return results from the cache. Can be used in combination with “alwaysRefresh”.
coordinationType Strategy for communicating instance changes to coordinated nodes. Cache Coordination services must be configured at the EntityManagerFactory level.

EclipseLink Cache Types

CacheType.FULL Will cache all Entity instances indefinitely.
CacheType.SOFT Cache uses SoftReference to hold Entities so Cache size is as large as VM allows.
CacheType.WEAK Cache uses WeakReference to hold entities so cache size is dependent on how many Entities are referenced by the application.
CacheType.SOFT_WEAK Recommended. A cache of specific size that uses SoftReference to hold a specified number of Entities. Remaining Entities are held by weak references.
CacheType.HARD_WEAK Recommended. A cache of specific size that uses “hard” references to hold a specified number of Entities. Remaining Entities are held by weak references.
CacheType.CACHE Legacy cache type that is not generally recommended. Can be used by Entities that are not referenced by any other Entity. Cache has an absolute fixed size.
CacheType.NONE Legacy and Not Recommended. Can be used by Entities that are not referenced by any other Entities. No caching occurs.

What to Cache

Caching can also introduce some challenges to your application. Choosing what and how much to cache is one of the first steps. Take into consideration the volatility of the data, who is changing the data, how distributed the application is, and how sensitive the application is to stale data.

Stale Data

Stale data occurs when a client has a view of the data that has been changed since it was read. A concurrent application will always have some amount of stale data, regardless of caching, as concurrent clients update the data after other clients have read the data. Generally, an EclipseLink cache does not increase exposure to stale data; however, additional servers, virtual machines, orthird partyy updates to the data will require a plan. This plan will be a combination of cache size andcache abilityy of entities combined with appropriate locking, refreshing, and invalidation policies.

Cache Invalidation Policies

EclipseLink offers automatic refreshing of Entites based on a time of day or age within the cache. @Cache(expiry= ) can be used to specify the age in milliseconds after which Entities of this type will need to be refreshed. @Cache(expiryTimeOfDay=@TimeOfDay(hour, minute, second)) can be used to specify a time of day (for instance, after a third-party nightly batch process has run) after which all Entities within the cache become invalid. Invalid Entities are automatically refreshed by EclipseLink as they are queried.

Refreshing

Once a version conflict has been detected or to ensure a stale data sensitive operation has the latest data, the application can request a refresh of the latest data from the database. The EclipseLink Query Hint “eclipselink.refresh” can be used in combination with queries or EntityManager find and lock operations to cause the refresh to occur more efficiently.

Cache Coordination

In an environment where multiple instances of the application are deployed, EclipseLink can coordinate the caches of those applications with simple configuration. With cache coordination, active EclipseLink nodes will broadcast either a summary of the changes made to an Entity or just the Entity id, for invalidation, to the other connected caches. With this functionality, the number of Optimistic Lock exceptions experienced can be reduced, which allows an active application to continue to benefit from caches.

Cache coordination is activated through Persistence Unit properties. First, the protocol is set through eclipselink.cache.coordination.protocol:

mms Sends and receives changes through a JMS Topic.
jms-publish Sends changes through JMS, receive through Message Driven Bean.
rmi Uses a fully connected RMI graph to send and receive changes.
rmi-iiop Same as above but uses RMI-IIOP transport protocols.

Additional configuration is completed based on the protocol selected:

13
1
​
2
<properties>
3
…
4
<property name=”eclipselink.cache.coordination.protocol” value=”mms” />
5
&lt;property name=”eclipselink.cache.coordination.jms.host” value=”t3://
6
localhost:7001/” />
7
<property name=”eclipselink.cache.coordination.jms.topic” value=”jms/
8
EclipseLinkTopic” />
9
<property name=”eclipselink.cache.coordination.jms.factory” value=”jms/
10
EclipseLinkTopicConnectionFactory” />
11
…
12
</properties>
13
​

Distributed Caches

Although there are no provided integrations with distributed caches within the EclipseLink project, the ability to connect to distributed caches is available through org.eclipse.persistence.sessions. interceptors.CacheInterceptor and @CacheInterceptors. Oracle’s TopLink Grid product, which integrates with Oracle Coherence, leverages this functionality.

Dealing with Multiple Clients

With multiple clients updating and reading data at the same time, it is important to prevent any data corruption when users update stale data or perform updates based on related stale data.

Optimistic Locking

Versioning each set of updates to an Entity and tracking and comparing those versions is one way to prevent updating stale data. The Java Persistence API provides tracking the version of an Entity through an attribute of the Entity. EclipseLink also provides the functionality to store the version value for the user outside of an Entity class. This can be useful when users do not want to expose versioning within the Entity. It is currently configured through a @DescriptorCustomizer.

The Java Persistence API offers only two supported types of versioning: integer and timestamp mapped to a single attribute. Through the @OptimisticLocking annotion, Eclipselink also supports multi-field locking. With multi-field locking, a set list of fields, changed fields, or all fields can be compared to determine the version of an Entity. This is useful in legacy systems where a version column has not been made available.

Not Caching Relationships

An extension to the normal entity cache configuration allows the developer to mark a relationship so that EclipseLink will not cache it. As an extension to the normal Entity cache configuration the @Noncacheable annotation can mark a relationship so that it will not be cached. Each time the Entity is loaded into a Persistence Context, the relationship will be rebuilt. This can be useful if different users have different access rights or if you always want the relationship to be refreshed.

5
1
​
2
@Noncacheable
3
@OneToOne
4
protected EntityB entityB;
5
​
Section 4

Query Extensions

EclipseLink has many advanced query features that provide far more flexibility than what is currently in the Java Persistence specification. These features are easily accessible through Query Hints.

Caching Query Results

If your application repeatedly executes the same queries and these queries are expected to return the same results, EclipseLink can cache the query results. Cached query results eliminate the need to query the database, which greatly improves throughput. As with the Entity cache, the Query cache can be configured for size and to auto-expire.

The Query Cache can be configured through Query Hints within the Java Persistence API.

eclipselink.query-results-cache Activates the query cache for this query.
eclipselink.query-results-cache.type Has same cache types as the Entity cache but the default for the Query cache is CacheType.cache.
eclipselink.query-results-cache.size Sets a cache size if appropriate.
eclipselink.query-results-cache.expiry Expires cache entries after a fixed number of milliseconds.
eclipselink.query-results-cache.expiry-time-of-day Expires cache entries at specific time of day.

Bulk Reading

If your application needs to read in multiple related Entities it can be far more efficient to read these Entities in a few queries rather than issue multiple separate queries for each relationship and query result. Java Persistence API allows for limited bulk reading using the JOIN FETCH construct in JPQL. However, EclipseLink offers both nested joins and Batch reading.

Join Fetch

Using the Query Hint eclipselink.join-fetch and a simple dot notation, an application can request multiple levels of Entities to be join fetched.

5
1
​
2
Query query = entityManger.createQuery(
3
“SELECT e FROM Employee e WHERE …”);
4
query.setHint(“eclipselink.join-fetch”, “e.department.address”);
5
​

This example will select the Employee, the employee’s Department, and the department’s Address in a single query.

Batch Reading

EclipseLink has an additional bulk reading feature called Batch Reading. Using Join Fetch can often require significant resources as a great deal of duplicate data is returned (for instance, when joining in a OneToMany relationship). Querying the related data using Batch Reading can be more efficient. Batch Reading will query for the root Entity and then use a subsequent query to load the related data. Although there is an additional query, it reduces the number of joins on the database and the amount of data returned.

5
1
​
2
Query query = entityManger.createQuery(
3
“SELECT e FROM Employee e WHERE …”);
4
query.setHint(“eclipselink.batch”, “e.phoneNumbers”);
5
​

Hot Tip

Batch Reading can be used in combination with Join Fetch for optimized bulk reading.

Stored Procedures

Executing a Stored Procedure through EclipseLink’s Java Persistence API extensions is as easy as defining a Named Stored Procedure query.

19
1
​
2
@NamedStoredProcedureQuery(
3
name=”SProcAddress”,
4
resultClass=models.jpa.advanced.Address.class,
5
procedureName=”SProc_Read_Address”,
6
parameters={
7
  @StoredProcedureParameter(
8
direction=IN_OUT,
9
name=”address_id_v”,
10
queryParameter=”ADDRESS_ID”,
11
type=Integer.class),
12
  @StoredProcedureParameter(
13
direction=OUT,
14
name=”street_v”,
15
queryParameter=”STREET”,
16
type=String.class)
17
}
18
)
19
​

This query is then called using the Java Persistence APIs.

3
1
​
2
Query aQuery = em.createNamedQuery(“SProcAddress”)
3
​

A call to getResultList() will return a collection of Address entities through the Stored Procedure’s result set. If no result set is returned, EclipseLink can build Entity results from the output parameters if the resultClass or resultSetMapping is set.

The Direction.OUT_CURSOR is used for stored procedure parameters that are returning result sets through “ref cursors”.

If both result sets and output parameters are returned by the stored procedure, then a SessionEventListener that responds to outputParametersDetected should be registered with the EntityManagerFactory and the output parameters will be returned through this event.

Fetch Groups

Lazy attributes can make queries more efficient by delaying the loading of data. EclipseLink offers a feature called Fetch Groups that allows you to define multiple lazy attribute configurations and apply those on a per-query basis. Attributes are fully lazy accessible, and accessing an unfetched attribute will cause the Entity attributes to be loaded as per the static lazy configuration from the Entity metadata.

Configuration

Fetch Groups can be created statically using @FetchGroup.

15
1
​
2
@FetchGroups({
3
  @FetchGroup(
4
name=”FirstLast”,
5
attributes={
6
@FetchAttribute(name=”first”),
7
@FetchAttribute(name=”last”)
8
}
9
  ),
10
  @FetchGroup(
11
name=”LastName”,
12
attributes={@FetchAttribute(name=”lastName”)}
13
  )
14
})
15
​

They are then applied to the query through the use of Query Hint.

3
1
​
2
query.setHint(QueryHints.FETCH_GROUP_NAME, “FirstLast”);
3
​

Fetch Groups can also be created and used at runtime…

4
1
​
2
FetchGroup fetchGroup = new FetchGroup(); fetchGroup.addAttribute(“lastName”);
3
query.setHint(QueryHints.FETCH_GROUP, fetchGroup);
4
​

Other Fetch Group query hints are available as well to provide fine-grained configuration. Details can be found in the QueryHints javaDocs.

Hot Tip

Have multiple Persistence Contexts in the same transaction? If any are performing transactional writes, ensure you disable an EclipseLink optimization with the Entity Manager property eclipse link. transaction.join-existing so all queries will access transactional data.

Cursors

When reading a large dataset, the application may wish to stream the results from a query. This is useful if the dataset is quite large. Using the query hint “eclipselink.cursor” set to “true”, EclipseLink will return a org.eclipse.persistence.queries.CursoredStream, which will allow the results to be retrieved iteratively from the database.

Hot Tip

Need to load a large dataset and want to bypass the Persistence Context to save heap space? Use the Query Hint “eclipselink.readonly” and the results of the Query will not be managed.

Query Redirectors

Should an application have the need to dynamically alter a query or execute a query against another resource, Query Redirectors can be used. A redirector implements a simple interface org.eclipse. persistence.queries.QueryRedirector, and the developer of the Redirector is free to do most anything. Any cache maintenance will have to occur within the Redirector if the query is executed against another resource.

Configuration

Query Redirectors can be set through the Query Hint eclipse link. query.redirector or set as default Redirectors on an Entity.

7
1
​
2
@QueryRedirectors(
3
allQueries=org.queryredirectors.AllQueriesForEntity.class)
4
@Entity
5
public class …
6
​
7
​

Default Redirectors will be called every time a query is executed against this Entity type. Default Redirectors can be configured per Entity by Query type as well.

Section 5

Mappings

Converters

Sometimes the data in the database column does not match the type of the corresponding Entity attribute. EclipseLink can handle simple conversion for @Basic mappings like Number to String but what if the conversion is more complicated? This is where converters can be useful. With a converter, custom bi-directional conversion can occur between the database and the Entity attributes. Converters are supported on @Basic mappings and primitive @ElementCollections.

EclipseLink offers some predefined converters that support commonly occurring conversions:

@ObjectTypeConverter Maps column values to attribute values (i.e., “t” -> True).
@TypeConverter Converts database type to Java type. Useful for ElementCollections.
@StructConverter Converts from Database Struct type. JGeometry has built in support.

For truly custom conversions, the @Converter that references an implementation of the org.eclipse.persistence.mappings.converters. Converter interface can be specified.

Converters can be set directly on the mapping through the corresponding annotation, or a Converter can be defined at the Entity level and referenced by name through @Convert. If the ElementCollection is a Map type, then a Converter can be applied to the Map’s Key through @MapKeyConvert.

33
1
​
2
@TypeConverter(
3
name=”Long2String”,
4
dataType=String.class,
5
objectType=Long.class
6
)
7
@ObjectTypeConverter(
8
  name=”CreditLine”,
9
  conversionValues={
10
@ConversionValue(dataValue=”RB”,
11
objectValue=ROYAL_BANK),
12
@ConversionValue(dataValue=”CIB”,
13
objectValue=CANADIAN_IMPERIAL),
14
@ConversionValue(dataValue=”SB”,
15
objectValue=SCOTTSBANK),
16
@ConversionValue(dataValue=”HD”,
17
objectValue=HALIFAX_DOWNTOWN)
18
  }
19
)
20
@Entity
21
public class Entity …
22
@ElementCollection
23
@MapKeyColumn(name=”BANK”)
24
@Column(name=”ACCOUNT”)
25
@Convert(“Long2String”)
26
@MapKeyConvert(“CreditLine”)
27
public Map
28
​
29
    getCreditLines() {
30
return creditLines;
31
}
32
​
33
​

Interface Attribute Types

If an application has single-valued Entity attributes that are interface types, EclipseLink’s VariableOneToOne mapping can be used to map these attributes as a polymorphic relationship. This mapping type uses a discriminator column similar to Java Persistence API inheritance support; but, in this case, the discriminator is found on the source table.

19
1
​
2
@VariableOneToOne(
3
targetInterface=Distributor.class,
4
cascade=PERSIST,
5
fetch=LAZY,
6
discriminatorColumn=@DiscriminatorColumn(
7
name=”DISTRIBUTOR_TYPE”,
8
discriminatorType=INTEGER),
9
discriminatorClasses={
10
@DiscriminatorClass(discriminator=”1”,
11
value=MegaBrands.class),
12
@DiscriminatorClass(discriminator=”2”,
13
value=Namco.class)
14
}
15
)
16
public Distributor getDistributor() {
17
  return distributor;
18
}
19
​

To execute queries with path expressions that include an interface mapping, a Query Key must be defined on the Interface descriptor. Currently, this must done using a SessionCustomizer. Details on Query Keys can be found here: http://wiki.eclipse.org/EclipseLink/ UserGuide/JPA/Basic_JPA_Development/Querying/Query_Keys

Additional Filtering Criteria

Need to support multi-tenancy, temporal filtering or any number of other use cases where an application has a query restriction that needs to be applied to the restrictions on all queries? @AdditionalCriteria can be applied to an Entity class to specify that additional filtering occurs for any queries on that type. When specifying the path in an AdditionalCriteria, the identification variable “this” is used to identify the root of the query.

5
1
​
2
@AdditionalCriteria(“this.role = :accessRole”);
3
@Entity
4
public class EntityA {…}
5
​

Additional Criteria supports parameters, and parameter values can be set at the EntityManagerFactory or EntityManager levels.

3
1
​
2
entityManager.setProperty(“accessRole”, “bravo”);
3
​

Hot Tip

Combine Additional Criteria with @Noncacheable relationships to provide EntityManager scoped user data.

Return On Insert/Update

If the database has triggers that return data to the calling client, the @ReturnInsert / @ReturnUpdate annotations can be applied to the corresponding @Basic mappings to have EclipseLink apply the return value to the Entity.

The result from the database will be parsed for the mappings field and the value placed in the attribute.

5
1
​
2
@ReturnInsert(returnOnly=true)
3
@Basic
4
protected long id;
5
​
Section 6

Connections

Partitioning

If an application needs access to multiple databases (perhaps for load balancing or data affinity), EclipseLink has functionality called Partitioning that will allow many schemes for accessing multiple databases.

With partitioning, users can “stripe” data across multiple databases or schemas by Entity field value or by Entity type.

3
1
​
2
@RangePartitioning, @HashPartitioning, @PinnedPartitioning, @ValuePartitiong
3
​

Other Partitioning Policies are available for load balancing or replication across multiple databases or schemas.

3
1
​
2
@ReplicationPartititoning, @RoundRobinPartitioning, @UnionPartitioning
3
​

Entirely custom policy implementations are also an option. If users need certain processing that can not be found in the pre-existing partitioning implementations the PartitioningPolicy can be extended and a custom Policy specified using @Partitioning.

An example of an Entity’s partitioning configuration follows:

14
1
​
2
@Entity
3
@Table(name = “PART_DEPT”)
4
@HashPartitioning(
5
name=”HashPartitioningByID”,
6
partitionColumn=@Column(name=”ID”),
7
unionUnpartitionableQueries=true,
8
connectionPools={“node2”, “node3”})
9
@UnionPartitioning(
10
  name=”UnionPartitioningAllNodes”,
11
 replicateWrites=true)
12
@Partitioned(“HashPartitioningByID”)
13
public class Department implements Serializable {
14
​

VPD, Proxy Authentication

If an application needs to access a database when proxy authentication or row level security is required, EclipseLink has easy-to-use configuration that will allow “authentication” of the connection.

For Proxy Authentication, provide the necessary Persistence Unit properties to the EntityManagerFactory or EntityManager and EclipseLink will ensure the connection acquired from the datasource will be “authenticated”.

7
1
​
2
Map emProperties = new HashMap();
3
emProperties.put(“eclipselink.oracle.proxy-type”,
4
OracleConnection.PROXYTYPE_USER_NAME);
5
emProperties.put(OracleConnection.PROXY_USER_NAME, “john”);
6
EntityManager em = emf.createEntityManager(emProperties);
7
​

Or in the case of injection:

5
1
​
2
entityManager.setProperty(“eclipselink.oracle.proxy-type”,
3
OracleConnection.PROXYTYPE_USER_NAME);
4
entityManager.setProperty(OracleConnection.PROXY_USER_NAME, “john”);
5
​

For Virtual Private Database (VPD) or manual “authentication”, a Session Event exists “postAcquireExclusiveConnection” that will be called whenever EclipseLink acquires a connection for “authentication”. This event can be used to provide any required details to the connection like a ClientIdentifier.

An additional property that specifies when EclipseLink must use the “authenticated” connection is required for both VPD type and Proxy authentication. “eclipselink.jdbc.exclusive-connection.mode” should be set to “Isolated” if all Entities corresponding to secured tables have been set to @Cacheable(false) or to “Always” otherwise .

Connection Pooling

When deploying an EclipseLink application in an environment without managed datasources, EclipseLink offers built-in connection management. Configuring connection pooling can be as simple as setting the Persistence Unit Properties using “eclipselink.connectionpool. “ during creation of the Entity Manager Factory. There are many connection pool properties combinations that can be found in the JavaDocs.

Section 7

Other Popular Extensions

Persistence Context Memory Management

If a Persistence Context tends to have a long lifecycle within an application, managing the size of the Persistence Context can be difficult. EclipseLink can allow an application to leverage the Java garbage collector and remove Entities from the Persistence Context that are no longer in use by the application. This is done through the EntityManager property “eclipselink.persistence-context.referencemode”. Possible values are:

  • HARD - the default and ensures no Entities will be removed from the Persistence Context automatically.
  • WEAK – in combination with weaving, ensures any Entities with changes will not be removed from Persistence Context; but other unreferenced Entities may be removed.
  • FORCED_WEAK – any unreferenced Entities may be removed from the Persistence Context by the garbage collector. Changes in these Entities will be lost if not already flushed.

Batch Writing

EclipseLink supports writing to the database using batched writes. This is configured through the Persistence Unit property “eclipse link. jdbc.batch-writing” and should be used in combination with parameter binding, which is active by default. Possible values for the property are:

  • JDBC – this uses standard JDBC batch writing and should be used in most cases.
  • Oracle-JDBC – use native Oracle database batch writing.

Customizers

EclipseLink has a great depth to its functionality. Although the most popular features are available, not all of the EclipseLink functionality is exposed through JPA extensions. “Customizers” are a simple mechanism that exposes internal EclipseLink customization to Java Persistence API applications.

Both EntityManagerFactory level customizers, called Session Customizers, and Entity level mapping customizers, called Descriptor Customizers, are available.

To use a Session Customizer, the Persistence Unit property “eclipselink.session.customizer” is used to specify an implementor of the interface org.eclipse.persistence.config.SessionCustomizer.

To use a Descriptor Customizer, a Persistence Unit property “eclipselink.descriptor.customizer.<entity name>” or @Customizer is used to specify a class that implements the interface org.eclipse. persistence.config.DescriptorCustomizer.

Event Listeners

EclipseLink has far more events available than those specified by Java Persistence API. Events are available on query execution, Entity Manager Factory creation, stored procedure output parameter results, connection acquisition, precise Entity lifecycle events, and at many other points during a running application.

Entity Listeners

The easiest listeners to use in Java Persistence are the Entity Listeners. These listeners (such as aboutToUpdate, postUpdate, postDelete, etc ) provide events at points during an Entity’s lifecycle. Events like these can be useful to implement auditing or client notification. To receive the event notification, the interface org.eclipse.persistence. descriptors.DescriptorEventListener is implemented or org.eclipse. persistence.descriptors.DescriptorEventAdaptor is extended for the desired events. Then using @EntityListeners, these listener classes are provided to EclipseLink.

Entity Manager Factory Listeners

The Entity Manager Factory Listeners are referred to as SessionEventListeners in EclipseLink. These listeners are notified for more general process notifications, like connection acquisition that is used for VPD; transaction events like preRollbackTransaction; EntityManager process events like postCalculateChanges that are fired after flush but before writes have begun; query execution events like outputParametersDetected for Stored Procedure execution; and many more events.

To receive notification of these events, a custom class is created that implements org.eclipse.persistence.sessions.SessionEventListener or extends org.eclipse.persistence.sessions.SessionEventAdaptor for the desired events. Then the listener is set on the Entity Manager Factory through the Persistence Unit property “eclipselink.sessionevent-listener”.

Section 8

Resources

Community

EclipseLink is a very powerful product with many customization and extension points, all of which could not possibly be covered in a Refcard. For more information or help using a feature, EclipseLink has an active and helpful community. Help can always be found using eclipselink-users@eclipse.org or the forums http://www.eclipse.org/forums/index.php?t=thread&frm_id=111. A comprehensive User Guide can be found here: http://wiki.eclipse.org/EclipseLink/UserGuide

Enhancements and Feedback

Because EclipseLink is an open-source project, new feature development, designs, and bug reports are available for review and feedback. eclipselink-dev@eclipse.org is an active mailing list, and all feature development is tracked using wiki http://wiki.eclipse.org/EclipseLink/Development and the bug database https://bugs.eclipse.org/bugs

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Optimizing JPA Performance: An EclipseLink, Hibernate, and OpenJPA Comparison
related article thumbnail

DZone Article

The Ultimate Guide on DB-Generated IDs in JPA Entities
related article thumbnail

DZone Article

Scaling Databases With EclipseLink And Redis
related article thumbnail

DZone Article

Mapping Java Entities for Persistence With Hibernate (Part 4)
related refcard thumbnail

Free DZone Refcard

Getting Started With Vector Databases
related refcard thumbnail

Free DZone Refcard

MongoDB Essentials
related refcard thumbnail

Free DZone Refcard

PostgreSQL Essentials
related refcard thumbnail

Free DZone Refcard

NoSQL Migration Essentials

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: