0% found this document useful (0 votes)
305 views

Eclipselink 3

eclipselink 3

Uploaded by

georgiua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
305 views

Eclipselink 3

eclipselink 3

Uploaded by

georgiua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 166

EclipseLink

Understanding EclipseLink
2.5

October 2013
EclipseLink Concepts Guide
Copyright 2012, 2013, by The Eclipse Foundation under the Eclipse Public License (EPL)
http://www.eclipse.org/org/documents/epl-v10.php
The initial contribution of this content was based on work copyrighted by Oracle and was submitted with
permission.
Print date: October 3, 2013
iii
Contents
Preface............................................................................................................................................................... xiii
Audience..................................................................................................................................................... xiii
Related Documents ................................................................................................................................... xiii
Conventions ............................................................................................................................................... xiii
1 Overview of EclipseLink
1.1 Understanding EclipseLink....................................................................................................... 1-1
1.1.1 What Is the Object-Persistence Impedance Mismatch?.................................................. 1-3
1.1.2 The EclipseLink Solution.................................................................................................... 1-3
1.2 Key Features ................................................................................................................................ 1-4
1.3 New Features............................................................................................................................... 1-4
1.3.1 RESTful Services .................................................................................................................. 1-4
1.3.2 Tenant Isolation.................................................................................................................... 1-5
1.3.3 NoSQL................................................................................................................................... 1-5
1.3.4 JSON...................................................................................................................................... 1-6
1.3.5 Database Change Notification........................................................................................... 1-6
1.3.6 Extensible Entities................................................................................................................ 1-6
1.3.7 Composite Persistence Units.............................................................................................. 1-6
1.3.8 External Metadata Sources ................................................................................................. 1-7
1.4 Key Concepts ............................................................................................................................... 1-7
1.4.1 EclipseLink Metadata.......................................................................................................... 1-7
1.4.2 Entities................................................................................................................................... 1-8
1.4.3 Descriptors............................................................................................................................ 1-8
1.4.4 Mappings .............................................................................................................................. 1-8
1.4.5 Data Access........................................................................................................................... 1-8
1.4.6 Caching.................................................................................................................................. 1-8
1.4.7 Queries .................................................................................................................................. 1-9
1.4.8 Expression Framework ....................................................................................................... 1-9
1.4.9 NoSQL Databases ................................................................................................................ 1-9
1.4.10 Performance Monitoring and Profiling ............................................................................ 1-9
1.5 Key Components......................................................................................................................... 1-9
1.5.1 EclipseLink Core and API .................................................................................................. 1-9
1.5.2 Object-Relational (JPA 2.0) Component ........................................................................ 1-10
1.5.3 Object-XML (JAXB 2.2) Component............................................................................... 1-10
1.5.3.1 SDO Component........................................................................................................ 1-11
iv
1.5.4 Database Web Services Component .............................................................................. 1-11
1.6 Key Tools................................................................................................................................... 1-12
1.6.1 Oracle JDeveloper ............................................................................................................ 1-12
1.6.2 Eclipse................................................................................................................................. 1-12
1.6.3 NetBeans ............................................................................................................................ 1-13
2 Understanding Mappings
2.1 About Object-Relational Mapping ........................................................................................... 2-1
2.1.1 Understanding Object-Relational Entity Architecture................................................... 2-1
2.1.1.1 Entities............................................................................................................................ 2-2
2.1.1.2 Persistence and Persistence Units .............................................................................. 2-2
2.1.1.3 Entity Managers............................................................................................................ 2-3
2.1.2 Adding Metadata Using Annotations .............................................................................. 2-3
2.1.2.1 Advantages and Disadvantages of Using Annotations.......................................... 2-4
2.1.3 About Configuration Basics ............................................................................................... 2-4
2.1.3.1 Default Configuration Values..................................................................................... 2-4
2.1.3.2 Configuring Persistence Units Using persistence.xml ............................................ 2-4
2.1.3.3 Object-Relational Data Type Mappings .................................................................... 2-4
2.1.3.3.1 Specifying Object-Relational Mappings Using orm.xml ................................. 2-5
2.1.3.3.2 Specifying EclipseLink Object-Relational Mappings Using eclipselink-orm.xml
2-5
2.1.3.4 Overriding and Merging Mapping Information...................................................... 2-5
2.1.3.5 Validating the XML Schema ....................................................................................... 2-6
2.1.3.6 Advantages and Disadvantages of Using XML....................................................... 2-6
2.1.4 About Data Sources ............................................................................................................. 2-6
2.1.5 About EclipseLink Caches.................................................................................................. 2-6
2.1.5.1 Defining Cache Behavior............................................................................................. 2-7
2.1.5.2 Caching in Clustered Environments.......................................................................... 2-7
2.1.6 About Database Queries..................................................................................................... 2-7
2.2 About Object-XML Mapping .................................................................................................... 2-8
2.2.1 Using EclipseLink Object-XML as the JAXB Provider ................................................... 2-8
2.2.2 Understanding Object-XML Architecture ....................................................................... 2-9
2.2.2.1 JAXB Contexts and JAXB Context Factories............................................................. 2-9
2.2.3 Serving Metadata for Object-XML ................................................................................. 2-10
2.2.4 About XML Bindings ....................................................................................................... 2-10
2.2.4.1 Specifying EclipseLink Object-XML Mappings Using eclipselink-oxm.xml ... 2-10
2.2.5 About Object-XML Data Type Mappings ..................................................................... 2-10
2.2.6 Querying Objects by XPath............................................................................................. 2-11
3 Understanding Application Development
3.1 Typical Development Stages ..................................................................................................... 3-1
3.2 Target Platforms.......................................................................................................................... 3-3
3.3 Building and Using the Persistence Layer .............................................................................. 3-3
3.3.1 Implementation Options..................................................................................................... 3-4
3.3.1.1 Using EclipseLink JPA Metatdata, Annotations, and XML ................................... 3-4
3.3.1.2 Using EclipseLink Metadata Java API....................................................................... 3-4
3.3.1.3 Using Method and Direct Field Access ..................................................................... 3-4
v
3.3.1.4 Using Java Byte-code Weaving................................................................................... 3-5
3.3.2 Persistent Class Requirements........................................................................................... 3-5
3.3.3 Persistence Layer Components.......................................................................................... 3-5
3.3.3.1 Mapping Metadata....................................................................................................... 3-5
3.3.3.2 Cache .............................................................................................................................. 3-5
3.3.3.3 Queries and Expressions ............................................................................................. 3-6
3.4 About Application Deployment .............................................................................................. 3-6
3.5 About Persisting Objects............................................................................................................ 3-6
3.5.1 Application Object Model .................................................................................................. 3-7
3.5.2 Data Storage Schema........................................................................................................... 3-7
3.5.3 Primary Keys and Object Identity..................................................................................... 3-7
3.5.4 Mappings .............................................................................................................................. 3-8
3.5.5 Foreign Keys and Object Relationships............................................................................ 3-8
3.5.6 Inheritance ............................................................................................................................ 3-8
3.5.7 Concurrency ......................................................................................................................... 3-8
3.5.8 Caching.................................................................................................................................. 3-9
3.5.9 Nonintrusive Persistence.................................................................................................... 3-9
3.5.10 Indirection............................................................................................................................. 3-9
3.5.11 Mutability........................................................................................................................... 3-10
3.6 About Metadata ....................................................................................................................... 3-10
3.6.1 Advantages of the Metadata Architecture.................................................................... 3-11
3.6.2 Creating Project Metadata............................................................................................... 3-11
3.6.2.1 Descriptors and Mappings....................................................................................... 3-12
3.6.2.2 Data Source Login Information............................................................................... 3-12
3.6.3 Creating Session Metadata .............................................................................................. 3-12
3.7 About Weaving ........................................................................................................................ 3-13
3.7.1 Using Dynamic Weaving................................................................................................. 3-13
3.7.2 Using Static Weaving ....................................................................................................... 3-13
3.7.3 Weaving POJO Classes .................................................................................................... 3-13
3.7.4 Weaving and Java EE Application Servers ................................................................... 3-14
3.7.5 Disabling Weaving with Persistence Unit Properties ................................................. 3-14
4 Understanding Entities
4.1 Identifying Entities ..................................................................................................................... 4-1
4.2 Entities and Persistent Identity................................................................................................. 4-1
4.3 Entities and Database Tables..................................................................................................... 4-2
4.4 Entities and Inheritance ............................................................................................................. 4-2
4.5 Entities and Embedded Objects ................................................................................................ 4-2
4.6 Entities and Sequence Generation............................................................................................ 4-3
4.7 Entities and Locking................................................................................................................... 4-3
5 Understanding Application Deployment
5.1 Integrating with an Application Server................................................................................... 5-1
5.1.1 Software Requirements....................................................................................................... 5-1
5.1.2 Setting Security Permissions .............................................................................................. 5-1
5.1.3 Migrating Applications to the EclipseLink Persistence Manager ................................ 5-2
vi
5.2 About the Persistence Unit ........................................................................................................ 5-2
5.2.1 About the Persistence Unit Name ..................................................................................... 5-2
5.2.2 About the Transaction Type, Persistence Provider and Data Source .......................... 5-2
5.2.3 About Mapping Files........................................................................................................... 5-3
5.2.4 About Managed Classes ..................................................................................................... 5-3
5.2.5 About Vendor Properties.................................................................................................... 5-4
5.2.6 About the Deployment Classpath..................................................................................... 5-4
5.2.7 About Persistence Unit Packaging Options..................................................................... 5-5
5.2.8 About the Persistence Unit Scope...................................................................................... 5-5
5.3 Integrating Clustering................................................................................................................ 5-5
6 Understanding Descriptors
6.1 Common Descriptor Concepts.................................................................................................. 6-1
6.1.1 Descriptor Architecture ...................................................................................................... 6-1
6.1.2 Descriptors and Inheritance ............................................................................................... 6-2
6.1.2.1 Specifying a Class Indicator........................................................................................ 6-3
6.1.2.1.1 Using Class Indicator Fields ................................................................................ 6-3
6.1.2.1.2 Using Class Extraction Methods ......................................................................... 6-4
6.1.2.2 Inheritance and Primary Keys .................................................................................... 6-5
6.1.2.3 Single and Multi-Table Inheritance............................................................................ 6-5
6.1.2.4 Aggregate and Composite Descriptors and Inheritance ........................................ 6-5
6.1.3 Descriptors and Aggregation............................................................................................. 6-5
6.1.4 Descriptor Customization .................................................................................................. 6-5
6.1.5 Amendment and After-Load Methods............................................................................. 6-6
6.1.6 Descriptor Event Manager ................................................................................................. 6-6
6.2 Object-Relational Descriptor Concepts.................................................................................... 6-6
6.2.1 Fetch Groups ....................................................................................................................... 6-6
6.2.1.1 AttributeGroup Types and Operations..................................................................... 6-7
6.2.1.2 FetchGroup.................................................................................................................... 6-7
6.2.1.3 Default FetchGroup...................................................................................................... 6-7
6.2.1.4 Named FetchGroup...................................................................................................... 6-8
6.2.1.5 Full FetchGroup............................................................................................................ 6-8
6.2.1.6 Load/LoadAll with FetchGroup................................................................................ 6-8
6.2.1.7 LoadGroup .................................................................................................................... 6-8
6.2.1.8 CopyGroup.................................................................................................................... 6-8
6.2.1.9 Merging.......................................................................................................................... 6-8
6.2.2 Descriptor Query Manager ................................................................................................ 6-8
6.2.3 Descriptors and Sequencing............................................................................................... 6-9
6.2.4 Descriptors and Locking..................................................................................................... 6-9
6.2.4.1 Optimistic Version Locking Policies.......................................................................... 6-9
6.2.4.1.1 Optimistic Version Locking Policies and Cascading .................................... 6-10
6.2.4.1.2 Optimistic Locking and Rollbacks ................................................................... 6-11
6.2.4.1.3 Optimistic Field Locking Policies .................................................................... 6-11
6.2.4.2 Pessimistic Locking Policies..................................................................................... 6-12
6.2.4.3 Applying Locking in an Application...................................................................... 6-12
6.2.4.3.1 Applying Optimistic Locking in an Application........................................... 6-12
6.2.4.3.2 Applying Pessimistic Locking in an Application.......................................... 6-13
vii
6.3 Object-XML Descriptor Concepts.......................................................................................... 6-13
6.3.1 Default Root Element ....................................................................................................... 6-13
6.4 Descriptor API.......................................................................................................................... 6-14
7 Understanding Mappings
7.1 Common Mapping Concepts .................................................................................................... 7-1
7.1.1 Mapping Architecture......................................................................................................... 7-1
7.1.2 Mapping Examples.............................................................................................................. 7-2
7.1.3 Using Lazy Loading ............................................................................................................ 7-3
7.1.4 Mapping Converters and Transformers........................................................................... 7-3
7.1.4.1 Serialized Object Converter ........................................................................................ 7-4
7.1.4.2 Type Conversion Converter........................................................................................ 7-4
7.1.4.3 Object Type Converter................................................................................................. 7-6
7.1.4.4 Transformation Mappings .......................................................................................... 7-6
7.1.5 Transformation Mapping ................................................................................................... 7-6
7.2 Object-Relational Mapping Concepts ...................................................................................... 7-7
7.2.1 Indirection (Lazy Loading)................................................................................................. 7-7
7.2.2 Value Holder Indirection.................................................................................................... 7-8
7.2.3 Transparent Indirection................................................................................................... 7-10
7.2.4 Proxy Indirection .............................................................................................................. 7-10
7.2.4.1 Proxy Indirection Restrictions ................................................................................. 7-11
7.2.5 Weaved Indirection .......................................................................................................... 7-11
7.2.6 Indirection and JPA.......................................................................................................... 7-11
7.2.7 Indirection, Serialization, and Detachment .................................................................. 7-11
7.3 Object-XML Mapping Concepts ............................................................................................ 7-12
7.3.1 Simple Type Translation.................................................................................................. 7-12
7.3.1.1 Default Read Conversions........................................................................................ 7-13
7.3.1.2 Default Write Conversions....................................................................................... 7-14
7.4 Object-JSON Mapping Concepts ........................................................................................... 7-14
7.5 About JPA Mapping Types .................................................................................................... 7-15
7.5.1 Basic Mappings ................................................................................................................. 7-15
7.5.2 Default Conversions and Converters ............................................................................ 7-16
7.5.3 Collection Mappings ........................................................................................................ 7-17
7.5.3.1 One-to-Many Mapping............................................................................................. 7-17
7.5.3.1.1 JPA Mapping....................................................................................................... 7-17
7.5.3.2 Many-to-Many Mapping.......................................................................................... 7-18
7.5.3.2.1 JPA Mapping....................................................................................................... 7-19
7.5.4 Using Optimistic Locking................................................................................................ 7-20
7.5.4.1 Optimistic Locking in a Stateless Environment .................................................... 7-20
7.5.4.2 Optimistic Version Locking ..................................................................................... 7-20
8 Understanding Data Access
8.1 About Externally Managed Transactional Data Sources ...................................................... 8-1
8.2 About Data Source Login Types............................................................................................... 8-1
8.3 About Data Source Platform Types.......................................................................................... 8-2
8.4 About Authentication................................................................................................................. 8-2
viii
8.4.1 Simple JDBC Authentication.............................................................................................. 8-3
8.4.2 Oracle Database Proxy Authentication ............................................................................ 8-3
8.4.3 Auditing................................................................................................................................ 8-4
8.5 About Connections ..................................................................................................................... 8-4
8.6 About Connection Pools ............................................................................................................ 8-4
8.6.1 Internal Connection Pools .................................................................................................. 8-5
8.6.2 External Connection Pools ................................................................................................. 8-5
8.6.3 Default (Write) and Read Connection Pools.................................................................... 8-5
8.6.4 Sequence Connection Pools................................................................................................ 8-6
8.6.5 Application-Specific Connection Pools ............................................................................ 8-6
8.7 About Data Partitioning Policies .............................................................................................. 8-6
8.8 About Clustered Databases and Oracle RAC......................................................................... 8-8
9 Understanding Caching
9.1 About Cache Architecture ......................................................................................................... 9-1
9.1.1 Persistence Unit Cache........................................................................................................ 9-2
9.1.2 Persistence Context Cache.................................................................................................. 9-3
9.1.2.1 Application Managed Persistence Contexts ............................................................. 9-3
9.1.2.2 Container Managed Persistence Contexts ................................................................ 9-3
9.1.3 Shared, Isolated, Protected, Weak, and Read-only Caches ........................................... 9-3
9.1.3.1 Isolated Cache ............................................................................................................... 9-4
9.1.3.2 Shared Cache................................................................................................................. 9-4
9.1.3.3 Protected Cache ............................................................................................................ 9-5
9.1.3.4 Weak Reference Mode ................................................................................................. 9-5
9.1.3.5 Read-Only Entities........................................................................................................ 9-6
9.2 About Cache Type and Size ...................................................................................................... 9-6
9.2.1 FULL Cache Type ................................................................................................................ 9-7
9.2.2 WEAK Cache Type.............................................................................................................. 9-7
9.2.3 SOFT Cache Type ................................................................................................................ 9-7
9.2.4 SOFT_CACHE and HARD_CACHE Cache Type .......................................................... 9-7
9.2.5 NONE and CACHE............................................................................................................. 9-8
9.2.6 Guidelines for Configuring the Cache and Identity Maps ............................................ 9-8
9.2.6.1 About the Internals of Weak, Soft, and Hard Cache Types ................................... 9-8
9.3 About Queries and the Cache ................................................................................................... 9-9
9.4 About Handling Stale Data ....................................................................................................... 9-9
9.4.1 Configuring a Locking Policy ......................................................................................... 9-10
9.4.1.1 Optimistic Locking.................................................................................................... 9-10
9.4.1.2 Pessimistic Locking ................................................................................................... 9-10
9.4.2 Configuring the Cache on a Per-Class Basis................................................................. 9-10
9.4.3 Forcing a Cache Refresh when Required on a Per-Query Basis ................................ 9-10
9.4.4 Configuring Cache Invalidation..................................................................................... 9-10
9.4.5 Configuring Cache Coordination................................................................................... 9-10
9.5 About Explicit Query Refreshes ............................................................................................ 9-11
9.5.1 Refresh Policy.................................................................................................................... 9-11
9.6 About Cache Expiration and Invalidation ........................................................................... 9-11
9.6.1 Advanced Cache Invalidation ........................................................................................ 9-12
9.7 About Cache Indexes............................................................................................................... 9-12
ix
9.8 About Query Results Cache ................................................................................................... 9-13
9.9 About Cache Locking and Transaction Isolation................................................................ 9-13
9.10 About Cache Optimization..................................................................................................... 9-13
9.11 About Cache Coordination..................................................................................................... 9-13
9.11.1 When to Use Cache Coordination.................................................................................. 9-15
9.11.2 Coordinated Cache Architecture and Types ................................................................ 9-15
9.11.2.1 JMS Coordinated Cache............................................................................................ 9-15
9.11.2.2 RMI Coordinated Cache........................................................................................... 9-16
9.11.3 Custom Coordinated Cache ............................................................................................ 9-16
9.11.4 Coordinated Cache and Clustering................................................................................ 9-16
9.11.4.1 Persistence Property Extensions for Cache Coordination .................................. 9-17
9.11.4.2 Cache Coordination and Oracle WebLogic ........................................................... 9-18
9.11.4.3 Cache Coordination and Glassfish.......................................................................... 9-18
9.11.4.4 Cache Coordination and IBM WebSphere............................................................. 9-18
10 Understanding Queries
10.1 Query Concepts........................................................................................................................ 10-1
10.1.1 Call Objects ........................................................................................................................ 10-2
10.1.2 DatabaseQuery Objects.................................................................................................... 10-2
10.1.3 Data-Level and Object-Level Queries............................................................................ 10-2
10.1.4 Summary Queries ............................................................................................................. 10-2
10.1.5 Descriptor Query Manager ............................................................................................. 10-2
10.1.6 EclipseLink Expressions .................................................................................................. 10-2
10.1.7 Query Keys ........................................................................................................................ 10-3
10.2 About JPQL Queries ................................................................................................................ 10-3
10.2.1 Select Queries .................................................................................................................... 10-3
10.2.1.1 SELECT Clause .......................................................................................................... 10-3
10.2.1.1.1 Aggregation functions ....................................................................................... 10-3
10.2.1.1.2 Constructors........................................................................................................ 10-3
10.2.1.2 FROM Clause ............................................................................................................. 10-3
10.2.1.2.1 JOIN...................................................................................................................... 10-4
10.2.1.2.2 JOIN FETCH....................................................................................................... 10-4
10.2.1.2.3 LEFT JOIN........................................................................................................... 10-4
10.2.1.2.4 ON........................................................................................................................ 10-4
10.2.1.2.5 Sub-selects in FROM clause .............................................................................. 10-4
10.2.1.3 ORDER BY clause...................................................................................................... 10-4
10.2.1.4 GROUP BY Clause..................................................................................................... 10-5
10.2.1.5 HAVING Clause........................................................................................................ 10-5
10.2.1.6 UNION........................................................................................................................ 10-5
10.2.2 WHERE Clause ................................................................................................................. 10-5
10.2.3 Update Queries ................................................................................................................. 10-5
10.2.4 Delete Queries ................................................................................................................... 10-6
10.2.5 Parameters ......................................................................................................................... 10-6
10.2.5.1 Literals......................................................................................................................... 10-7
10.2.6 Functions............................................................................................................................ 10-7
10.2.7 EclipseLink Special Operators ........................................................................................ 10-7
10.2.8 EclipseLink Extensions .................................................................................................... 10-8
x
10.3 About SQL Query Language.................................................................................................. 10-8
10.4 About the Criteria API ............................................................................................................ 10-9
10.4.1 CriteriaBuilder................................................................................................................... 10-9
10.4.2 CriteriaQuery .................................................................................................................... 10-9
10.4.3 Where.................................................................................................................................. 10-9
10.4.4 Subquery .......................................................................................................................... 10-10
10.4.5 Parameters ....................................................................................................................... 10-10
10.4.6 Functions.......................................................................................................................... 10-10
10.4.7 Special Operations .......................................................................................................... 10-10
10.4.8 Metamodel ....................................................................................................................... 10-10
10.4.9 Tuple Queries .................................................................................................................. 10-10
10.4.10 JpaCriteriaBuilder and EclipseLink Extensions ......................................................... 10-10
10.5 About Native SQL Queries................................................................................................... 10-11
10.5.1 Parameters ....................................................................................................................... 10-12
10.5.2 Named Native SQL Queries.......................................................................................... 10-12
10.5.3 SQL Result Set Mapping................................................................................................ 10-12
10.6 About Advanced Native Query Support ........................................................................... 10-12
10.7 About JPA Query Hints ........................................................................................................ 10-13
10.8 About Query Casting ............................................................................................................ 10-14
10.8.1 JPA 2.0 Type .................................................................................................................... 10-14
10.8.2 Downcasting in JPQL..................................................................................................... 10-14
10.8.3 JPA Criteria API .............................................................................................................. 10-14
10.8.4 EclipseLink Expression Support for Downcast.......................................................... 10-14
10.9 About Oracle Extensions for Queries.................................................................................. 10-14
10.9.1 Query Hints ..................................................................................................................... 10-15
10.9.2 Hierarchical Queries....................................................................................................... 10-15
10.9.3 Flashback Queries........................................................................................................... 10-15
10.9.4 Stored Functions ............................................................................................................. 10-15
11 Understanding EclipseLink Expressions
11.1 About the Expression Framework......................................................................................... 11-1
11.1.1 Comparing Expressions to SQL...................................................................................... 11-1
11.2 About Expression Components ............................................................................................. 11-1
11.2.1 Boolean Logic .................................................................................................................... 11-2
11.2.2 Database Functions and Operators ................................................................................ 11-2
11.2.2.1 Database Functions ................................................................................................... 11-2
11.2.2.2 Database Operators ................................................................................................... 11-3
11.2.2.3 Mathematical Functions ........................................................................................... 11-3
11.2.2.4 XMLType Functions.................................................................................................. 11-4
11.2.3 Platform and User-Defined Functions........................................................................... 11-4
11.2.4 Expressions for One-to-One and Aggregate Object Relationships ........................... 11-4
11.2.5 Expressions for Joining and Complex Relationships ................................................. 11-4
11.2.5.1 About Joins ................................................................................................................. 11-4
11.2.5.2 Using EclipseLink Expression API for Joins.......................................................... 11-5
12 Understanding Non-relational Data Sources
12.1 NoSQL Platform Concepts ..................................................................................................... 12-1
xi
12.2 About NoSQL Persistence Units............................................................................................ 12-2
12.2.1 Persistence Unit Properties for NoSQL Platforms ....................................................... 12-2
12.3 About JPA Applications on the NoSQL Platform............................................................... 12-3
12.3.1 Mapping Restrictions on JPA Annotations................................................................... 12-3
12.4 About Mapping NoSQL Objects............................................................................................ 12-4
12.5 About Queries and the NoSQL Platform............................................................................. 12-4
12.6 About Transactions and the NoSQL Platform..................................................................... 12-5
13 Understanding Performance Monitoring and Profiling
13.1 Performance Profiling ............................................................................................................. 13-1
13.2 Fetch Group Monitoring......................................................................................................... 13-1
13.3 Performance Monitoring......................................................................................................... 13-2
13.4 Query Monitoring.................................................................................................................... 13-3
A Database and Application Server Support
A.1 Database Support....................................................................................................................... A-1
A.2 Application Server Support...................................................................................................... A-4
A.2.1 EclipseLink MOXy as the JAXB Provider for Application Servers ............................. A-5
A.3 Non-SQL Standard Database Support: NoSQL..................................................................... A-5
xii
xiii
Preface
EclipseLink delivers a proven standards based enterprise Java solution for all of your
relational, XML, and JSON persistence needs based on high performance and
scalability, developer productivity, and flexibility in architecture and design.
Audience
This document is intended for application developers and administrators who want to
know more about the concepts behind EclipseLink and its features.
Related Documents
For more information, see the following documents in the EclipseLink documentation
set:
I Solutions Guide for EclipseLink
I Java Persistence API (JPA) Extensions Reference for EclipseLink
I Developing JAXB Applications Using EclipseLink MOXy
I Developing Persistence Architectures Using EclipseLink
I Java API Reference for EclipseLink
I Java Persistence specification for complete information about JPA
http://jcp.org/en/jsr/detail?id=317
Conventions
The following text conventions are used in this document:
Convention Meaning
boldface Boldface type indicates graphical user interface elements associated
with an action, or terms defined in text or the glossary.
italic Italic type indicates book titles, emphasis, or placeholder variables for
which you supply particular values.
monospace Monospace type indicates commands within a paragraph, URLs, code
in examples, text that appears on the screen, or text that you enter.
xiv
1
Overview of EclipseLink 1-1
1Overview of EclipseLink
This chapter describes EclipseLink and its key features: the components that are
included with EclipseLink, metadata, application architectures, mappings, and the
API.
This chapter contains the following sections:
I Understanding EclipseLink
I Key Features
I New Features
I Key Concepts
I Key Components
I Key Tools
1.1 Understanding EclipseLink
EclipseLink is an open-source mapping and persistence framework for use in a Java
environment, including Java Platform, Standard Edition (Java SE) and Java Platform,
Enterprise Edition (Java EE). The EclipseLink project is under the stewardship of the
Eclipse Foundation.
EclipseLink completely implements the following specifications, plus extensions to
those specifications:
I Java Persistence API (JPA)
JPA is the Java API for object/relational mapping (ORM), where Java objects are
mapped to database artifacts, for the purpose of managing relational data in Java
applications. JPA includes Java Persistence Query Language (JPQL), the Java
Persistence Criteria API, and the Java API and XML schema for defining
object/relational mapping metadata.
The latest version of the specification is JSR 317: Java Persistence 2.0. See
http://jcp.org/en/jsr/detail?id=317.
Some of the EclipseLink extensions to standard JPA are:
Support for mapping to nonrelational (NoSQL) databases.
Features useful in Software as a Service (SaaS) environments, including tenant
isolation, extensible entities, external metadata sources.
Java API for RESTful Web Services (JAX-RS, defined in JSR 311).
Understanding EclipseLink
1-2 Understanding EclipseLink
Many other additional annotations, annotation extensions, Java Persistence
Query Language (JPQL) extensions, JPA query customizations extensions, and
persistence property extensions.
I Java Architecture for XML Binding (JAXB)
JAXB is the Java API for object/XML mapping (OXM), where an XML document is
bound to Java objects, based on the XML document's XSD schema. JAXB provides
methods for unmarshalling (reading) XML instance documents into Java content
trees, and then marshalling (writing) Java content trees back into XML instance
documents. JAXB also provides a way to generate XML schema from Java objects.
The latest version of the specification is JSR 222: Java Architecture for XML Binding
(JAXB) 2.0. See http://jcp.org/en/jsr/detail?id=222. J
In addition to the implementations of the standard specifications described above,
EclipseLink includes the following:
I EclipseLink Database Web Services (DBWS)
DBWS is a development tool and a runtime for providing Java EE-compliant,
client-neutral access to relational database artifacts via a Web service. The
development tool, DBWS Builder, is a command-line utility that generates the
necessary deployment artifacts. (DBWS Builder is integrated into the Eclipse Dali
Java Persistence toolset and into Oracle JDeveloper.) The runtime provider takes a
service descriptor (along with related deployment artifacts) and realizes it as a
JAX-WS 2.0 Web service. The runtime uses EclipseLink to bridge between the
database and the XML SOAP Messages used by Web service clients.
I EclipseLink Enterprise Information Services (EIS)
EIS is a facility for enabling the use of data stores through Java Connector
Architecture (JCA) resource adapters. Using XML metadata, the interactions and
their exchanged data are configured and mapped onto a domain model. The
interactions data can be mapped from either the Common Client interface (CCI) or
using XML schemas. This use is intended for non-relational data stores where no
JDBC or SQL access is provided.
EclipseLink can be used with a wide range of Java Enterprise Edition (Java EE) and
Java application architectures. Use EclipseLink to design, implement, deploy, and
optimize an advanced, object-persistence and object-transformation layer that
supports a variety of data sources and formats, including relational databases,
nonrelational (NoSQL) databases, XML, JSON, and Web Services.
EclipseLink supports Java persistence in Java EE, Java SE and web containers
including integration with various application servers including:
I Oracle WebLogic Server
I Oracle Glassfish Server
I JBoss Web Server
Note: The EclipseLink JAXB implementation is part of the
EclipseLink MOXy component, which extends EclipseLink JAXB to
support JavaScript Object Notation (JSON) documents. EclipseLink
supports all object/XML options when reading and writing JSON.
MOXy also includes support for the older native EclipseLink
object/XML API).
Understanding EclipseLink
Overview of EclipseLink 1-3
I IBM WebSphere application server
I SAP NetWeaver
I Oracle Containers for Java EE (OC4J)
I Various other web containers, such as Apache Tomcat, Eclipse Gemini, IBM
WebSphere CE, and SpringSource Server
EclipseLink lets you quickly capture and define object-to-data source and
object-to-data representation mappings in a flexible, efficient metadata format.
The runtime lets your application exploit this mapping metadata with a simple session
facade that provides in-depth support for data access, queries, transactions (both with
and without an external transaction controller), and caching.
For more information about EclipseLink, see "Key Features" on page 1-4.
1.1.1 What Is the Object-Persistence Impedance Mismatch?
Java-to-data source integration is a widely underestimated problem when creating
enterprise Java applications. This complex problem involves more than simply reading
from and writing to a data source. The data source elements include tables, rows,
columns, and primary and foreign keys. The Java and Java EE programming
languages include entity classes (regular Java classes), business rules, complex
relationships, and inheritance. In a nonrelational data source, you must match your
Java entities with XML elements and schemas.
A successful solution requires bridging these different technologies and solving the
object-persistence impedance mismatcha challenging and resource-intensive
problem. To solve this problem, you must resolve the following issues between Java
EE and the data source elements:
I Fundamentally different technologies
I Different skill sets
I Different staff and ownership for each of the technologies
I Different modeling and design principles
As an application developer, you need a product that lets you integrate Java
applications with any data source, without compromising application design or data
integrity. In addition, as a Java developer, you need the ability to store (that is, persist)
and retrieve business domain objects using a relational database or a nonrelational
data source as a repository.
1.1.2 The EclipseLink Solution
EclipseLink addresses the disparity between Java objects and data sources. It contains
a persistence framework that lets you build applications that combine the best aspects
of object technology with a specific data source. You can do the following:
I Persist Java objects to virtually any relational database
I Perform in-memory conversions between Java objects and XML and JSON
documents
I Map any object model to any relational or nonrelational schema
I Use EclipseLink successfully, even if you are unfamiliar with SQL or JDBC,
because EclipseLink offers a clear, object-oriented view of data sources
Key Features
1-4 Understanding EclipseLink
1.2 Key Features
An extensive set of features are provided. You can use these features to rapidly build
high-performance enterprise applications that are scalable and maintainable.
Some of the primary features are the following:
I Nonintrusive, flexible, metadata-based architecture
I Advanced mapping support and flexibility: relational, object-relational data type,
and XML
I Optimized for highly scalable performance and concurrency with extensive
performance tuning options
I Comprehensive object caching support including cluster integration for some
application servers (such as Oracle Fusion Middleware Server)
I Extensive query capability including: Java Persistence Query Language (JPQL),
native SQL, and EclipseLink Expressions framework
I Just-in-time reading
I Object-level transaction support and integration with popular application servers
and databases
I Optimistic and pessimistic locking options and locking policies
For additional information and downloads, see the EclipseLink home page:
http://www.eclispe.org/eclipselink/
1.3 New Features
The following sections provide a brief overview of new features in EclipseLink.
I RESTful Services
I Tenant Isolation
I NoSQL
I JSON
I Database Change Notification
I Extensible Entities
I Composite Persistence Units
I External Metadata Sources
1.3.1 RESTful Services
EclipseLink allows you to expose JPA entities through a standards-based
(JAX-RS/JAXB/JPA) RESTful service. REST is an acronym for Representational State
Transfer, which is a design idiom that embraces a stateless client-server architecture.
In this architecture, Web services are viewed as resources which can be identified by
their URIs.
Basic HTTP operations, such as create (POST), read (GET), update (PUT), and delete
(DELETE) can be called on the services.
Data in RESTful services are referenced using a URI. A URI can be constructed in
different ways, depending on the target, for example:
New Features
Overview of EclipseLink 1-5
I URI for JPA entities with a single-part primary key
I URI for JPA entities with composite keys
I URI with mapped named read queries
I URI for name update and delete queries
Clients can interact with the RESTful service in any of these ways:
I By using a web browser as the client
I By using Java SE as the client
I By using implementation-specific APIs
For more information, see "Exposing JPA Entities Through RESTful Services" in
Solutions Guide for EclipseLink.
1.3.2 Tenant Isolation
EclipseLink simplifies the development of application components that offer support
for multiple tenants. Developers and deployers have complete control of the
application and data isolation they require. Each tenant has access to its own data,
while other tenants data is invisible to it.
EclipseLink provides these options for tenant isolation:
I Single-table tenant isolation allows tenants to share tables. Each tenant has its own
rows, identified by discriminator columns, and those rows are invisible to other
tenants.
I With table-per-tenant tenant isolation, each tenant has its own table or tables,
identified by table tenant discriminators, and those tables are invisible to other
users.
I With Virtual Private Database (VPD) tenant isolation, tenants use a VPD database,
which provides the functionality to support multiple tenants sharing the same
table.
For more information, see "Using Tenant Isolation" in Solutions Guide for EclipseLink.
1.3.3 NoSQL
NoSQL is a classification of database systems that do not support the SQL standard.
The NoSQL classification can be expanded to include Enterprise Information Systems
(EIS) including application databases, legacy databases, messaging systems, and
transaction processing monitors. EclipseLink supports persistence of Java objects to
NoSQL databases through the Java Persistence API (JPA). EclipseLink's native API is
also supported with NoSQL databases.
NoSQL maps objects to structured data such as XML or JSON. It also supports
embedded data, embedded collections, and all of the existing JPA mapping
annotations.
Whether querying is supported in NoSQL depends on the NoSQL platform you are
using. The JPA transaction API is supported with NoSQL data-sources. Some NoSQL
data-sources might not support transactions, so the level of transaction support is
dependent on the NoSQL platform.
For more information, see Chapter 12, "Understanding Non-relational Data Sources."
See also "Using EclipseLink with NoSQL Databases" in Solutions Guide for EclipseLink.
New Features
1-6 Understanding EclipseLink
1.3.4 JSON
JavaScript Object Notation (JSON) is a text-based open standard designed for
human-readable data interchange. It is derived from the JavaScript scripting language
for representing simple data structures and associative arrays. It is
language-independent, with parsers available for many languages.
JAXB binding metadata is used to marshall Java objects to and from JSON. This
feature is useful when creating RESTful services; JAX-RS services can accept both XML
and JSON messages.
For more information on JSON support, see "Developing JAXB Applications Using
EclipseLink MOXy."
1.3.5 Database Change Notification
A shared (L2) object cache reduces database access for objects and their relationships.
This cache is enabled by default which is normally not a problem, unless the contents
of the database are modified directly by other applications, or by the same application
on other servers in a clustered environment. This may result in stale data in the cache.
If the contents of the database are modified, then EclipseLink Database Change
Notification (DCN) ensures that the contents of the cache are synchronized with the
database. DCN allows shared caching to be used in the JPA environment.
See "Using Caching with a Shared Database in a JPA Environment" in Solutions Guide
for EclipseLink.
1.3.6 Extensible Entities
Extensible entities allow mappings to be added dynamically. In this case, the entity
stores extended attributes within a map instead of static attributes. The entity then
defines how values from this map are mapped to the database using an
eclipselink-orm.xml mapping file. Extensible entities are useful in a multi-tenant
(or SaaS) architecture where a shared, generic application can be used by multiple
clients (tenants). Tenants have private access to their own data, and to data shared
with other tenants.
Using extensible entities, you can:
I Build an application where some mappings are common to all users and some
mappings are user-specific.
I Add mappings to an application after it is made available to a customer (even
post-deployment).
I Use the same EntityManagerFactory interface to work with data after
mappings have changed.
I Provide an additional source of metadata to be used by an application.
For more information on making entities extensible, see "Providing Software as a
Service" in Solutions Guide for EclipseLink.
1.3.7 Composite Persistence Units
You can expose multiple persistence units (each with unique sets of entity types) as a
single persistence context by using a composite persistence unit. Individual
persistence units that are part of this composite persistence unit are called composite
member persistence units. For more information, see "Using Multiple Databases with a
Composite Persistence Unit" in Solutions Guide for EclipseLink.
Key Concepts
Overview of EclipseLink 1-7
1.3.8 External Metadata Sources
You can store your mapping information in a metadata source that is external to the
running application. Because the mapping information is retrieved when the
application creates the persistence unit, you can dynamically override or extend
mappings in a deployed application. See "Using an External Metadata Source" in
Solutions Guide for EclipseLink.
1.4 Key Concepts
This section provides a brief introduction to several of the key concepts described in
this documentation. The key concepts highlighted in this section are as follows:
I EclipseLink Metadata
I Entities
I Descriptors
I Mappings
I Data Access
I Caching
I Queries
I Expression Framework
I NoSQL Databases
I Performance Monitoring and Profiling
1.4.1 EclipseLink Metadata
EclipseLink metadata is the bridge between the development of an application and its
deployed runtime environment. You can capture the metadata using:
I JPA annotations in Java files and the JPA-defined properties in the
persistence.xml, eclipselink-orm.xml, and orm.xml files.
Metadata is also captured by EclipseLink JPA annotations and property extensions
in the persistence.xml file. The eclipselink-orm.xml file can also be used
to specify property extensions beyond the JPA specification.
I JAXB annotations in Java files and JAXB-defined properties in the
eclipselink-oxm.xml file.
The eclipselink-oxm.xml file can be used to define property extensions
beyond the JAXB specification.
I Java and the EclipseLink API.
The metadata lets you pass configuration information into the runtime environment.
The runtime environment uses the information in conjunction with the persistent
classes, such as Java objects, JPA entities, and the code written with the EclipseLink
API, to complete the application. See "Adding Metadata Using Annotations" on
page 2-3 for more information. See also Java Persistence API (JPA) Extensions Reference
for EclipseLink.
Mappings can be stored external to the application. This can be as simple as making
the eclipselink-orm.xml or eclipselink-oxm.xml file with the additional
mapping information available on a web server as a file. It can also be more complex
involving a server process that stores the mapping information and allows the
Key Concepts
1-8 Understanding EclipseLink
information to be updated dynamically. For more information, see
"EclipseLink/Examples/JPA/MetadataSource" in the EclipseLink documentation.
http://wiki.eclipse.org/EclipseLink/Examples/JPA/MetadataSource
1.4.2 Entities
An entity is a persistence domain object. Typically, an entity represents a table in a
relational database, and each entity instance corresponds to a row in the table. The
primary programming artifact of an entity is the entity class, although entities can use
helper classes.
The persistent state of an entity is represented either through persistent fields or
persistent properties. These fields or properties use object/relational mapping
annotations to map the entities and entity relationships to the relational data in the
underlying data store.
See Chapter 4, "Understanding Entities."
1.4.3 Descriptors
Descriptors describe how a Java class relates to a data source representation. They
relate object classes to the data source at the data model level. For example, persistent
class attributes may map to database columns.
EclipseLink uses descriptors to store the information that describes how an instance of
a particular class can be represented in a data source. Descriptors are used internally
by EclipseLink, and are defined through annotations, XML, or in IDEs such as
JDeveloper or Eclipse, then read at run time.
See Chapter 6, "Understanding Descriptors."
1.4.4 Mappings
Mappings describe how individual object attributes relate to a data source
representation. Mappings can involve a complex transformation or a direct entry.
EclipseLink uses mappings to determine how to transform data between object and
data source representations. Mappings are used internally by EclipseLink, and are
defined through annotations, XML, or in IDEs such as Eclipse, then read from the
project XML file at run time.
See Chapter 7, "Understanding Mappings."
1.4.5 Data Access
A data source platform includes options specific to a particular data source including
binding, use of native SQL, use of batch writing, and sequencing.
See Chapter 8, "Understanding Data Access."
1.4.6 Caching
The EclipseLink cache is an in-memory repository that stores recently read or written
objects based on class and primary key values. The cache is used to improve
performance by avoiding unnecessary trips to the database, manage locking and cache
isolation level, and manage object identity.
See Chapter 9, "Understanding Caching."
Key Components
Overview of EclipseLink 1-9
1.4.7 Queries
You can to create, read, update, and delete persistent objects or data using queries in
both Java EE and non-Java EE applications for both relational and nonrelational data
sources. Queries can be made at the object level or data level.
A number of query languages are supported, such as Java Persistence Query
Language (JPQL), SQL, and the Expression Framework. The Java Persistence Criteria
API can also be used to define dynamic queries through the construction of
object-based query definition objects, rather than use of the string-based approach of
JPQL.
See Chapter 10, "Understanding Queries."
1.4.8 Expression Framework
By using the EclipseLink Expressions framework, you can specify query search criteria
based on your domain object model. Expressions offer a number of advantages over
SQL. For example, expressions are easier to maintain, changes to descriptors or
database tables do not affect the querying structures in the application, they enhance
readability by standardizing the Query interface, and they simplify complex
operations.
See Chapter 11, "Understanding EclipseLink Expressions."
1.4.9 NoSQL Databases
NoSQL is a classification of database systems that do not support the SQL standard.
These include document databases, key-value stores, and various other non-standard
databases. Persistence of Java objects to NoSQL databases is supported through the
Java Persistence API (JPA). EclipseLink's native API is also supported with NoSQL
databases.
See Chapter 12, "Understanding Non-relational Data Sources."
1.4.10 Performance Monitoring and Profiling
A diverse set of features is provided to measure and optimize application
performance. You can enable or disable most features in the descriptors or session,
making any resulting performance gains global. Tools are provided for performance
profiling and performance, fetch group, and query monitoring.
See Chapter 13, "Understanding Performance Monitoring and Profiling."
1.5 Key Components
1.5.1 EclipseLink Core and API
The EclipseLink Core provides the runtime component. Access to the runtime can be
obtained directly through the EclipseLink API. The runtime environment is not a
separate or external processit is embedded within the application. Application calls
invoke EclipseLink to provide persistence behavior. This function enables
transactional and thread-safe access to shared database connections and cached
objects.
Key Components
1-10 Understanding EclipseLink
The EclipseLink API provides the reference implementation for JPA 2.0 (JSR-317). The
org.eclipse.persistence.* classes encapsulate the EclipseLink API and provide
extensions beyond the specification. These extensions include EclipseLink-specific
properties and annotations. For more information on the API, properties and
extensions, see Java Persistence API (JPA) Extensions Reference for EclipseLink.
The JAXB APIs are included in Java SE 6. In the eclipselink.jar file, the
org.eclipse.persistence.jaxb.* classes encapsulate the EclipseLink support
for JAXB.
1.5.2 Object-Relational (JPA 2.0) Component
JPA simplifies Java persistence. It provides an object-relational mapping approach that
lets you declaratively define how to map Java objects to relational database tables in a
standard, portable way. JPA works both inside a Java EE application server and
outside an EJB container in a Java Standard Edition (Java SE) application. The main
features included in the 2.0 JPA update are:
I Expanded object/relational mapping functionality
Support for collections of embedded objects
Multiple levels of embedded objects
Ordered lists
Combinations of access types
I A criteria query API
I Standardization of query "hints"
I Standardization of additional metadata to support DDL generation
I Support for validation
1.5.3 Object-XML (JAXB 2.2) Component
Object-XML, also known as MOXy, is an EclipseLink component that enables you to
bind Java classes to XML schemas. Object-XML implements JAXB which lets you
provide mapping information through annotations. Support for storing the mappings
in XML format is provided by MOXy. The many advanced mappings that are
available enable you to handle complex XML structures without having to mirror the
schema in your Java class model.
The objects produced by the EclipseLink JAXB compiler are Java POJO models. They
are generated with the necessary annotations required by the JAXB specification. The
JAXB runtime API can be used to marshal and unmarshal objects.
When using Object-XML as the JAXB provider, no metadata is required to convert
your existing object model to XML. You can supply metadata (using annotations or
XML) only when you must fine-tune the XML representation of the model.
Using EclipseLink Object-XML, you can manipulate XML in the following ways:
I Generate a Java Model from an XML schema
I Specify the EclipseLink MOXy JAXB runtime
I Use JAXB to manipulate XML
I Generate an XML schema from a Java model
Key Components
Overview of EclipseLink 1-11
For more information on Object-XML and these use cases, see Developing JAXB
Applications Using EclipseLink MOXy.
EclipseLink provides maximum flexibility with the ability to control how your object
model is mapped to an XML schema. There are many advantages to having control
over your own object model:
I You can design the domain classes specifically for your application using the
appropriate patterns and practices.
I You can use XPath-based mapping. This prevents the need for having a 1-to-1
relationship between classes and XML schema types. For more information, see
Developing JAXB Applications Using EclipseLink MOXy.
I You can instantiate objects in a way that is appropriate to your application.
I You can control your own class path dependencies. Most JAXB implementations
put vendor specific code in the generated classes that add class path dependencies
to your application.
One of the key advantages of EclipseLink is that the mapping information can be
stored externally and does not require any changes to the Java classes or XML schema.
This means that you can map your domain objects to more than one schema, or if your
schema changes, you can update the mapping metadata instead of modifying your
domain classes. This is also useful when mapping third-party classes, because you
might not have access to the source to add annotations.
1.5.3.1 SDO Component
The Service Data Objects (SDO) component provides the reference implementation of
Service Data Objects version 2.1.1. The reference implementation is described in
JSR-235. The SDO implementation incorporates the reference implementation and
provides additional features primarily used for converting Java objects to XML, and
for building and using data object models that can be incorporated into service
architectures.
SDO provides you with the following capabilities:
I Use of the SDO APIs
I Conversion an XML Schema
I Customization of your XSD for SDO usage
I Use of dynamic data objects to manipulate XML
I Use of static data objects
Run the SDO compilergenerate type safe data objects
Use type safe data objects to manipulate XML
For more information, see "Getting Started with EclipseLink SDO" in the EclipseLink
documentation:
http://www.eclipse.org/eclipselink/moxy.php
1.5.4 Database Web Services Component
Database Web Services (DBWS) enables simple and efficient access to relational
database artifacts by using a web service. It provides Java EE-compliant client-neutral
access to the database without having to write Java code. DBWS extends EclipseLinks
core capabilities while using existing ORM and OXM components.
Key Tools
1-12 Understanding EclipseLink
DBWS has a runtime provider component that takes a service descriptor (along with
related deployment artifacts) and realizes it as a JAX-WS 2.0 Web service. The runtime
provider uses EclipseLink to bridge between the database and the XML SOAP
Messages used by web service clients. For information on DBWS architecture, see
Developing Persistence Architectures Using EclipseLink.
1.6 Key Tools
This section describes the support for EclipseLink provided by Oracle JDeveloper,
Eclipse, and NetBeans development environments. Any tooling is compatible with
EclipseLink, but these offer specific integration.
This section contains the following subsections:
I Oracle JDeveloper
I Eclipse
I NetBeans
1.6.1 Oracle JDeveloper
Oracle JDeveloper is a Java EE development environment with end-to-end support to
develop, debug, and deploy e-business applications and web services.
For JDeveloper information and downloads, see:
http://www.oracle.com/us/products/tools/019657.htm
JDeveloper includes a number of features to aid in the development of applications
that use EclipseLink. These features include wizards to reverse engineer JPA entities
from database tables and to generate EJB 3.0 Session Beans with EntityManager
injection. It also includes methods for querying JPA entities and to test client
generation.
JDeveloper tools enable you to quickly and easily configure and map your Java classes
and JPA entities to different data sources, including relational databases and XML
schemas without using code.
DBWSBuilder script (included in EclipseLink install) can be used to run the
DBWSBuilder utility to generate the Web service. JDeveloper uses the API provided,
but does not use the DBWSBuilder script directly.
For more information on Oracle JDeveloper's EclipseLink support, see JDeveloper
online help.
1.6.2 Eclipse
The Eclipse IDE provides a number of features and utilities to help you create, run,
and maintain applications that use JPA. These capabilities are extended if you install
OEPE.
For Eclipse IDE information and downloads, see:
http://www.oracle.com/technetwork/developer-tools/eclipse/overvi
ew/index.html
The Dali Java Persistence Tools Project provides extensible frameworks and tools for
defining and editing object-relational mappings for JPA entities. JPA mapping support
focuses on minimizing the complexity of mapping by providing entity generation
Key Tools
Overview of EclipseLink 1-13
wizards, design-time validation, and a robust UI for entity and persistence unit
configuration.
For Dali information and downloads, see:
http://www.eclipse.org/webtools/dali
Other tools and utilities from the Oracle, open source, and third party vendor
communities are available from the Eclipse Marketplace.
http://marketplace.eclipse.org/
1.6.3 NetBeans
NetBeans IDE bundles Oracle GlassFish Server, which includes EclipseLink. The IDE
provides full support for JPA-based code development. This support includes entity
class wizards for constructing entities and editor hints to ensure that entities conform
to the JPA specification. NetBeans also provides a persistence unit editor for
constructing a persistence.xml file.
For NetBeans information and downloads, see:
http://netbeans.org/index.html
Key Tools
1-14 Understanding EclipseLink
2
Understanding Mappings 2-1
2Understanding Mappings
This chapter describes the items that can be used in Object-Relational and Object-XML
mapping.
This chapter contains the following sections:
I About Object-Relational Mapping
I About Object-XML Mapping
2.1 About Object-Relational Mapping
EclipseLink provides a complete, JPA-compliant JPA implementation. It provides
complete compliance for all of the mandatory features and many of the optional
features. It also supports EclipseLink features not described in the JPA specification,
such as object-level cache, distributed cache coordination, extensive performance
tuning options, enhanced Oracle Database support, advanced mappings, optimistic
and pessimistic locking options, extended annotations, and query hints.
For more information, see Java Persistence API (JPA) Extensions Reference for EclipseLink.
The following sections describe many of these features.
I Understanding Object-Relational Entity Architecture
I Adding Metadata Using Annotations
I About Configuration Basics
I About Data Sources
I About EclipseLink Caches
I About Database Queries
2.1.1 Understanding Object-Relational Entity Architecture
The entity architecture is composed of entities, persistence units, persistence contexts,
entity manager factories, and entity managers. Figure 21 illustrates the relationships
between these elements:
I Persistence creates one or more EntityManagerFactory objects.
I Each EntityManagerFactory is configured by one persistence unit.
I EntityManagerFactory creates one or more EntityManager objects.
I One or more EntityManagers manage one PersistenceContext.
About Object-Relational Mapping
2-2 Understanding EclipseLink
Figure 21 Relationships Between Entity Architecture Elements
2.1.1.1 Entities
An entity is any application-defined object with the following characteristics:
I It can be made persistent.
I It has a persistent identity (a key that uniquely identifies an entity instance and
distinguishes it from other instances of the same entity type. An entity has a
persistent identity when there is a representation of it in a data store).
I It is transactional in a sense that a persistence view of an entity is transactional (an
entity is created, updated, and deleted within a transaction, and a transaction is
required for the changes to be committed in the database). However, in-memory
entities can be changed without the changes being persisted.
I It is not a primitive, a primitive wrapper, or built-in object. An entity is a
fine-grained object that has a set of aggregated states that is typically stored in a
single place (such as a row in a table) and have relationships to other entities.
The entity also contains entity metadata that describes the entity. Entity metadata is
not persisted to the database. It is used by the persistence layer to manage the entity
from when it is loaded until it is invoked at runtime. Metadata can be expressed as
annotations on the Java programming elements or in XML files (descriptors). For more
information, see Chapter 4, "Understanding Entities."
Beginning with the current release, you can define and use extensible entities where
mappings can be added spontaneously. In this case, the entity stores extended
attributes within a map instead of static attributes. The entity then defines how values
from this map are mapped to the database using an eclipselink-orm.xml
mapping file. In addition to being able to dynamically define mappings, EclipseLink
also enables these extended mappings to be stored and managed externally. This
external storage enables your extended mappings to be defined while the application
is running. For more information on making entities extensible, see "Providing
Software as a Service" in Solutions Guide for EclipseLink.
2.1.1.2 Persistence and Persistence Units
Persistence is a characteristic of an entity. This means that the entity can be represented
in a data store, and it can be accessed at a later time.
A persistence unit identifies a persistable unit and defines the properties associated
with it. It also defines the objects that must be persisted. The objects can be entity
classes, embeddable classes, or mapped superclasses. The persistence unit provides
About Object-Relational Mapping
Understanding Mappings 2-3
the configuration for the entity manager factory. Entity managers created by the entity
manager factory inherit the properties defined in the persistence unit.
2.1.1.3 Entity Managers
An entity manager enables API calls to perform operations on an entity. Until an entity
manager is used to create, read, or write an entity, the entity is a nonpersistent Java
object. When an entity manager obtains a reference to an entity, that entity becomes
managed by the entity manager. The set of managed entity instances within an entity
manager at any given time is called its persistence context; only one Java instance with
the same persistent identity can exist in a persistence context at any time.
You can configure an entity manager to read or write to a particular database, to
persist or manage certain types of objects, and to be implemented by a specific
persistence provider. The persistence provider supplies the implementation for JPA,
including the EntityManager interface implementation, the Query implementation,
and the SQL generation.
Entity managers are provided by an EntityManagerFactory. The configuration for
an entity manager is bound to the EntityManagerFactory, but it is defined
separately as a persistence unit. You name persistence units to enable differentiation
between EntityManagerFactory objects. This way, your application obtains control
over which configuration to use for operations on a specific entity. The configuration
that describes the persistence unit is defined in a persistence.xml file. You name
persistence units to be able to request a specific configuration to be bound to an
EntityManagerFactory.
2.1.2 Adding Metadata Using Annotations
An annotation is a simple, expressive means of decorating Java source code with
metadata that is compiled into the corresponding Java class files for interpretation at
run time by a JPA persistence provider to manage persistent behavior.
A metadata annotation represents a Java language feature that lets you attach
structured and typed metadata to the source code. Annotations alone are sufficient for
the metadata specificationyou do not need to use XML. Standard JPA annotations
are in the javax.persistence package.
For more information, see Chapter 10 "Metadata Annotations" in the JPA Specification
http://jcp.org/en/jsr/detail?id=317
EclipseLink provides a set of proprietary annotations as an easy way to add metadata
to the Java source code. The metadata is compiled into the corresponding Java class
files for interpretation at run time by a JPA persistence provider to manage persistent
behavior. You can apply annotations at the class, method, and field levels.
EclipseLink annotations expose some features that are currently not available through
the use of JPA metadata:
I Basic propertiesBy default, the EclipseLink persistence provider automatically
configures a basic mapping for simple types. Use these annotations to fine-tune
the immediate state of an entity in its fields or properties.
I RelationshipsEclipseLink has defaults for some relationships, such as
One-To-One and One-To-Many. Other relationships must be mapped explicitly.
Use the annotations to specify the type and characteristics of entity relationships
and to fine-tune how your database implements these relationships.
I Embedded objectsAn embedded object does not have its own persistent
identity; it is dependent upon an entity for its identity. By default, the persistence
About Object-Relational Mapping
2-4 Understanding EclipseLink
provider assumes that every entity is mapped to its own table. Use the following
annotations to override this behavior for entities that are owned by other entities.
2.1.2.1 Advantages and Disadvantages of Using Annotations
Using annotations provides several advantages:
I They are relatively simple to use and understand.
I They provide in-line metadata within with the code that it describes; you do not
need to replicate the source code context of where the metadata applies.
The primary disadvantage of annotations is that the metatdata becomes unnecessarily
coupled to the code; changes to metadata require changing and recompiling the source
code.
2.1.3 About Configuration Basics
The following sections describe some of the key configuration files in an Object
Relational Mapping project.
2.1.3.1 Default Configuration Values
Each annotation has a default value (consult the JPA specification for defaults). A
persistence engine defines defaults that apply to the majority of applications. You only
need to supply values when you want to override the default value. Therefore, having
to supply a configuration value is not a requirement, but the exception to the rule. This
is known as configuration by exception.
The default values are described in Java Persistence API (JPA) Extensions Reference for
EclipseLink. See also Chapter 10, "Metadata Annotations" in the JPA specification.
http://jcp.org/en/jsr/detail?id=317
The configuration is done by exception: if a value is not specified in one of the
configuration files, then a default value is used.
2.1.3.2 Configuring Persistence Units Using persistence.xml
A persistence unit defines the details that are required when you acquire an entity
manager. You specify a persistence unit by name when you acquire an entity manager
factory. Use the JPA persistence file, persistence.xml, to configure a persistence
unit. You can specify any vendor-specific extensions in the file by using a
<properties> element.
This file appears in the META-INF/ directory of your persistence unit JAR file or in the
classpath.
For more information, see Section 5.2, "About the Persistence Unit." See also
"Persistence Property Extensions Reference" in Java Persistence API (JPA) Extensions
Reference for EclipseLink.
2.1.3.3 Object-Relational Data Type Mappings
Object-relational data type mappings transform certain object data member types to
structured data source representations optimized for storage in specialized
Note: You should be familiar with the defaults to be able to change
the behavior when necessary.
About Object-Relational Mapping
Understanding Mappings 2-5
object-relational databases such as Oracle Database. Object-relational data type
mappings let you map an object model into an object-relational model. You can use
only object-relational data type mappings with specialized object-relational databases
optimized to support object-relational data type data source representations.
For more information, see Java Persistence API (JPA) Extensions Reference for EclipseLink.
2.1.3.3.1 Specifying Object-Relational Mappings Using orm.xml Use the orm.xml file to
apply the metadata to the persistence unit. This metadata is a union of all the mapping
files and the annotations (if there is no xml-mapping-metadata-complete
element). If you use one mapping orm.xml file for your metadata and place this file in
a META-INF directory on the classpath, then you do not need to explicitly list it. The
persistence provider will automatically search for this file (orm.xml) and use it.
The schema for the JPA 2.0 orm.xml is orm_2_0.xsd. (http://java.sun.
com/xml/ns/persistence/orm_2_0.xsd)
If you use a different name for your mapping files or place them in a different location,
you must list them in the mapping-file element of the persistence.xml file.
2.1.3.3.2 Specifying EclipseLink Object-Relational Mappings Using eclipselink-orm.xml The
standard JPA orm.xml file applies metadata to the persistence unit. It provides
support for all of the JPA 2.0 mappings. You can use this file instead of annotations or
to override JPA annotations in the source code. The eclipselink-orm.xml file
supports the mappings defined by the orm.xml file and the full set of EclipseLink
extensions beyond JPA 2.0. Any settings that you make in the eclipselink-orm.
xml file will override settings in the orm.xml file.
For more information on the eclipselink-orm.xml file, see "eclipselink-orm.xml
Schema Reference" in Java Persistence API (JPA) Extensions Reference for EclipseLink.
For more information, on overriding values, see:
I "XML Overriding Rules" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
I The schema for eclipselink-orm.xml is eclipselink_orm_2_2.xsd:
http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_2.
xsd
2.1.3.4 Overriding and Merging Mapping Information
To override the orm.xml file's mapping, you must define the
META-INF/eclipselink-orm.xml file in the project. When both orm.xml and
eclipselink-orm.xml are specified, the contents of eclipselink-orm.xml
override orm.xml and any other JPA mapping file specified in the persistence unit. If
there are overlapping specifications in multiple ORM files, the files are merged if there
are no conflicting entities.
For more information, see "Overriding and Merging" in Java Persistence API (JPA)
Extensions Reference for EclipseLink.
Note: Using this mapping file enables many EclipseLink advanced
features, but it may prevent the persistence unit from being portable
to other JPA implementations.
About Object-Relational Mapping
2-6 Understanding EclipseLink
2.1.3.5 Validating the XML Schema
By default the content of your .orm XML file is not validated against the JPA .orm
XML schema.
During development it is a good idea to validate your .orm XML file against the
schema to ensure it is valid. In EclipseLink, validating the .orm XML schema can be
enabled using the persistence unit property "eclipselink.orm.validate.
schema" in your persistence.xml file.
2.1.3.6 Advantages and Disadvantages of Using XML
Some advantages of using XML instead of annotations include:
I No coupling between the metadata and the source code
I Compliance with the existing, pre-EJB 3.0 development process
I Support in IDEs and source control systems
The main disadvantages of mapping with XML include:
I It is inherently complex (when compared to annotations)
I The need for replication of the code context (that is, defining the structure in both
the XML and the source code)
For more information, see Chapter 10 "Metadata Annotations" in the JPA Specification:
http://jcp.org/en/jsr/detail?id=317
2.1.4 About Data Sources
An important part of the definition of the persistence unit is the location where the
provider can find data to read and write. This is called the data source. The data
source is typically a database. The database location is specified in the form of a JDBC
data source in the JNDI namespace of the server.
Typically, applications that use EclipseLink are run in the context of a JTA transaction.
Specify the name of the data source in the jta-data-source element in the
persistence.xml file. If the application is not run in the context of a transaction,
then it is considered to be resource-local. In this case, specify the name of the data
source in the non-jta-data-source element.
You can also specify a non-relational database data source, such as an XML schema.
For more information, see Chapter 8, "Understanding Data Access."
Applications can be run in standalone, or Java SE, mode. In this mode, the application
runs outside the server, with a non-JTA compliant data source, and in a non-Oracle
stack. In this case, you must provide driver-specific information, such as the JDBC
driver class, the URL that the client uses to connect to the database, and the user name
and password to access the database. For more information and an example of running
an application in standalone mode, see "Testing EclipseLink JPA Outside a Container"
in Solutions Guide for EclipseLink.
2.1.5 About EclipseLink Caches
By default, EclipseLink uses a shared object cache that caches a subset of all objects
read and persisted for the persistence unit. The shared cache differs from the local
EntityManager cache. The shared cache exists for the duration of the persistence
unit (EntityManagerFactory or server) and is shared by all EntityManagers and
About Object-Relational Mapping
Understanding Mappings 2-7
users of the persistence unit. The local EntityManager cache is not shared and only
exists for the duration of the EntityManager or transaction.
The benefit of the shared cache is that after an object is read, the database does not
need to be accessed if the object is read again. Also, if the object is read by using a
query, it does not need to be rebuilt, and its relationships do not need to be fetched
again.
The limitation of the shared cache is that if the database is changed directly through
JDBC, or by another application or server, the objects in the shared cache will be stale.
EclipseLink offers several mechanism to deal with stale data including:
I Refreshing
I Invalidation
I Optimistic locking
I Cache coordination
I Database Change Notification (DCN)
The shared cache can also be disabled, or it can be selectively enabled and disabled by
using the @Cache or @Cacheable annotations.
EclipseLink also offers several different caching strategies, to configure how many
objects are cached and how much memory is used.
If the application detects that the cache is out of date, it can clear, refresh, or invalidate
it programmatically. Clearing the cache can cause object identity issues if any of the
cached objects are in use, so invalidating is safer. If you know that none of the cached
objects are in use, then you can clear the cache.
For more information, see Chapter 9, "Understanding Caching."
2.1.5.1 Defining Cache Behavior
EclipseLink provides an @Cache annotation which lets you define cache properties.
The properties include cache type, size, and refresh rules, among others. See Java
Persistence API (JPA) Extensions Reference for EclipseLink.
2.1.5.2 Caching in Clustered Environments
Caching in a clustered environment can have problems because changes made on one
server are not reflected on objects cached in other servers. This is not a problem for
read-only objects, but it is for objects that are frequently updated.
EclipseLink offers several solutions to this problem.
I The cache can be disabled for the classes that frequently change.
I Cache coordination can be used to broadcast changes between the servers in the
cluster to update or invalidate changed objects.
I Cache invalidation based on time-to-live or time-of-day.
I Optimistic locking prevents updates to stale objects and triggers the objects to be
invalidated in the cache.
For more information, see Section 9.11.4, "Coordinated Cache and Clustering".
2.1.6 About Database Queries
The object-relational component of EclipseLink supports a variety of queries.
About Object-XML Mapping
2-8 Understanding EclipseLink
I JPQL queries
I SQL queries
I Criteria API queries
I Native SQL queries
I EclipseLink JPA query hints
I Query casting
I Oracle Extensions for queries
I Advanced EclipseLink native queries
For information on these queries, see Chapter 10, "Understanding Queries."
2.2 About Object-XML Mapping
The Object-XML component, supplied by EclipseLink, enables you to efficiently bind
Java classes to XML schemas. Object-XML implements JAXB, enabling you to provide
your mapping information through annotations and providing support for storing the
mappings in XML format.
JAXB (Java Architecture for XML BindingJSR 222) is the standard for XML Binding
in Java. JAXB covers 100 percent of XML Schema concepts. EclipseLink provides a
JAXB implementation with many extensions.
When using EclipseLink Object-XML as the JAXB provider, no metadata is required to
convert your existing object model to XML. You can supply metadata (using
annotations or XML) if you want to fine-tune the XML representation.
Object-XML includes many advanced mappings that let you handle complex XML
structures without having to mirror the schema in your Java class model.
For more information, see Developing JAXB Applications Using EclipseLink MOXy.
The following sections describe many of these features.
I Using EclipseLink Object-XML as the JAXB Provider
I Understanding Object-XML Architecture
I Serving Metadata for Object-XML
I About XML Bindings
I Specifying EclipseLink Object-XML Mappings Using eclipselink-oxm.xml
I Querying Objects by XPath
2.2.1 Using EclipseLink Object-XML as the JAXB Provider
To use Object-XML as your JAXB provider, you must identify the entry point to the
JAXB runtime. This entry point is the EclipseLink JAXBContextFactory class.
Create a text file called jaxb.properties and enter the path to the
JAXBContextFactory class as the value of the javax.xml.bind.context.
factory context parameter, for example:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
The jaxb.properties file must appear in the same package as the domain classes.
About Object-XML Mapping
Understanding Mappings 2-9
2.2.2 Understanding Object-XML Architecture
In the sample Object-XML architecture illustrated in Figure 22, the starting point is an
XML schema. A binding compiler binds the source schema to a set of schema-derived
program classes and interfaces. JAXB-annotated classes within the application are
generated either by a schema compiler or the result of a developer adding JAXB
annotations to existing Java classes. The application can either marshal data to an XML
document or unmarshal the data to a tree of content objects. Each content object is an
instance of either a schema derived or an existing program element mapped by the
schema generator and corresponds to an instance in the XML.
Figure 22 A Sample Object-XML Architecture
2.2.2.1 JAXB Contexts and JAXB Context Factories
The JAXBContextFactory class is the entry point into the EclipseLink JAXB
runtime. It provides the required factory methods and can create new instances of
JAXBContext objects.
The JAXBContextFactory class has the ability to:
I Create a JAXBContext object from an array of classes and a properties object
I Create a JAXBContext object from a context path and a classloader
The JAXBContext class provides the client's entry point to the JAXB API. The
JAXBContext class is responsible for interpreting the metadata, generating schema
files, and for creating instances of these JAXB objects: Marshaller, Unmarshaller,
Binder, Introspector, and Validator.
Object-XML offers several options when creating the JAXBContext object. You have
the option of booting from:
I A list of one or more JAXB-annotated classes
I A list of one or more EclipseLink XML Bindings documents defining the
mappings for your Java classes
I A combination of classes and XML Bindings
About Object-XML Mapping
2-10 Understanding EclipseLink
I A list of context paths
I A list of session names, referring to EclipseLink sessions defined in sessions.
xml
2.2.3 Serving Metadata for Object-XML
In addition to the input options described in Section 2.2.2.1, "JAXB Contexts and JAXB
Context Factories," Object-XML provides the concept of a MetadataSource object.
This object lets you to store mapping information outside of your application and
retrieve it when the application's JAXBContext object is being created or refreshed.
For information on implementing MetadataSource, see Developing JAXB Applications
Using EclipseLink MOXy.
2.2.4 About XML Bindings
EclipseLink enables you to use all of the standard JAXB annotations. In addition to the
standard annotations, EclipseLink offers another way of expressing your
metadatathe EclipseLink XML Bindings document. Not only can XML Bindings
separate your mapping information from your actual Java class, it can also be used for
more advanced metadata tasks such as:
I Augmenting or overriding existing annotations with additional mapping
information.
I Specifying all mappings information externally, without using Java annotations.
I Defining your mappings across multiple Bindings documents.
I Specifying virtual mappings that do not correspond to concrete Java fields.
For more information, see Developing JAXB Applications Using EclipseLink MOXy.
2.2.4.1 Specifying EclipseLink Object-XML Mappings Using eclipselink-oxm.xml
You can use Java annotations to specify JAXB features in your projects. In addition to
Java annotations, EclipseLink provides an XML mapping configuration file called
eclipselink-oxm.xml. This mapping file contains the standard JAXB mappings
and configuration options for advanced mapping types. You can use the
eclipselink-oxm.xml file in place of or to override JAXB annotations in source
code.
2.2.5 About Object-XML Data Type Mappings
XML mappings transform object data members to the XML elements of an XML
document whose structure is defined by an XML Schema Document (XSD). You can
map the attributes of a Java object to a combination of XML simple and complex types
using a wide variety of XML mapping types.
Classes are mapped to complex types, object relationships map to XML elements, and
simple attributes map to text nodes and XML attributes. The real power in using
Object-XML is that when mapping an object attribute to an XML document, XPath
statements are used to specify the location of the XML data.
Note: Using this mapping file will enable many advanced features
but it can prevent the model from being portable to other JAXB
implementations.
About Object-XML Mapping
Understanding Mappings 2-11
EclipseLink stores XML mappings for each class in the class descriptor. EclipseLink
uses the descriptor to instantiate objects mapped from an XML document and to store
new or modified objects as XML documents.
EclipseLink provides XML mappings that are not defined in the JAXB specification.
Some of the Object-XML extensions are available through EclipseLink annotations;
others require programmatic changes to the underlying metadata.
For more information on these mappings, see Developing JAXB Applications Using
EclipseLink MOXy.
2.2.6 Querying Objects by XPath
In addition to using conventional Java access methods to get and set your object's
values, EclipseLink Object-XML also lets you access values using an XPath statement.
There are special APIs on EclipseLinks JAXBContext object that enable you to get
and set values by XPath. For more information, see Developing JAXB Applications Using
EclipseLink MOXy.
About Object-XML Mapping
2-12 Understanding EclipseLink
3
Understanding Application Development 3-1
3Understanding Application Development
To ensure the best design for your application, Oracle recommends that you follow an
iterative step-by-step development process. The flexibility of EclipseLink lets you use
any development tool.
These sections describe recommended development processes:
I Typical Development Stages
I Target Platforms
I Building and Using the Persistence Layer
I About Application Deployment
I About Persisting Objects
I About Metadata
I About Weaving
3.1 Typical Development Stages
This section describes the general development stages for EclipseLink applications.
Figure 31 illustrates the development process.
Typical Development Stages
3-2 Understanding EclipseLink
Figure 31 EclipseLink Development Process
Design the Application (1)
Define your application requirements, select an architecture, and determine the target
platform. EclipseLink works with any architecture and any platform.
When designing the application, you should also create an object model for the
application. It is important to create the object model before mapping objects, because
defining persistent mappings for an incorrect or rapidly changing model can be very
difficult. See Section 3.5, "About Persisting Objects" for more information.
Develop the Application (2, 3, 4)
Create the Java classes and decide how the classes should be implemented by the data
source. When working with a legacy system, decide how the classes relate to the
existing data. If there is no legacy data source to integrate, decide how to store each
class in the data source and create the required schema. Alternatively, you can use
EclipseLink to create your initial tables.
Using a development tool such as JDeveloper, create descriptors and mappings for the
persistent classes. Use sessions to manipulate the persistent classes, including
querying and changing data. See Section 1.6, "Key Tools" for more information.
Avoid building all your model's descriptors in a single iteration. Start with a small
subset of your classes. Build and test their descriptors, then gradually add new
Building and Using the Persistence Layer
Understanding Application Development 3-3
descriptors and relationships. This lets you catch common problems before they
proliferate through your entire design.
Write Java code to use database sessions. Sessions are used to query for database
objects and write objects to the database.
Deploy the Application (5)
Generate, package, then deploy the necessary files to your application server. The
required information will vary, depending on your environment and architecture.
Maintain the Application (6)
EclipseLink includes many options that can enhance application performance. You can
customize most aspects of EclipseLink to suit your requirements. Use advanced
EclipseLink features or write custom querying routines to access the database in
specific ways, and to optimize performance.
3.2 Target Platforms
When you design your application, you must choose how and where to use
EclipseLink. You can perform a variety of persistence and data transformation
functions on a variety of Java-supported platforms. When you design your application
architecture, keep these capabilities in mind.
EclipseLink supports any enterprise architecture that uses Java, including the
following:
I Java EE
I Spring
I Java Web servers such as Tomcat
I Java clients such as Java SE and Web browsers
I Server Java platforms
Application packaging requirements of the specific target platform (for deployment in
the host Java or Java EE environment) influence how you use and configure
EclipseLink. For example, you package a Java EE application in an Enterprise Archive
(EAR) file. Within the EAR file, there are several ways to package persistent entities
within Web Archive (WAR) and Java Archive (JAR) files. How you configure
EclipseLink depends, in part, on how you package the application and how you use
the host application server class loader.
For detailed information about supported application server versions, custom
integration, and configuration requirements, see Section 5.1, "Integrating with an
Application Server.".
3.3 Building and Using the Persistence Layer
EclipseLink requires that classes must meet certain minimum requirements before they
can become persistent. EclipseLink also provides alternatives to most requirements.
EclipseLink uses a nonintrusive approach by employing a metadata architecture that
allows for minimal object model intrusions.
This section includes the following information:
I Implementation Options
I Persistent Class Requirements
Building and Using the Persistence Layer
3-4 Understanding EclipseLink
I Persistence Layer Components
3.3.1 Implementation Options
When implementing your persistence layer using EclipseLink, consider the following
options:
I Using EclipseLink JPA Metatdata, Annotations, and XML
I Using EclipseLink Metadata Java API
I Using Method and Direct Field Access
I Using Java Byte-code Weaving
3.3.1.1 Using EclipseLink JPA Metatdata, Annotations, and XML
When using JPA, you can specify persistence layer components using any combination
of standard JPA annotations and persistence.xml, EclipseLink JPA annotation
extensions, and EclipseLink JPA persistence.xml extensions.
For more information, see Section 2.1.3, "About Configuration Basics".
3.3.1.2 Using EclipseLink Metadata Java API
Persistence layer components may be coded or generated as Java. To use Java code,
you must manually write code for each element of the project including: project, login,
platform, descriptors, and mappings. This may be more efficient if your application is
model-based and relies heavily on code generation.
3.3.1.3 Using Method and Direct Field Access
You can access the fields (data members) of a class by using a getter/setter method
(also known as property access) or by accessing the field itself directly.
When to use method or direct field access depends on your application design.
Consider the following guidelines:
I Use method access outside of a class.
This is the natural public API of the class. The getter/setter methods handle any
necessary side-effects and the client need not know anything about those details.
I Use direct field access within a class to improve performance.
In this case, you are responsible for taking into consideration any side-effects not
invoked by bypassing the getter/setter methods.
When considering using method or direct field access, consider the following
limitations.
If you enable change tracking on a getter/setter method (for example, you decorate
method setPhone with @ChangeTracking), then EclipseLink tracks changes
accordingly when a client modifies the field (phone) using the getter/setter methods.
Similarly, if you enable change tracking on a field (for example, you decorate field
phone with @ChangeTracking), then EclipseLink tracks changes accordingly when a
client modifies the field (phone) directly.
However, if you enable change tracking on a getter/setter method (for example, you
decorate method setPhone with @ChangeTracking) and a client accesses the field
(phone) directly, EclipseLink does not detect the change. If you choose to code in this
style of field access within a class for performance and method access outside of a
class, then be aware of this limitation.
Building and Using the Persistence Layer
Understanding Application Development 3-5
For more information, see the description of the @ChangeTracking annotation in Java
Persistence API (JPA) Extensions Reference for EclipseLink
3.3.1.4 Using Java Byte-code Weaving
Weaving is a technique of manipulating the byte-code of compiled Java classes.
Weaving is used to enhance both JPA entities and Plain Old Java Object (POJO) classes
for such things as lazy loading, change tracking, fetch groups, and internal
optimizations.
For more information, see Section 3.7, "About Weaving".
3.3.2 Persistent Class Requirements
When you create persistent Java objects, use direct access on private or protected
attributes.
If you are using weaving, the ValueHolderInterface is not required. For more
information, see Section 3.7, "About Weaving." See Section 7.2.1, "Indirection (Lazy
Loading)" for more information on indirection and transparent indirection.
3.3.3 Persistence Layer Components
The purpose of your applications persistence layer is to use a session at run time to
associate mapping metadata and a data source (see Chapter 8, "Understanding Data
Access") to create, read, update, and delete persistent objects using the EclipseLink
cache, queries and expressions, and transactions.
Typically, the EclipseLink persistence layer contains the following components:
I Mapping Metadata
I Cache
I Queries and Expressions
3.3.3.1 Mapping Metadata
The EclipseLink application metadata model is based on the project. The project
includes descriptors, mappings, and various policies that customize the run-time
capabilities. You associate this mapping and configuration information with a
particular data source and application by referencing the project from a session.
For more information, see the following:
I Section 3.6.2, "Creating Project Metadata"
I Chapter 6, "Understanding Descriptors"
I Chapter 7, "Understanding Mappings"
3.3.3.2 Cache
By default, EclipseLink sessions provide an object-level cache that guarantees object
identity and enhances performance by reducing the number of times the application
needs to access the data source. EclipseLink provides a variety of cache options,
including locking, refresh, invalidation, isolation, and coordination. Using cache
coordination, you can configure EclipseLink to synchronize changes with other
instances of the deployed application. You configure most cache options at the
persistence unit or entity level. You can also configure cache options on a per-query
basis or on a descriptor to apply to all queries on the reference class.
About Application Deployment
3-6 Understanding EclipseLink
For more information, see Chapter 9, "Understanding Caching."
3.3.3.3 Queries and Expressions
For Object-relational architectures, EclipseLink provides several object and data query
types, and offers flexible options for query selection criteria, including the following:
I EclipseLink expressions
I JPQL (Java Persistence Query Language)
I SQL
I Stored procedures
I Query by example
With these options, you can build any type of query. Oracle recommends using named
queries to define application queries. Named queries are held in the project metadata
and referenced by name. This simplifies application development and encapsulates the
queries to reduce maintenance costs.
For Object-relational architectures, you are free to use any of the query options
regardless of the persistent entity type. Alternatively, you can build queries in code,
using the EclipseLink API.
For more information, see Chapter 10, "Understanding Queries" and Chapter 11,
"Understanding EclipseLink Expressions."
3.4 About Application Deployment
Application packaging (for deployment in the host Java or Java EE environment)
influences EclipseLink use and configuration. For example, you package a Java EE
application in an EAR file. Within the EAR file, there are several ways to package
persistent entities within WAR and JAR files. How you configure EclipseLink depends,
in part, on how you package the application and how you use the class loader of the
host application server.
The EclipseLink approach to deployment involves packaging application files into a
single file, such as a JAR or an EAR file. This approach lets you create clean and
self-contained deployments that do not require significant file management. After
creating these files, deploy the project.
For more information, see Chapter 5, "Understanding Application Deployment."
3.5 About Persisting Objects
This section includes a brief description of relational mapping and provides
information and restrictions to guide object and relational modeling. This information
is useful when building applications.
This section includes information on the following:
I Application Object Model
I Data Storage Schema
Note: These query techniques cannot be used with Object-XML
(OXM, JAXB) mapping. However you can perform queries when
using legacy EIS XML projects.
About Persisting Objects
Understanding Application Development 3-7
I Primary Keys and Object Identity
I Mappings
I Foreign Keys and Object Relationships
I Inheritance
I Concurrency
I Caching
I Nonintrusive Persistence
I Indirection
I Mutability
3.5.1 Application Object Model
Object modeling refers to the design of the Java classes that represent your application
objects. You can use your favorite integrated development environment (IDE) or
Unified Modeling Language (UML) modeling tool to define and create your
application object model.
Any class that registers a descriptor with EclipseLink database sessions is called a
persistent class. EclipseLink does not require that persistent classes provide public
accessor methods for any private or protected attributes stored in the database. Refer
to Section 3.3.2, "Persistent Class Requirements" for more information.
3.5.2 Data Storage Schema
Your data storage schema refers to the design that you implement to organize the
persistent data in your application. This schema refers to the data itselfnot the actual
data source (such as a relational database or nonrelational legacy system).
During the design phase of the application development process, you should decide
how to implement the classes in the data source. When integrating existing data source
information, you must determine how the classes relate to the existing data. If no
legacy information exists to integrate, decide how you will store each class, then create
the necessary schema. For more information, see Section 3.1, "Typical Development
Stages."
3.5.3 Primary Keys and Object Identity
When making objects persistent, each object requires an identity to uniquely identify it
for storage and retrieval. Object identity is typically implemented using a unique
primary key. This key is used internally by EclipseLink to identify each object, and to
create and manage references. Violating object identity can corrupt the object model.
In a Java application, object identity is preserved if each object in memory is
represented by one, and only one, object instance. Multiple retrievals of the same
object return references to the same object instancenot multiple copies of the same
object.
EclipseLink supports multiple identity maps to maintain object identity (including
composite primary keys). See Section 9.2, "About Cache Type and Size" for additional
information.
About Persisting Objects
3-8 Understanding EclipseLink
3.5.4 Mappings
EclipseLink uses metadata to describe how objects and beans map to the data source.
This approach isolates persistence information from the object modelyou are free to
design their ideal object model, and DBAs are free to design their ideal schema. For
more information, see Section 3.6, "About Metadata".
At run time, EclipseLink uses the metadata to seamlessly and dynamically interact
with the data source, as required by the application.
EclipseLink provides an extensive mapping hierarchy that supports the wide variety
of data types and references that an object model might contain. For more information,
see Chapter 7, "Understanding Mappings."
3.5.5 Foreign Keys and Object Relationships
A foreign key can be one or more columns that reference a unique key, usually the
primary key, in another table. Foreign keys can be any number of fields (similar to
primary key), all of which are treated as a unit. A foreign key and the primary parent
key it references must have the same number and type of fields.
Foreign keys represents relationships from a column or columns in one table to a
column or columns in another table. For example, if every Employee has an attribute
address that contains an instance of Address (which has its own descriptor and table),
the one-to-one mapping for the address attribute would specify foreign key
information to find an address for a particular Employee.
3.5.6 Inheritance
Object-oriented systems allow classes to be defined in terms of other classes. For
example: motorcycles, sedans, and vans are all kinds of vehicles. Each of the vehicle
types is a subclass of the Vehicle class. Similarly, the Vehicle class is the superclass of
each specific vehicle type. Each subclass inherits attributes and methods from its
superclass (in addition to having its own attributes and methods).
Inheritance provides several application benefits, including the following:
I Using subclasses to provide specialized behaviors from the basis of common
elements provided by the superclass. By using inheritance, you can reuse the code
in the superclass many times.
I Implementing abstract superclasses that define generic behaviors. This abstract
superclass may define and partially implement behavior, while allowing you to
complete the details with specialized subclasses.
3.5.7 Concurrency
To have concurrent clients logged in at the same time, the server must spawn a
dedicated thread of execution for each client. Java EE application servers do this
automatically. Dedicated threads enable each client to work without having to wait for
the completion of other clients. EclipseLink ensures that these threads do not
interfere with each other when they make changes to the identity map or perform
database transactions.
Your client can make transactional changes in an isolated and thread safe manner.
EclipseLink manages clones for the objects you modify to isolate each clients work
from other concurrent clients and threads. This is essentially an object-level transaction
mechanism that maintains all of the ACID (Atomicity, Consistency, Isolation,
Durability) transaction principles as a database transaction.
About Persisting Objects
Understanding Application Development 3-9
EclipseLink supports configurable optimistic and pessimistic locking strategies to let
you customize the type of locking that the EclipseLink concurrency manager uses.
For more information, see Section 6.2.4, "Descriptors and Locking."
3.5.8 Caching
EclipseLink caching improves application performance by automatically storing data
returned as objects from the database for future use. This caching provides several
advantages:
I Reusing Java objects that have been previously read from the database minimizes
database access
I Minimizing SQL calls to the database when objects already exist in the cache
I Minimizing network access to the database
I Setting caching policies a class-by-class and bean-by-bean basis
I Basing caching options and behavior on Java garbage collection
EclipseLink supports several caching polices to provide extensive flexibility. You can
fine-tune the cache for maximum performance, based on individual application
performance. Refer to Chapter 9, "Understanding Caching" for more information.
3.5.9 Nonintrusive Persistence
The EclipseLink nonintrusive approach of achieving persistence through a metadata
architecture means that there are almost no object model intrusions.
To persist Java objects, EclipseLink does not require any of the following:
I Persistent superclass or implementation of persistent interfaces
I Store, delete, or load methods required in the object model
I Special persistence methods
I Generating source code into or wrapping the object model
See Section 3.3, "Building and Using the Persistence Layer" for additional information
on this nonintrusive approach. See also Section 3.6, "About Metadata."
3.5.10 Indirection
An indirection object takes the place of an application object so the application object is
not read from the database until it is needed. Using indirection, or lazy loading in JPA,
allows EclipseLink to create stand-ins for related objects. This results in significant
performance improvements, especially when the application requires the contents of
only the retrieved object rather than all related objects.
Without indirection, each time the application retrieves a persistent object, it also
retrieves all the objects referenced by that object. This may result in lower performance
for some applications.
EclipseLink provides several indirection models, such as proxy indirection,
transparent indirection, and value holder indirection.
Note: Oracle strongly recommends that you always use indirection.
About Metadata
3-10 Understanding EclipseLink
See Section 7.1.3, "Using Lazy Loading" and Section 7.2.1, "Indirection (Lazy Loading)"
for more information.
3.5.11 Mutability
Mutability is a property of a complex field that specifies whether the field value may
be changed or not changed as opposed to replaced.
An immutable mapping is one in which the mapped object value cannot change unless
the object ID of the object changes: that is, unless the object value is replaced by
another object value altogether.
A mutable mapping is one in which the mapped object value can change without
changing the object ID of the object.
By default, EclipseLink assumes the following:
I all TransformationMapping instances are mutable
I all JPA @Basic mapping types, except Serializable types, are immutable
(including Date and Calendar types)
I all JPA @Basic mapping Serializable types are mutable
Whether a value is immutable or mutable largely depends on how your application
uses your persistent classes. For example, by default, EclipseLink assumes that a
persistent field of type Date is immutable: this means that as long as the value of the
field has the same object ID, EclipseLink assumes that the value has not changed. If
your application uses the set methods of the Date class, you can change the state of the
Date object value without changing its object ID. This prevents EclipseLink from
detecting the change. To avoid this, you can configure a mapping as mutable: this tells
EclipseLink to examine the state of the persistent value, not just its object ID.
You can configure the mutability of the following:
I TransformationMapping instances;
I any JPA @Basic mapping type (including Date and Calendar types) individually;
I all Date and Calendar types.
Mutability can affect change tracking performance. For example, if a transformation
mapping maps a mutable value, EclipseLink must clone and compare the value in a
unit of work. If the mapping maps a simple immutable value, you can improve unit of
work performance by configuring the mapping as immutable.
Mutability also affects weaving. EclipseLink can only weave an attribute change
tracking policy for immutable mappings.
For more information, see Section 3.7, "About Weaving". See also the description of the
@Mutable annotation in Java Persistence API (JPA) Extensions Reference for EclipseLink.
3.6 About Metadata
The EclipseLink metadata is the bridge between the development of an application
and its deployed run-time environment. Capture the metadata using the following:
I Annotations, persistence.xml, orm.xml, eclipselink-orm.xml,
eclipselink-oxm.xml, and annotation and persistence.xml property extensions.
The persistence provider interprets all these sources of metadata to create an
in-memory session and project at run time.
I Java and the EclipseLink API (this approach is the most labor-intensive).
About Metadata
Understanding Application Development 3-11
The metadata lets you pass configuration information into the run-time environment.
The run-time environment uses the information in conjunction with the persistent
classes (Java objects or entities) and the code written with the EclipseLink API, to
complete the application.
For more information, see "Overriding and Merging" in Java Persistence API (JPA)
Extensions Reference for EclipseLink.
Figure 32 EclipseLink Metadata
This section describes the following:
I Advantages of the Metadata Architecture
I Creating Project Metadata
I Creating Session Metadata
3.6.1 Advantages of the Metadata Architecture
The EclipseLink metadata architecture provides many important benefits, including
the following:
I Stores mapping information in XMLnot in the domain model objects
I By using the metadata, EclipseLink does not intrude in the object model or the
database schema
I Allows you to design the object model as needed, without forcing any specific
design
I Allows DBAs to design the database as needed, without forcing any specific
design
I Does not rely on code-generation (which can cause serious design,
implementation, and maintenance issues)
I Is unobtrusive: adapts to the object model and database schema, rather than
requiring you to design their object model or database schema to suit EclipseLink
Using EclipseLink JPA, you have the flexibility of expressing persistence metadata
using standard JPA annotations, deployment XML, or both and you can optionally
take advantage of EclipseLink JPA annotation and persistence.xml property
extensions.
3.6.2 Creating Project Metadata
A project contains the mapping metadata that the EclipseLink runtime uses to map
objects to a data source. The project is the primary object used by the EclipseLink
runtime.
About Metadata
3-12 Understanding EclipseLink
This section describes the principal contents of project metadata, including the
following:
I Descriptors and Mappings
I Data Source Login Information
For Object-relational mapping, the EclipseLink runtime constructs an in-memory
project based on any combination of JPA annotations, persistence.xml, orm.xml, and
EclipseLink JPA annotation and persistence.xml property extensions.
For Object-XML mapping, the EclipseLink runtime uses a combination of JAXB
annotations and eclipselink-oxm bindings. See "Overriding and Merging" in Java
Persistence API (JPA) Extensions Reference for EclipseLink.
3.6.2.1 Descriptors and Mappings
EclipseLink maps persistent entities to the database in the application, using the
descriptors and mappings you build with JDeveloper. These tools support several
approaches to project development, including the following:
I Importing classes and tables for mapping
I Importing classes and generating tables and mappings
I Importing tables and generating classes and mappings
I Creating both class and table definitions
The most common solution is to develop the persistent entities using a development
tool, such as a modeling tool or an integrated development environment (IDE) like
JDeveloper, and to develop the relational model through appropriate relational design
tools. You then use JDeveloper to construct mappings that relate these two models.
Although JDeveloper offers the ability to generate persistent entities or the relational
model components for an application, these utilities are intended only to assist in
rapid initial development strategiesnot complete round-trip application
development.
For more information, see Chapter 6, "Understanding Descriptors" and Chapter 7,
"Understanding Mappings".
3.6.2.2 Data Source Login Information
For POJO projects, you configure a session login in the session metadata that specifies
the information required to access the data source.
For more information, see Section 3.6.3, "Creating Session Metadata."
3.6.3 Creating Session Metadata
A EclipseLink session contains the information required to access the data source. The
session is the primary object used by your application to access the features of the
EclipseLink runtime.
Using EclipseLink JPA, the EclipseLink runtime constructs an in-memory session
based on any combination of JPA annotations, persistence.xml, orm.xml, and
EclipseLink JPA annotation and persistence.xml property extensions. The use of a
sessions.xml file is optional. See "Overriding and Merging" in Java Persistence API
(JPA) Extensions Reference for EclipseLink.
About Weaving
Understanding Application Development 3-13
3.7 About Weaving
Weaving is a technique of manipulating the byte-code of compiled Java classes. The
EclipseLink JPA persistence provider uses weaving to enhance both JPA entities and
Plain Old Java Object (POJO) classes for such things as lazy loading, change tracking,
fetch groups, and internal optimizations.
Weaving can be performed either dynamically at runtime, when entities are loaded, or
statically at compile time by post-processing the entity .class files. By default,
EclipseLink uses dynamic weaving whenever possible, including inside a Java EE
application server and in Java SE when the EclipseLink agent is configured. Dynamic
weaving is recommended as it is easy to configure and does not require any changes to
a project's build process.
This section describes the following:
I Using Dynamic Weaving
I Using Static Weaving
I Weaving POJO Classes
I Weaving and Java EE Application Servers
I Disabling Weaving with Persistence Unit Properties
3.7.1 Using Dynamic Weaving
Use dynamic weaving to weave application class files one at a time, as they are loaded
at run time. Consider this option when the number of classes to weave is few or when
the time taken to weave the classes is short.
If the number of classes to weave is large or the time required to weave the classes is
long, consider using static weaving.
3.7.2 Using Static Weaving
Use static weaving to weave all application class files at build time so that you can
deliver prewoven class files. Consider this option to weave all applicable class files at
build time so that you can deliver prewoven class files. By doing so, you can improve
application performance by eliminating the runtime weaving step required by
dynamic weaving.
In addition, consider using static weaving to weave in Java environments where you
cannot configure an agent.
3.7.3 Weaving POJO Classes
EclipseLink uses weaving to enable the following for POJO classes:
I Lazy loading
I Change tracking
I Fetch groups
EclipseLink weaves all the POJO classes in the JAR you create when you package a
POJO application for weaving.
EclipseLink weaves all the classes defined in the persistence.xml file, that is:
I All the classes you list in the persistence.xml file.
About Weaving
3-14 Understanding EclipseLink
I All classes relative to the JAR containing the persistence.xml file if element
<exclude-unlisted-classes> is false.
3.7.4 Weaving and Java EE Application Servers
The default EclipseLink weaving behavior applies in any Java EE JPA-compliant
application server using the EclipseLink JPA persistence provider.To change this
behavior, modify your persistence.xml file (for your JPA entities or POJO classes) to
use EclipseLink JPA properties, EclipseLink JPA annotations, or both.
3.7.5 Disabling Weaving with Persistence Unit Properties
To disable weaving using EclipseLink persistence unit properties, configure your
persistence.xml file with one or more of the following properties set to false:
I eclipse.weaving; disables all weaving
I eclipselink.weaving.lazy; disables weaving for lazy loading (indirection)
I eclipselink.weaving.changetracking; disables weaving for change tracking
I eclipselink.weaving.fetchgroups; disables weaving for fetch groups
I eclipselink.weaving.internal; disables weaving for internal optimization
I eclipselink.weaving.eager; disables weaving for indirection on eager
relationships
4
Understanding Entities 4-1
4Understanding Entities
An entity is a lightweight persistence domain object. Typically, an entity represents a
table in a relational database, and each entity instance corresponds to a row in the
table. The primary programming artifact of an entity is the entity class, although
entities can use helper classes.
The persistent state of an entity is represented either through persistent fields or
persistent properties. These fields or properties use object/relational mapping
annotations to map the entities and entity relationships to the relational data in the
underlying data store.
You can configure your entity's identity, as well as the locking technique and sequence
generation options for your entity.
This chapter contains the following sections:
I Identifying Entities
I Entities and Persistent Identity
I Entities and Database Tables
I Entities and Inheritance
I Entities and Embedded Objects
I Entities and Sequence Generation
I Entities and Locking
4.1 Identifying Entities
Use the @Entity annotation to specify that a class is an entity.
For more information, see Chapter 2 "Entities" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
4.2 Entities and Persistent Identity
Every entity must have a persistent identity, which is an equivalent of a primary key in
a database table that stores the entity state.
Note: The entity class must also be listed in your persistence.xml
file, unless you set the tag <exclude-unlisted-classes> to false. An
entity can also be defined using an orm.xml file and the <entity> tag.
Entities and Database Tables
4-2 Understanding EclipseLink
By default, the EclipseLink persistence provider assumes that each entity has at least
one field or property that serves as a primary key.
You can generate and/or configure the identity of your entities by using the following
annotations:
I @Id
I @IdClass
I @EmbeddedId
I @GeneratedValue
I @TableGenerator
I @SequenceGenerator
I @UuidGenerator
You can also use these annotations to fine-tune how your database maintains the
identity of your entities. For more information on these annotations, see "Metadata for
Object/Relational Mapping" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
4.3 Entities and Database Tables
Every entity class maps to a specific table or set of tables in the database. By default,
the entity's table name is defaulted as its entity name as uppercase, which defaults to
the entity's short class name. An entity normally maps to a single table, but can also
map to multiple tables, or even a view.
You can customize an entity's tables using the following annotations:
I @Table
I @SecondaryTable
4.4 Entities and Inheritance
JPA defines several difference methods for persisting objects with inheritance. The
@Inheritance annotation is used in the root class to define SINGLE_TABLE, JOINED,
and TABLE_PER_CLASS inheritance. For abstract classes that define common state or
persistence behavior, but have no relationship on the database, the @MappedSuperclass
annotation can be used.
I @Inheritance
I @MappedSuperclass
4.5 Entities and Embedded Objects
You can use the @Embeddable annotation to map an embedded class. An embeddable is
a special type of class that is not directly persistent, but persisted only with its parent
entity. An embeddable can be referenced from an entity or another embeddable using
the @Embedded annotation for a single reference, @EmbeddedId for an embedded id, or
the @ElementCollection annotation for a Collection or Map reference. An
embeddable can also be used in any Map key using the @MapKeyClass annotation.
I @Embeddable
I @EmbeddedId
Entities and Locking
Understanding Entities 4-3
I @Embedded
I @ElementCollection
4.6 Entities and Sequence Generation
Many databases support an internal mechanism for id generation called sequences.
You can use a database sequence to generate identifiers when the underlying database
supports them.
I @SequenceGeneratorIf you use the @GeneratedValue annotation to specify a
primary key generator of type SEQUENCE, then you can use the
@SequenceGenerator annotation to fine-tune this primary key generator to do the
following:
change the allocation size to match your application requirements or database
performance parameters
change the initial value to match an existing data model (for example, if you
are building on an existing data set for which a range of primary key values
has already been assigned or reserved)
use a predefined sequence in an existing data model
I @TableGeneratorIf you use the @GeneratedValue annotation to specify a
primary key generator of type TABLE, then you can use the @TableGenerator
annotation to fine-tune this primary key generator to do the following:
change the name of the primary key generator's table, because the name is
awkward, a reserved word, incompatible with a preexisting data model, or
invalid as a table name in your database
change the allocation size to match your application requirements or database
performance parameters
change the initial value to match an existing data model (for example, if you
are building on an existing data set, for which a range of primary key values
has already been assigned or reserved)
configure the primary key generator's table with a specific catalog or schema
configure a unique constraint on one or more columns of the primary key
generator's table
For more information and examples of these annotations, see "Metadata for
Object/Relational Mapping" in the JPA Specification.
4.7 Entities and Locking
You have the choice between optimistic and pessimistic locking. Oracle recommends
using optimistic locking. For more information, see Section 6.2.4, "Descriptors and
Locking."
By default, the EclipseLink persistence provider assumes that the application is
responsible for data consistency.
Use the @Version annotation to enable JPA-managed optimistic locking by specifying
the version field or property of an entity class that serves as its optimistic lock value
(recommended).
When choosing a version field or property, ensure that the following is true:
I there is only one version field or property per entity
Entities and Locking
4-4 Understanding EclipseLink
I you choose a property or field persisted to the primary table (see "Table
Annotation" in the JPA Specification)
I your application does not modify the version property or field
The @Version annotation does not have attributes.
For more information, see the following:
I "Optimistic Locking and Concurrency" in the JPA Specification
http://jcp.org/en/jsr/detail?id=317
I "Version Annotation" in the JPA Specification
http://jcp.org/en/jsr/detail?id=317
I EclipseLink JPA extensions for optimistic locking described in Java Persistence API
(JPA) Extensions Reference for EclipseLink
For more information on the EclipseLink artifacts configured by JPA metadata, see
Section 6.2.4, "Descriptors and Locking".
Note: The field or property type must either be a numeric type (such
as Number, long, int, BigDecimal, and so on), or a
java.sql.Timestamp. Oracle recommends using a numeric type.
5
Understanding Application Deployment 5-1
5Understanding Application Deployment
Packaging means assembling all parts of the application in a way that can be correctly
interpreted and used by the infrastructure when the application is deployed into an
application server or run in a stand-alone JVM.
For more information, see Chapter 6 "Entity Packaging" in the JPA Specification:
http://jcp.org/en/jsr/detail?id=317
This chapter contains the following sections:
I Integrating with an Application Server
I About the Persistence Unit
I Integrating Clustering
5.1 Integrating with an Application Server
This section describes concepts unique to application server integration, including the
following:
I Software Requirements
I Setting Security Permissions
I Migrating Applications to the EclipseLink Persistence Manager
5.1.1 Software Requirements
To run EclipseLink applications within a Java EE container, your system must meet the
following software requirements:
I An application server or Java EE container
I XML parser
I A JDBC driver configured to connect with your local database system (for more
information, see your database administration documentation);
I Any of the following:
Any Java environment that is compatible with the Sun JDK 1.6 or later;
A command-line JVM executable (such as java.exe or jre.exe).
5.1.2 Setting Security Permissions
By default, when you run applications in a JVM configured with a nondefault java.
lang.SecurityManager, the runtime environment executes certain internal functions
About the Persistence Unit
5-2 Understanding EclipseLink
by executing a PrivilegedAction with java.security.AccessController method
doPrivileged. This ensures that you do not need to grant many permissions to
EclipseLink for it to perform its most common operations. You need only grant certain
permissions depending on the types of optional features you use.
If you run EclipseLink-enabled applications in a JVM without a nondefault
SecurityManager, you do not need to set any permissions. For more information, see
"Using Oracle EclipseLink with the Oracle Database" in Solutions Guide for EclipseLink.
5.1.3 Migrating Applications to the EclipseLink Persistence Manager
You can configure an application server to use EclipseLink as the persistence manager.
You can use only one persistence manager for all of the entities with container-
managed persistence in a JAR file.
5.2 About the Persistence Unit
A persistence unit defines the details that are required when you acquire an entity
manager. To package your EclipseLink JPA application, you must configure the
persistence unit during the creation of the persistence.xml file. Define each
persistence unit in a persistence-unit element in the persistence.xml file.
Use the persistence.xml file to package your entities. Once you chose a packaging
strategy, place the persistence.xml file in the META-INF directory of the archive of
your choice. The following sections provide more detail on how to specify the
persistence unit. For more information and examples, see "persistence.xml file" in the
JPA Specification. For information on EclipseLink extensions to the persistence.xml
file, see "Persistence Property Extensions Reference" in Java Persistence API (JPA)
Extensions Reference for EclipseLink.
I About the Persistence Unit Name
I About the Transaction Type, Persistence Provider and Data Source
I About Mapping Files
I About Managed Classes
I About Vendor Properties
I About the Deployment Classpath
I About Persistence Unit Packaging Options
I About the Persistence Unit Scope
5.2.1 About the Persistence Unit Name
If you are developing your application in a Java EE environment, ensure that the
persistence unit name is unique within each module. For example, you can define only
one persistence unit with the name EmployeeService in an emp_ejb.jar file.
For more information, see "name" in the JPA Specification.
5.2.2 About the Transaction Type, Persistence Provider and Data Source
If you are developing your application in a Java EE environment, accept the default
transaction type: JTA, and for the persistence provider setting, set the persistence
provider in a provider element. Specify the data source in a jta-data-source
element.
About the Persistence Unit
Understanding Application Deployment 5-3
For more information, see "transaction-type" and "provider" in the JPA Specification.
5.2.3 About Mapping Files
Apply the metadata to the persistence unit. This metadata is a union of all the
mapping files and the annotations (if there is no xml-mapping-metadata-complete
element). If you use one mapping orm.xml file for your metadata, and place this file in
a META-INF directory on the classpath, then you do not need to explicitly list it, because
the EclipseLink persistence provider will automatically search for this file and use it. If
you named your mapping files differently or placed them in a different location, then
you must list them in the mapping-file elements in the persistence.xml file.
For more information, see "mapping-file, jar-file, class, exclude-unlisted-classes" in the
JPA Specification
5.2.4 About Managed Classes
Typically, you put all of the entities and other managed classes in a single JAR file,
along with the persistence.xml file in the META-INF directory, and one or more
mapping files (when you store metadata in XML).
At the time the EclipseLink persistence provider processes the persistence unit, it
determines which set of entities, mapped superclasses, and embedded objects each
particular persistence unit will manage.
At deployment time, the EclipseLink persistence provider may obtain managed classes
from any of the following sources. A managed class will be included if it is one of the
following:
I Local classes: the classes annotated with @Entity, @MappedSuperclass or
@Embeddable in the deployment unit in which its persistence.xml file was
packaged. For more information, see "Entity" in the JPA Specification.
I Classes in mapping files: the classes that have mapping entries, such as entity (see
"entity" in the JPA Specification), mapped-superclass or embeddable, in an XML
mapping file. For more information, see "mapped-superclass" and "embeddable"
in the JPA Specification.
If these classes are in the deployed component archive, then they will already be
on the classpath. If they are not, you must explicitly include them in the classpath.
I Explicitly listed classes: the classes that are listed as class elements in the
persistence.xml file.
Consider listing classes explicitly if one of the following applies:
I there are additional classes that are not local to the deployment unit JAR. For
example, there is an embedded object class in a different JAR that you want to
use in an entity in your persistence unit. You would list the fully qualified
Note: If you are deploying your application in the Java EE
environment, the application server itself, not the EclipseLink
persistence provider, will discover local classes. In the Java SE
environment, you can use the exclude-unlisted-classes element to
false to enable this functionalityEclipseLink persistence provider
will attempt to find local classes if you set this element to false. See
"mapping-file, jar-file, class, exclude-unlisted-classes" in the JPA
Specification.
About the Persistence Unit
5-4 Understanding EclipseLink
class in the class element in the persitence.xml file. You would also need to
ensure that the JAR or directory that contains the class is on the classpath of
the deployed component (by adding it to the manifest classpath of the
deployment JAR, for example);
I you want to exclude one or more classes that may be annotated as an entity.
Even though the class may be annotated with the @Entity annotation, you do
not want it treated as an entity in this particular deployed context. For
example, you may want to use this entity as a transfer object and it needs to be
part of the deployment unit. In this case, in the Java EE environment, you have
to use the exclude-unlisted-classes element of the persistence.xml
filethe use of the default setting of this element prevents local classes from
being added to the persistence unit. For more information, see "mapping-file,
jar-file, class, exclude-unlisted-classes" of the JPA Specification.
I you plan to run your application in the Java SE environment, and you list your
classes explicitly because that is the only portable way to do so in Java SE.
I Additional JAR files of managed classes: the annotated classes in a named JAR file
listed in a jar-file element in the persistence.xml file. For more information, see
"mapping-file, jar-file, class, exclude-unlisted-classes" in the JPA Specification.
You have to ensure that any JAR file listed in the jar-file element is on the classpath
of the deployment unit. Do so by manually adding the JAR file to the manifest
classpath of the deployment unit.
Note that you must list the JAR file in the jar-file element relative to the parent of
the JAR file in which the persistence.xml file is located. This matches what you
would put in the classpath entry in the manifest file.
5.2.5 About Vendor Properties
The last section in the persistence.xml file is the properties section. The properties
element gives you the chance to supply EclipseLink persistence provider-specific
settings for the persistence unit. See "properties" in the JPA Specification. see also
"Persistence Property Extensions Reference" in Java Persistence API (JPA) Extensions
Reference for EclipseLink.
5.2.6 About the Deployment Classpath
To be accessible to the EJB JAR, WAR, or EAR file, a class or a JAR file must be on the
deployment classpath. You can achieve this in one of the following ways:
I Put the JAR file in the manifest classpath of the EJB JAR or WAR file.
To do this, add a classpath entry to the META-INF/MANIFEST.MF file in the JAR or
WAR file. You can specify one or more directories or JAR files, separating them by
spaces.
I Place the JAR file in the library directory of the EAR file.
This will make the JAR file available on the application classpath and accessible by
all of the modules deployed within the EAR file. By default, this would be the lib
directory of the EAR file, although you may configure it to be any directory in the
EAR file using the library-directory element in the application.xml
deployment descriptor.
Integrating Clustering
Understanding Application Deployment 5-5
5.2.7 About Persistence Unit Packaging Options
Java EE allows for persistence support in a variety of packaging configurations. You
can deploy your application to the following module types:
I EJB modules: you can package your entities in an EJB JAR. When defining a
persistence unit in an EJB JAR, the persistence.xml file is not optionalyou must
create and place it in the META-INF directory of the JAR alongside the deployment
descriptor, if it exists.
I Web modules: you can use WAR file to package your entities. In this case, place
the persistence.xml file in the WEB-INF/classes/META-INF directory. Since the
WEB-INF/classes directory is automatically on the classpath of the WAR, specify
the mapping file relative to that directory.
I Persistence archives: a persistence archive is a JAR that contains a persistence.
xml file in its META-INF directory and the managed classes for the persistence unit
defined by the persistence.xml file. Use a persistence archive if you want to allow
multiple components in different Java EE modules to share or access a persistence
unit.
Once you created a persistence archive, you can place it in either the root or the
application library directory of the EAR. Alternatively, you can place the
persistence archive in the WEB-INF/lib directory of a WAR. This will make the
persistence unit accessible only to the classes inside the WAR, but it enables the
decoupling of the definition of the persistence unit from the web archive itself.
For more information, see "Persistence Unit Packaging" in the JPA Specification.
5.2.8 About the Persistence Unit Scope
You can define any number of persistence units in single persistence.xml file. The
following are the rules for using defined and packaged persistence units:
I Persistence units are accessible only within the scope of their definition.
I Persistence units names must be unique within their scope.
For more information, see "Persistence Unit Scope" in the JPA Specification.
5.3 Integrating Clustering
Most application servers include a clustering service that you can use with your
EclipseLink application.
To use EclipseLink with an application server cluster, use this general procedure:
1. Install the eclipselink.jar file (and include it in the classpath) on each
application server in the cluster to which you deploy EclipseLink applications.
2. Configure the cache consistency options appropriate for your application.
For more information, see Chapter 9, "Understanding Caching."
3. Configure the coordinated cache support for your application server, if available.
For more information, see Chapter 9, "Understanding Caching."
4. Configure clustering on each application server.
For more information, see your application server documentation.
Integrating Clustering
5-6 Understanding EclipseLink
6
Understanding Descriptors 6-1
6Understanding Descriptors
EclipseLink uses descriptors to store the information that describes how an instance of
a particular class can be represented by a data source. Descriptors own mappings that
associate class instance variables with a data source and transformation routines that
are used to store and retrieve values. As such, the descriptor acts as the connection
between a Java object and its data source representation.
This chapter includes the following sections:
I Common Descriptor Concepts
I Object-Relational Descriptor Concepts
I Object-XML Descriptor Concepts
I Descriptor API
6.1 Common Descriptor Concepts
The following sections describe the concepts that are common to Object-Relational and
Object-XML descriptors.
I Descriptor Architecture
I Descriptors and Inheritance
I Descriptors and Aggregation
I Descriptor Customization
I Amendment and After-Load Methods
I Descriptor Event Manager
6.1.1 Descriptor Architecture
A descriptor stores all the information describing how an instance of a particular
object class can be represented in a data source.
EclipseLink descriptors may contain the following information:
I The persistent Java class it describes and the corresponding data source (database
tables or XML complex type interaction)
I A collection of mappings, which describe how the attributes and relationships for
that class are represented in the data source
I The primary key information (or equivalent) of the data source
I A list of query keys (or aliases) for field names
Common Descriptor Concepts
6-2 Understanding EclipseLink
I Information for sequence numbers
I A set of optional properties for tailoring the behavior of the descriptor, including
support for caching refresh options, identity maps, optimistic locking, the event
manager, and the query manager
There is a descriptor type for each data source type that EclipseLink supports. In some
cases, multiple descriptor types are valid for the same data source type. The type of
descriptor you use determines the type of mappings that you can define.
6.1.2 Descriptors and Inheritance
Inheritance describes how a derived (child) class inherits the characteristics of its
superclass (parent). You can use descriptors to describe the inheritance relationships
between classes in relational and XML projects.
In the descriptor for a child class, you can override mappings that have been specified
in the descriptor for a parent class, or map attributes that have not been mapped at all
in the parent class descriptor.
Figure 61 illustrates the Vehicle object modela typical Java inheritance hierarchy.
The root class Vehicle contains two branch classes: FueledVehicle and
NonFueledVehicle. Each branch class contains a leaf class: Car and Bicycle,
respectively.
Figure 61 Example Inheritance Hierarchy
EclipseLink recognizes the following three types of classes in an inheritance hierarchy:
1. The root class stores information about all instantiable classes in its subclass
hierarchy. By default, queries performed on the root class return instances of the
root class and its instantiable subclasses. However, the root class can be configured
so queries on it return only instances of itself, without instances of its subclasses.
For example, the Vehicle class in Figure 61 is a root class.
2. Branch classes have a persistent superclass and also have subclasses. By default,
queries performed on the branch class return instances of the branch class and any
of its subclasses. However, as with the root class, the branch class can be
Common Descriptor Concepts
Understanding Descriptors 6-3
configured so queries on it return only instances of itself without instances of its
subclasses.
For example, the FueledVehicle class in Figure 61 is a branch class.
3. Leaf classes have a persistent superclass in the hierarchy but do not have
subclasses. Queries performed on the leaf class can only return instances of the
leaf class.
For example, the Car class in Figure 61 is a leaf class.
In the descriptor for a child class, you can override mappings that have been specified
in the descriptor for a parent class, or map attributes that have not been mapped at all
in the parent class descriptor.
This section includes information on the following topics:
I Specifying a Class Indicator
I Inheritance and Primary Keys
I Single and Multi-Table Inheritance
I Aggregate and Composite Descriptors and Inheritance
6.1.2.1 Specifying a Class Indicator
When configuring inheritance, you configure the root class descriptor with the means
of determining which subclasses it should instantiate.
You can do this in one of the following ways:
I Using Class Indicator Fields
I Using Class Extraction Methods
6.1.2.1.1 Using Class Indicator Fields You can use a persistent attribute of a class to
indicate which subclass should be instantiated. For example, in a relational descriptor,
you can use a class indicator field in the root class table. The indicator field should not
have an associated direct mapping unless it is set to read-only.
You can use strings or numbers as values in the class indicator field.
The root class descriptor must specify how the value in the class indicator field
translates into the class to be instantiated.
One approach is to configure the root class descriptor with a class indicator dictionary:
a collection of key-values that associates a simple key, stored in the class indicator
field, with a class to instantiate. Table 61 illustrates the class indicator dictionary for
the Vehicle class subclasses, as shown in Figure 61.
Note: All leaf classes in the hierarchy must have a class indicator
and they must have the same type of class indicator (field or class
extraction method).
Note: If the indicator field is part of the primary key, define a
write-only transformation mapping for the indicator field.
Common Descriptor Concepts
6-4 Understanding EclipseLink
Another approach is to simply use the class name itself as the value stored in the class
indicator field. This avoids having to define unique indicators for each class at the
expense of a slightly larger key value (depending on the length of your class names).
6.1.2.1.2 Using Class Extraction Methods You can define a Java method to compute the
class indicator based on any available information in the object's data source record.
Such a method is called a class extraction method.
Using a class extraction method, you do not need to include an explicit class indicator
field in your data model and you can handle relationships that are too complex to
describe using class indicator fields.
A class extraction method must have the following characteristics:
I it must be defined on the root descriptors class;
I it must be static;
I it must take a Record as an argument;
I it must return the java.lang.Class object to use for the Record passed in.
You may also need to define only-instances and with-all-subclasses expressions. If you
use a class extraction method, then you must provide EclipseLink with expressions to
correctly filter sibling instances for all classes that share a common table.
For example, Table 62 lists the rows in the EMPLOYEE table. The Employee class is the
base class. Director, Manager, Programmer, and TechWriter classes each derive from
the Employee class. However, in your application, instances of Manager, Programmer,
and TechWriter classes must be represented as Employee instances and instances of
Director must be represented as Director instances. Because there is not a one-to-one
correspondence between class and JOB_TYPE field value, the JOB_TYPE field alone
cannot serve as a class indicator field (see Section 6.1.2.1.1, "Using Class Indicator
Fields"). To resolve this issue, you could use the class extraction method, shown in
Example 61.
Example 61 Class Extraction Method
...
// If the JOB_TYPE field value in record equals 2, return the Director class.
// Return the Employee class for all other JOB_TYPE field values
Table 61 Class Indicator Dictionary for the Vehicle Class
Key Value
F FueledVehicle
N NonFueledVehicle
C Car
B Bicycle
Table 62 EMPLOYEE Table
ID NAME JOB_TYPE JOB_TITLE
732 Bob Jones 1 Manager
733 Sarah Smith 3 Technical Writer
734 Ben Ng 2 Director
735 Sally Johnson 3 Programmer
Common Descriptor Concepts
Understanding Descriptors 6-5
public static Class getClassFromRecord(Record record) {
if (record.get("JOB_TYPE").equals(new Integer(2)) {
return Director.class;
}
else {
return Employee.class;
}
}
When configuring inheritance using a class extraction method, EclipseLink does not
generate SQL for queries on the root class.
6.1.2.2 Inheritance and Primary Keys
For relational projects, EclipseLink assumes that all of the classes in an inheritance
hierarchy have the same primary key, as set in the root descriptor.
6.1.2.3 Single and Multi-Table Inheritance
In a relational project, you can map your inheritance hierarchy to a single table or to
multiple tables.
6.1.2.4 Aggregate and Composite Descriptors and Inheritance
You can designate relational descriptors as aggregates. XML descriptors are always
composites (see Section 6.1.3, "Descriptors and Aggregation").
When configuring inheritance for a relational aggregate descriptor, all the descriptors
in the inheritance tree must be aggregates. The descriptors for aggregate and
non-aggregate classes cannot exist in the same inheritance tree.
When configuring inheritance for an XML descriptor, because all XML descriptors are
composites, descriptor type does not restrict inheritance.
6.1.3 Descriptors and Aggregation
Two objectsa source (parent or owning) object and a target (child or owned)
objectare related by aggregation if there is a strict one-to-one relationship between
them, and all the attributes of the target object can be retrieved from the same data
source representation as the source object. This means that if the source object exists,
then the target object must also exist, and if the source object is destroyed, then the
target object is also destroyed.
In this case, the descriptors for the source and target objects must be designated to
reflect this relationship.
In EJB 3.0, an aggregate is known as an embeddable. In the EJB 3.0 specification, an
embeddable may not contain another embeddable (that is, the EJB 3.0 specification
does not support nested aggregates).
For more information, see Section 6.1.2.4, "Aggregate and Composite Descriptors and
Inheritance".
6.1.4 Descriptor Customization
You can customize a descriptor at run time by specifying a descriptor customizera
Java class that implements the org.eclipse.persistence.config.
DescriptorCustomizer interface and provides a default (zero-argument) constructor.
Object-Relational Descriptor Concepts
6-6 Understanding EclipseLink
You use a descriptor customizer to customize a descriptor at run time through code
API similar to how you use an amendment method to customize a descriptor. See
Section 6.1.5, "Amendment and After-Load Methods".
6.1.5 Amendment and After-Load Methods
You can associate a static Java method that is called when a descriptor is loaded at run
time. This method can amend the run-time descriptor instance through the descriptor
Java code API.
You can only modify descriptors before the session has been connected; you should
not modify descriptors after the session has been connected.
6.1.6 Descriptor Event Manager
In relational projects, EclipseLink raises various instances of DescriptorEvent during
the persistence life cycle. Each descriptor owns an instance of
DescriptorEventManager that is responsible for receiving these events and
dispatching them to the descriptor event handlers registered with it.
Using a descriptor event handler, you can execute your own application specific logic
whenever descriptor events occur, allowing you to take customized action at various
points in the persistence life-cycle. For example, using a descriptor event handler, you
can do the following:
I Synchronize persistent objects with other systems, services, and frameworks
I Maintain nonpersistent attributes of which EclipseLink is not aware
I Notify other objects in the application when the persistent state of an object
changes
I Implement complex mappings or optimizations not directly supported by
EclipseLink mappings
6.2 Object-Relational Descriptor Concepts
The following sections describe the concepts specific to Object-Relational descriptors.
I Fetch Groups
I Descriptor Query Manager
I Descriptors and Sequencing
I Descriptors and Locking
6.2.1 Fetch Groups
By default, when you execute an object-level read query for a particular object class,
EclipseLink returns all the persistent attributes mapped in the objects descriptor. With
this single query, all the objects persistent attributes are defined, and calling their get
methods returns the value directly from the object.
When you are interested in only some of the attributes of an object, it may be more
efficient to return only a subset of the objects attributes using a fetch group.
Using a fetch group, you can define a subset of an object's attributes and associate the
fetch group with either a ReadObjectQuery or ReadAllQuery query. When you execute
the query, EclipseLink retrieves only the attributes in the fetch group. EclipseLink
Object-Relational Descriptor Concepts
Understanding Descriptors 6-7
automatically executes a query to fetch all the attributes excluded from this subset
when and if you call a get method on any one of the excluded attributes.
You can define more than one fetch group for a class. You can optionally designate at
most one such fetch group as the default fetch group. If you execute either a
ReadObjectQuery or ReadAllQuery query without specifying a fetch group,
EclipseLink will use the default fetch group, unless you configure the query otherwise.
Before using fetch groups, Oracle recommends that you perform a careful analysis of
system use. In many cases, the extra queries required to load attributes not in the fetch
group could well offset the gain from the partial attribute loading.
Fetch groups can be used only with basic mappings configured with FetchType.LAZY
(partial object queries).
EclipseLink uses the AttributeGroup that can be used to configure the use of partial
entities in fetch, load, copy, and merge operations.
I Fetch: Control which attributes and their associated columns are retrieved from
the database
I Load: Control which relationships in the entities returned from a query are
populated
I Copy: Control which attributes are copied into a new entity instance
I Merge: Merge only those attributes fetched, loaded, or copied into an entity
6.2.1.1 AttributeGroup Types and Operations
The following sections describe the possible AttributeGroup types and operations.
I FetchGroup
I Default FetchGroup
I Named FetchGroup
I Full FetchGroup
I Load/LoadAll with FetchGroup
I LoadGroup
I CopyGroup
I Merging
6.2.1.2 FetchGroup
The FetchGroup defines which attributes should be fetched (selected from the
database) when the entity is retrieved as the result of a query execution. The inclusion
of relationship attributes in a FetchGroup only determines if the attribute's required
columns should be fetched and populated. In the case of a lazy fetch type the inclusion
of the attribute simply means that its proxy will be created to enable lazy loading
when accessed. To force a relationship mapping to be populated when using a
FetchGroup on a query the attribute must be included in the group and must either be
FetchType.EAGER or it must be included in an associated LoadGroup on the query.
6.2.1.3 Default FetchGroup
FetchGroup also has the notion of named and default FetchGroup which are managed
by the FetchGroupManager. A default FetchGroup is defined during metadata
processing if one or more basic mappings are configured to be lazy and the entity class
implements FetchGroupTracker (typically introduced through weaving). The default
Object-Relational Descriptor Concepts
6-8 Understanding EclipseLink
FetchGroup is used on all queries for this entity type where no explicit FetchGroup or
named FetchGroup is configured.
6.2.1.4 Named FetchGroup
A Named FetchGroup can be defined for an entity using @FetchGroup annotation or
within the eclipselink-orm.xml file.
6.2.1.5 Full FetchGroup
A FetchGroup when first created is assumed to be empty. The user must add the
attributes to the FetchGroup. If a FetchGroup is required with all of the attributes then
the FetchGroupManager.createFullFetchGroup() must be used.
6.2.1.6 Load/LoadAll with FetchGroup
A FetchGroup can also be configured to perform a load operation of relationship
mappings and nested relationship mappings.
6.2.1.7 LoadGroup
A LoadGroup is used to force a specified set of relationship attributes to be populated
in a query result.
6.2.1.8 CopyGroup
The CopyGroup replaces the deprecated ObjectCopyPolicy being used to define how a
entity is copied. In addition to specifying the attributes defining what should be
copied from the source entity graph into the target copy the CopyGroup also allows
definition of:
I shouldResetPrimaryKey: Reset the identifier attributes to their default value. This
is used when the copy operation is intended to clone the entity in order to make a
new entity with similar state to the source. Default is false.
I shouldResetVersion: Reset the optimistic version locking attribute to its default
value in the copies. Default is false.
I depth: defines cascade mode for handling relationships. By default CASCADE_
PRIVATE_PARTS is used but it can also be configured to NO_CASCADE and CASCADE_
ALL_PARTS.
6.2.1.9 Merging
When a partial entity is merged into a persistence context that has an AttributeGroup
associated with it defining which attributes are available only those attributes are
merged. The relationship mappings within the entity are still merged according to
their cascade merge settings.
6.2.2 Descriptor Query Manager
Each relational descriptor provides an instance of DescriptorQueryManager that you
can use to configure the following:
I named queries
I custom default queries for basic persistence operations
I additional join expressions
Object-Relational Descriptor Concepts
Understanding Descriptors 6-9
6.2.3 Descriptors and Sequencing
An essential part of maintaining object identity is managing the assignment of unique
values (that is, a specific sequence) to distinguish one object instance from another.
Sequencing options you configure at the project (or session) level determine the type
of sequencing that EclipseLink uses. In a POJO project, you can use session-level
sequence configuration to override project-level sequence configuration, on a
session-by-session basis, if required.
After configuring the sequence type, for each descriptors reference class, you must
associate one attribute, typically the attribute used as the primary key, with its own
sequence.
6.2.4 Descriptors and Locking
With object-relational mapping, you can configure a descriptor with any of the
following locking policies to control concurrent access to a domain object:
I OptimisticAll users have read access to the data. When a user attempts to make
a change, the application checks to ensure the data has not changed since the user
read the data.
I PessimisticThe first user who accesses the data with the purpose of updating it
locks the data until completing the update.
I No lockingThe application does not prevent users overwriting each others
changes.
Oracle recommends using optimistic locking for most types of applications to ensure
that users do not overwrite each other's changes.
This section describes the various types of locking policies that EclipseLink supports,
including the following:
I Optimistic Version Locking Policies
I Pessimistic Locking Policies
I Applying Locking in an Application
6.2.4.1 Optimistic Version Locking Policies
With optimistic locking, all users have read access to the data. When a user attempts to
make a change, the application checks to ensure the data has not changed since the
user read the data.
Optimistic version locking policies enforce optimistic locking by using a version field
(also known as a write-lock field) that you provide in the reference class that
EclipseLink updates each time an object change is committed.
EclipseLink caches the value of this version field as it reads an object from the data
source. When the client attempts to write the object, EclipseLink compares the cached
version value with the current version value in the data source in the following way:
I If the values are the same, EclipseLink updates the version field in the object and
commits the changes to the data source.
I If the values are different, the write operation is disallowed because another client
must have updated the object since this client initially read it.
EclipseLink provides the following version-based optimistic locking policies:
I VersionLockingPolicy
Object-Relational Descriptor Concepts
6-10 Understanding EclipseLink
I TimestampLockingPolicy
For descriptions of these locking policies, see "Setting Optimistic Locking" in Solutions
Guide for EclipseLink.
Whenever any update fails because optimistic locking has been violated, EclipseLink
throws an OptimisticLockException. This should be handled by the application when
performing any database modification. The application must notify the client of the
locking contention, refresh the object, and have the client reapply its changes.
You can choose to store the version value in the object as a mapped attribute, or in the
cache. In three-tier applications, you typically store the version value in the object to
ensure it is passed to the client when updated (see Section 6.2.4.3, "Applying Locking
in an Application").
If you store the version value in the cache, you do not need to map it. If you do map
the version field, you must configure the mapping as read-only.
To ensure that the parent objects version field is updated whenever a privately owned
child object is modified, consider Section 6.2.4.1.1, "Optimistic Version Locking Policies
and Cascading".
If you are using a stored procedure to update or delete an object, your database may
not return the row-count required to detect an optimistic lock failure, so your stored
procedure is responsible for checking the optimistic lock version and throwing an
error if they do not match. Only version locking is directly supported with a
StoredProcedureCall. Because timestamp and field locking require two versions of
the same field to be passed to the call, an SQL call that uses an ## parameter to access
the translation row could be used for other locking policies.
6.2.4.1.1 Optimistic Version Locking Policies and Cascading If your database schema is
such that both a parent object and its privately owned child object are stored in the
same table, then if you update the child object, the parent objects version field will be
updated.
However, if the parent and its privately owned child are stored in separate tables, then
changing the child will not, by default, update the parents version field.
To ensure that the parent objects version field is updated in this case, you can either
manually update the parent objects version field or, if you are using a
VersionLockingPolicy, you can configure EclipseLink to automatically cascade the
child objects version field update to the parent.
After you enable optimistic version locking cascading, when a privately owned child
object is modified, EclipseLink will traverse the privately owned foreign reference
mappings, updating all the parent objects back to the root.
Optimistic version locking cascading is only applied if the child object is registered in
a unit of work.
EclipseLink supports optimistic version locking cascading for:
Note: In general, Oracle recommends numeric version locking
because of the following:
I accessing the timestamp from the data source can have a negative
impact on performance;
I time stamp locking is limited to the precision that the database
stores for timestamps.
Object-Relational Descriptor Concepts
Understanding Descriptors 6-11
I object changes in privately owned one-to-one and one-to-many mappings
I relationship changes (adding or removing) in the following collection mappings
(privately owned or not):
direct collection
one-to-many
many-to-many
aggregate collection
Consider the example object graph shown in Figure 62
Figure 62 Optimistic Version Locking Policies and Cascading Example
In this example, ObjectA privately owns ObjectB, and ObjectB privately owns
ObjectC, and ObjectC privately owns ObjectD.
Suppose you register ObjectB in a unit of work, modify an ObjectB field, and commit
the unit of work. In this case, ObjectB checks the cache for ObjectA and, if not present,
queries the database for ObjectA. ObjectB then notifies ObjectA of its change. ObjectA
forces an update on its version optimistic locking field even though it has no changes
to its corresponding table.
Suppose you register ObjectA in a unit of work, access its ObjectB to access its ObjectC
to access its ObjectD, modify an ObjectD field, and commit the unit of work. In this
case, ObjectD notifies ObjectC of its changes. ObjectC forces an update on its version
optimistic locking field even though it has no changes to its corresponding table.
ObjectC then notifies ObjectB of the ObjectD change. ObjectB then notifies ObjectA of
the ObjectD change. ObjectA forces an update on its version optimistic locking field
even though it has no changes to its corresponding table.
6.2.4.1.2 Optimistic Locking and Rollbacks With optimistic locking, use the UnitOfWork
method commitAndResumeOnFailure to rollback a locked objects value, if you store the
optimistic lock versions in the cache.
If you store the locked versions in an object, you must refresh the objects (or their
versions) on a failure. Alternatively, you can acquire a new unit of work on the failure
and reapply any changes into the new unit of work.
6.2.4.1.3 Optimistic Field Locking Policies Optimistic field locking policies enforce
optimistic locking by using one or more of the fields that currently exist in the table to
determine if the object has changed since the client read the object.
The unit of work caches the original state of the object when you first read the object or
register it with the unit of work. At commit time, the unit of work compares the
original values of the lock fields with their current values on the data source during
the update. If any of the lock fields values have changed, an optimistic lock exception
is thrown.
Object-Relational Descriptor Concepts
6-12 Understanding EclipseLink
EclipseLink provides the following optimistic field locking policies:
I AllFieldsLockingPolicy
I ChangedFieldsLockingPolicy
I SelectedFieldsLockingPolicy
I VersionLockingPolicy
I TimestampLockingPolicy
For descriptions of these locking policies, see "Setting Optimistic Locking" in Solutions
Guide for EclipseLink.
6.2.4.2 Pessimistic Locking Policies
With pessimistic locking, the first user who accesses the data with the purpose of
updating it locks the data until completing the update.
When using a pessimistic locking policy, you can configure the policy to either fail
immediately or to wait until the read lock is acquired.
You can use a pessimistic locking policy only in a project with a container-managed
persistence type and with descriptors that have EJB information.
You can also use pessimistic locking (but not a pessimistic locking policy) at the query
level.
EclipseLink provides an optimization for pessimistic locking when this locking is used
with entities with container-managed persistence: if you set your query to pessimistic
locking and run the query in its own new transaction (which will end after the
execution of the finder), then EclipseLink overrides the locking setting and does not
append FOR UPDATE to the SQL. However, the use of this optimization may produce an
undesirable result if the pessimistic lock query has been customized by the user with a
SQL string that includes FOR UPDATE. In this case, if the conditions for the optimization
are present, the query will be reset to nonpessimistic locking, but the SQL will remain
the same resulting in the locking setting of the query conflicting with the querys SQL
string. To avoid this problem, you can take one of the following two approaches:
I Use an expression (see Chapter 11, "Understanding EclipseLink Expressions") for
the selection criteria. This will give EclipseLink control over the SQL generation.
I Place the finder in a transaction to eliminate conditions for the optimization.
6.2.4.3 Applying Locking in an Application
To correctly lock an object in an application, you must obtain the lock before the object
is sent to the client for editing.
6.2.4.3.1 Applying Optimistic Locking in an Application If you are using optimistic locking,
you have the following two choices for locking objects correctly:
1. Map the optimistic lock field in your object as not read-only and pass the version
to the client on the read and back to the server on the update.
Ensure that the original version value is sent to the client when it reads the object
for the update. The client must then pass the original version value back with the
update information, and this version must be set into the object to be updated
after it is registered/read in the new unit of work on the server.
2. Hold the unit of work for the duration of the interaction with the client.
Object-XML Descriptor Concepts
Understanding Descriptors 6-13
Either through a stateful session bean, or in an HTTP session, store the unit of
work used to read the object for the update for the duration of the client
interaction.
You must read the object through this unit of work before passing it to the client
for the update. This ensures that the version value stored in the unit of work cache
or in the unit of work clone will be the original value.
This same unit of work must be used for the update.
The first option is more commonly used, and is required if developing a stateless
application.
6.2.4.3.2 Applying Pessimistic Locking in an Application If you are using pessimistic
locking, you must use the unit of work to start a database transaction before the object
is read. You must hold this unit of work and database transaction while the client is
editing the object and until the client updates the object. You must use this same unit
of work to update the object.
6.3 Object-XML Descriptor Concepts
The following section describes the use of default root elements in Object-XML
descriptors.
6.3.1 Default Root Element
You configure XML descriptors with a default root element so that the EclipseLink
runtime knows the data source data type associated with the class the descriptor
describes.
This section describes what a default root element is and how EclipseLink uses it.
Consider the Customer and Address classes and their mappings, shown in
Example 62.
Example 62 Customer and Address Classes
Class: Customer
Default Root: customer
Attributes and Mappings:
name:String Direct Mapping name/text()
billingAddress:Address Composite Object Mapping to billing-address
shippingAddress:Address Composite Object Mapping to shipping-address
Class: Address
Default Root: address
Attributes and Mappings:
street:String Direct Mapping to street/text()
city:String Direct Mapping to city/text()
These classes correspond to the XML schema, shown in Example 63.
Example 63 Customer and Address Schema
<xsd:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
Note: The undefined document root element of a referenced object is
ignored during marshalling with an any collection mapping and
object mapping.
Descriptor API
6-14 Understanding EclipseLink
<xsd:complexType name="address-type">
<xsd:sequence>
<element name="street" type="xsd:string"/>
<element name="city" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="customer" type="customer-type"/>
<xsd:complexType name="customer-type">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="billing-address" type="address-type"/>
<xsd:element name="shipping-address" type="address-type"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
When an instance of the Customer class is persisted to XML, the EclipseLink runtime
performs the following:
1. Gets the default root element.
The Customer class instance corresponds to the root of the XML document. The
EclipseLink runtime uses the default root element specified on the descriptor
(customer) to start the XML document. EclipseLink then uses the mappings on the
descriptor to marshal the objects attributes:
<customer>
<name></name>
</customer>
2. When the EclipseLink runtime encounters an object attribute such as
billingAddress, it checks the mapping associated with it to determine with what
element (billing-address) to continue:
<customer>
<name></name>
<billing-address/>
</customer>
The EclipseLink runtime checks the mapping's reference descriptor (Address) to
determine what attributes to persist:
<customer>
<name></name>
<billing-address>
<street></street>
<city></city>
</billing-address>
</customer>
6.4 Descriptor API
The Descriptor API can be used to define, or amend EclipseLink descriptors through
Java code. The Descriptor API classes are mainly in the org.eclipse.persistence.
descriptors package. These include the following classes:
I ClassDescriptor (abstract generic Descriptor API)
I RelationalDescriptor (relational project-specific API)
I DescriptorEventManager (event API)
I DescriptorQueryManager (query API)
Descriptor API
Understanding Descriptors 6-15
I InheritancePolicy
I InterfacePolicy
I ReturningPolicy
I Locking policies (various optimistic locking policies)
The Descriptor API also includes these non-relational descriptors:
I org.eclipse.persistence.oxm.XMLDescriptor
I org.eclipse.persistence.eis.EISDescriptor
For object-relational data type and XML projects, descriptor classes are in the org.
eclipse.persistence.mappings.structures and org.eclipse.persistence.oxm
packages, respectively.
The following illustrates the hierarchy of descriptor types that derive from the class
org.eclipse.persistence.descriptors.ClassDescriptor.
class org.eclipse.persistence.descriptors.ClassDescriptor
class org.eclipse.persistence.descriptors.RelationalDescriptor
class org.eclipse.persistence.mappings.structures.ObjectRelationalDataTypeDescriptor
class org.eclipse.persistence.oxm.XMLDescriptor
Descriptor API
6-16 Understanding EclipseLink
7
Understanding Mappings 7-1
7Understanding Mappings
EclipseLink can transform data between an object representation and a representation
specific to a data source. This transformation is called mapping and it is the core of
EclipseLink projects.
A mapping corresponds to a single data member of a domain object. It associates the
object data member with its data source representation and defines the means of
performing the two-way conversion between object and data source.
This chapter includes the following sections:
I Common Mapping Concepts
I Object-Relational Mapping Concepts
I Object-XML Mapping Concepts
I Object-JSON Mapping Concepts
I About JPA Mapping Types
7.1 Common Mapping Concepts
This section describes concepts for relational and nonrelational mappings that are
unique to EclipseLink:
I Mapping Architecture
I Mapping Examples
I Mapping Converters and Transformers
Serialized Object Converter
Type Conversion Converter
Object Type Converter
Transformation Mappings
7.1.1 Mapping Architecture
To define a mapping, you draw upon the following components:
I The data representation specific to the data source (such as a relational database
table or schema-defined XML element) in which you store the objects data.
I A descriptor for a particular object class.
I An object class to map.
Common Mapping Concepts
7-2 Understanding EclipseLink
For an example of a typical EclipseLink mapping, see Section 7.1.2, "Mapping
Examples".
The type of data source you define in your project determines the type of mappings
you can use and how you configure them. In a persistent project, you use mappings to
persist to a data source. In a nonpersistent project, you use mappings simply to
transform between the object format and some other data representation (such as
XML).
A descriptor represents a particular domain object: it describes the objects class. A
descriptor also owns the mappings: one mapping for each of the class data members
that you intend to persist or transform in memory.
For more information about descriptors, see Chapter 6, "Understanding Descriptors".
7.1.2 Mapping Examples
Although EclipseLink supports more complex mappings, most EclipseLink classes
map to a single database table or XML element that defines the type of information
available in the class. Each object instance of a given class maps to a single row
comprising the objects attributes, plus an identifier (the primary key) that uniquely
identifies the object.
Figure 71 illustrates the simplest database mapping case in which:
I Table_X in the database represents Class_X.
I Object_X1 and Object_X2 are instances of Class_X.
I Individual rows in Table_X represent Object_X1 and Object_X2, as well as any
other instances of Class_X.
Figure 71 How Classes and Objects Map to a Database Table
Note: A mapping is the same regardless of whether your project is
persistent or nonpersistent.
Common Mapping Concepts
Understanding Mappings 7-3
EclipseLink provides you with the tools to build these mappings, from the simple
mappings illustrated in Figure 71, to complex mappings.
For an additional example of a relational mapping, see Figure 72, "Serialized Object
Converter (relational)".
7.1.3 Using Lazy Loading
JPA specifies that lazy loading is a hint to the persistence provider that data should be
fetched lazily when it is first accessed, if possible. If you are developing your
application in a Java EE environment, set fetch to javax.persistence.FetchType.
LAZY, and the persistence provider supplies all the necessary functionality.
When using a one-to-one or many-to-one mapping in a Java SE environment, use
either dynamic or static weaving to perform lazy loading when the fetch attribute is
set to FetchType.LAZY.
When using a one-to-one or many-to-one mapping in a Java SE environment and the
environment does not permit the use of -javaagent on the JVM command line, use
static weaving to perform lazy loading when the fetch attribute is set to FetchType.
LAZY.
Table 71 lists support for lazy loading by mapping type.
7.1.4 Mapping Converters and Transformers
If existing EclipseLink mappings do not meet your needs, you can create custom
mappings using mapping extensions. These extensions include the following:
I Serialized Object Converter
I Type Conversion Converter
I Object Type Converter
I Transformation Mappings
Table 71 Support for Lazy Loading by Mapping Type
Mapping Java EE Java SE
Many-to-many Lazy loading is performed when the
fetch attribute is set to javax.
persistence.FetchType.LAZY
(default).
Lazy loading is performed when the
fetch attribute is set to javax.
persistence.FetchType.LAZY
(default).
One-to-many Lazy loading is performed when the
fetch attribute is set to javax.
persistence.FetchType.LAZY
(default).
Lazy loading is performed when the
fetch attribute is set to javax.
persistence.FetchType.LAZY
(default).
One-to-one Lazy loading is performed when the
fetch attribute is set to javax.
persistence.FetchType.LAZY.
The fetch attribute is ignored and
default javax.persistence.
FetchType.EAGER applies.
Many-to-one Lazy loading is performed when the
fetch attribute is set to javax.
persistence.FetchType.LAZY.
The fetch attribute is ignored and
default javax.persistence.
FetchType.EAGER applies
Basic Lazy loading is performed when the
fetch attribute is set to javax.
persistence.FetchType.LAZY.
The fetch attribute is ignored and
default javax.persistence.
FetchType.EAGER applies
Common Mapping Concepts
7-4 Understanding EclipseLink
7.1.4.1 Serialized Object Converter
The serialized object converter can be used with direct and direct collection mappings,
allowing you to map complex objects into binary fields through Java object
serialization. Serialized objects are normally stored in RAW or Binary Large Object
(BLOB) fields in the database, or HEX or BASE64 elements in an XML document.
Figure 72 shows an example of a direct-to-field mappings that uses a serialized object
converter. The attribute jobDescription contains a formatted text document that is
stored in the JOB_DESC field of the database.
Figure 72 Serialized Object Converter (relational)
Figure 73 demonstrates an example of a nonrelational mapping that uses a serialized
object converter. The attribute jobDescription contains a formatted text document
that EclipseLink stores in the JOB DESCRIPTION element of an XML schema.
Figure 73 Serialized Object Converter (nonrelational)
The serialized object converter relies on the Java serializer. Before you map a domain
object with the serialized object converter, ensure that the domain object implements
the java.io.Serializable interface (or inherits that implementation) and marks all
nonserializable fields transient.
7.1.4.2 Type Conversion Converter
The type conversion converter can be used with direct and direct collection mappings,
allowing you to map complex objects into binary fields. For example, a Number in the
data source can be mapped to a String in Java, or a java.util.Date in Java can be
mapped to a java.sql.Date in the data source.
Figure 74 illustrates a type conversion mapping (relational). Because the java.util.
Date class is stored by default as a Timestamp in the database, it must first be
converted to an explicit database type such as java.sql.Date (required only for
Note: Except for simple type translation, you can use the mapping
converters and transformers regardless of whether your data source is
relational or nonrelational. Simple type translation is applicable only
to XML projects.
Common Mapping Concepts
Understanding Mappings 7-5
DB2most other databases have a single date data type that can store any date or
time).
Figure 74 Type Conversion Mapping (relational)
Figure 75 illustrates a type conversion mapping (nonrelational). java.util.Date
object is mapped to a String in a XML schema.
Figure 75 Type Conversion Mapping (nonrelational)
You can use a type conversion converter to specify the specific database type when
that type must be handled specially for the database. This includes support for the
special Oracle JDBC binding options required for NCHAR, NVARCHAR2, and NCLOB fields
as well as the special Oracle Thin JDBC insert and update requirements for handling
BLOB and CLOB fields greater than 5K.
EclipseLink uses the NCharacter, NClob and NString types in the org.eclipse.
persistence.platform.database.oracle package as the converter data type to
support the NCHAR, NCLOB and NVARCHAR2 types. EclipseLink uses the java.sql.Blob
and Clob types as the converter data type to support BLOB and CLOB values greater
than 5K.
You can configure a type conversion converter to map a data source time type (such as
TIMESTAMP) to a java.lang.String provided that the String value conforms to the
following formats:
I YYYY/MM/DD HH:MM:SS
I YY/MM/DD HH:MM:SS
I YYYY-MM-DD HH:MM:SS
I YY-MM-DD HH:MM:SS
For more complex String to TIMESTAMP type conversion, consider a transformation
mapping (see Section 7.1.4.4, "Transformation Mappings").
Common Mapping Concepts
7-6 Understanding EclipseLink
7.1.4.3 Object Type Converter
The object type converter can be used with direct and direct collection mappings
allowing you to match a fixed number of values to Java objects. Use this converter
when the values in the schema differ from those in Java.
Figure 76 illustrates an object type conversion between the Employee attribute gender
and the XML element gender. If the value of the Java object attribute is Female,
EclipseLink stores it in the XML element as F.
Figure 76 Object Type XML Converter
EclipseLink
***********************************************************************************************
7.1.4.4 Transformation Mappings
In some special circumstances, existing mapping types and their default Java to data
source type handling may be insufficient. In these special cases, you can consider
using a transformation mapping to perform specialized translations between how a
value is represented in Java and in the data source.
A transformation mapping is made up of the following two components:
I attribute transformer: performs the object attribute transformation at read time
I field transformer: performs the object attribute-to-field transformation at write
time
You can implement a transformer as either a separate class or as a method on your
domain object.
Within your implementation of the attribute and field transformer, you can take
whatever actions are necessary to transform your application data to suit your data
source, and vise versa.
For more information, see Section 7.1.5, "Transformation Mapping".
7.1.5 Transformation Mapping
Use transformation mappings for specialized translations for how a value is
represented in Java and how it is represented in the database.
Tip: Because of the complexity of transformation mappings, it is
often easier to perform the transformation with a converter or
getter and setter methods of a direct-to-field mapping.
Object-Relational Mapping Concepts
Understanding Mappings 7-7
Figure 77 illustrates a transformation mapping. The values from the B_DATE and B_
TIME fields are used to create a java.util.Date to be stored in the birthDate attribute.
Figure 77 Transformation Mappings
Often, a transformation mapping is appropriate when values from multiple fields are
used to create an object. This type of mapping requires that you provide an attribute
transformation that is invoked when reading the object from the database. This must
have at least one parameter that is an instance of Record. In your attribute
transformation, you can use Record method get to retrieve the value in a specific
column. Your attribute transformation can optionally specify a second parameter, an
instance of Session. The Session performs queries on the database to get additional
values needed in the transformation. The transformation should return the value to be
stored in the attribute.
Transformation mappings also require a field transformation for each field, to be written
to the database when the object is saved. The transformation returns the value to be
stored in that field.
7.2 Object-Relational Mapping Concepts
This section describes concepts for relational mappings that are unique to EclipseLink:
I Indirection (Lazy Loading)
I Value Holder Indirection
I Transparent Indirection
I Proxy Indirection
I Weaved Indirection
I Indirection and JPA
I Indirection, Serialization, and Detachment
7.2.1 Indirection (Lazy Loading)
By default, when EclipseLink retrieves a persistent object, it retrieves all of the
dependent objects to which it refers. When you configure indirection (also known as
lazy reading, lazy loading, and just-in-time reading) for an attribute mapped with a
relationship mapping, EclipseLink uses an indirection object as a place holder for the
referenced object: EclipseLink defers reading the dependent object until you access
that specific attribute. This can result in a significant performance improvement,
Object-Relational Mapping Concepts
7-8 Understanding EclipseLink
especially if the application is interested only in the contents of the retrieved object,
rather than the objects to which it is related.
Oracle strongly recommends using indirection for all relationship mappings. Not only
does this lets you optimize data source access, but it also allows EclipseLink to
optimize the unit of work processing, cache access, and concurrency.
Figure 78 shows an indirection example. Without indirection, reading the Order
object also reads the dependent collection of LineItem objects. With indirection,
reading the Order object does not read the dependent collection of LineItem objects:
the lineItems attribute refers to an indirection object. You can access other attributes
(such as customerId), but EclipseLink reads the dependent LineItem objects only if
and when you access the lineItems attribute.
Figure 78 EclipseLink Indirection
EclipseLink supports the following types of indirection:
I Value Holder Indirection
I Transparent Indirection
I Proxy Indirection
When using indirection with an object that your application serializes, you must
consider the effect of any untriggered indirection objects at deserialization time. See
Section 7.2.7, "Indirection, Serialization, and Detachment".
7.2.2 Value Holder Indirection
Persistent classes that use indirection must replace relationship attributes with value
holder attributes. A value holder is an instance of a class that implements the
ValueHolderInterface interface, such as ValueHolder. This object stores the
Note: The use of indirection is especially important for providing a
proper maintenance of bidirectional relationships. In this case, you
must use indirection. If you are operating with collections, you must
use transparent indirection (see Section 7.2.3, "Transparent
Indirection").
Object-Relational Mapping Concepts
Understanding Mappings 7-9
information necessary to retrieve the object it is replacing from the database. If the
application does not access the value holder, the replaced object is never read from the
database.
To obtain the object that the value holder replaces, use the getValue and setValue
methods of the ValueHolderInterface. A convenient way of using these methods is to
hide the getValue and setValue methods of the ValueHolderInterface inside get and
set methods, as shown in the following illustrations.
Figure 79 shows the Employee object being read from the database. The Address
object is not read and will not be created unless it is accessed.
Figure 79 Address Object Not Read
The first time the address is accessed, as in Figure 710, the ValueHolder reads and
returns the Address object.
Figure 710 Initial Request
Subsequent requests for the address do not access the database, as shown in
Figure 711.
Figure 711 Subsequent Requests
If you are using method access, the get and set methods specified in the mapping must
access the instance of ValueHolderInterface, rather than the object referenced by the
Object-Relational Mapping Concepts
7-10 Understanding EclipseLink
value holder. The application should not use these getter and setter, but use the getter
and setter that hide the usage of value holders, for example:
public class Employee {

private ValueHolderInterface addressValueHolder;

// Use this get/set pair when configuring your Mapping
public void setAddressValueHolder(ValueHolderInterface value) {
this.addressValueHolder = value;
}
public ValueHolderInterface getAddressValueHolder() {
return this.addressValueHolder;
}

// Your application uses these methods to interact with Addresses
public void setAddress(Address address) {
this.addressValueHolder.setValue(address);
}
public Address getAddress() {
return this.addressValueHolder.getValue(address);
}

}
7.2.3 Transparent Indirection
Transparent indirection lets you declare any relationship attribute of a persistent class
that holds a collection of related objects as any of the following:
I java.util.Collection
I java.util.Hastable
I java.util.List
I java.util.Map
I java.util.Set
I java.util.Vector
EclipseLink will use an indirection object that implements the appropriate interface
and also performs just-in-time reading of the related objects. When using transparent
indirection, you do not have to declare the attributes as ValueHolderInterface.
Newly created collection mappings use transparent indirection by default if their
attribute is not a ValueHolderInterface.
You can configure EclipseLink to automatically weave transparent indirect container
indirection for JPA entities and Plain Old Java Object (POJO) classes. For more
information, see Section 3.3.1.4, "Using Java Byte-code Weaving" and Section 3.7,
"About Weaving."
7.2.4 Proxy Indirection
The Java class Proxy lets you use dynamic proxy objects as place-holders for a defined
interface. Certain EclipseLink mappings can be configured to use proxy indirection,
which gives you the benefits of indirection without the need to include EclipseLink
classes in your domain model. Proxy indirection is to one-to-one relationship
mappings as indirect containers are to collection mappings.
To use proxy indirection, your domain model must satisfy all of the following criteria:
Object-Relational Mapping Concepts
Understanding Mappings 7-11
I The target class of the one-to-one relationship must implement a public interface.
I The one-to-one attribute on the source class must be of the interface type.
I If you employ method accessing, then the getter and setter methods must use the
interface.
Before using proxy indirection, be aware of the restrictions it places on how you use
the unit of work (see Section 7.2.4.1, "Proxy Indirection Restrictions").
To configure proxy indirection, you can use JDeveloper or Java in an amendment
method.
7.2.4.1 Proxy Indirection Restrictions
Proxy objects in Java are only able to intercept messages sent. If a primitive operation
such as ==, instanceof, or getClass is used on a proxy, it will not be intercepted. This
limitation can require the application to be somewhat aware of the usage of proxy
objects.
You cannot register the target of a proxy indirection implementation with a unit of
work. Instead, first register the source object with the unit of work. This lets you
retrieve a target object clone with a call to a getter on the source object clone.
7.2.5 Weaved Indirection
For JPA entities or POJO classes that you configure for weaving, EclipseLink weaves
value holder indirection for one-to-one mappings. If you want EclipseLink to weave
change tracking and your application includes collection mappings (one-to-many or
many-to-many), then you must configure all collection mappings to use transparent
indirect container indirection only (you may not configure your collection mappings to
use eager loading nor value holder indirection).
For more information, see Section 3.3.1.4, "Using Java Byte-code Weaving".
7.2.6 Indirection and JPA
When you set mapping annotation attribute fetch to lazy, the EclipseLink JPA
persistence provider uses indirection.
By default, one-to-many and many-to-many relationships are lazy and use transparent
indirection, while one-to-one and many-to-one relationships are not lazy.
If you set one-to-one or many-to-one relationships to lazy, and you enable weaving,
the EclipseLink JPA persistence provider will use weaving to enable value holder
indirection for these relationships.
For more information, see the following:
I Section 7.2.5, "Weaved Indirection"
I Section 3.3.1.4, "Using Java Byte-code Weaving"
7.2.7 Indirection, Serialization, and Detachment
When using indirection (lazy loading), it is likely that a graph of persistent objects will
contain untriggered indirection objects. Because indirection objects are transient and
do not survive serialization between one JVM and another, untriggered indirection
objects will trigger an error if the relationship is accessed after deserialization.
The application must ensure that any indirect relationships that will be required after
deserialization have been instantiated before serialization. This can be done through
Object-XML Mapping Concepts
7-12 Understanding EclipseLink
accessing the get method for any relationship using ValueHolder or weaved
indirection, and by calling the size method to any relationship using transparent
indirection. If the application desired the relationships to be always instantiated on
serialization, you could overwrite the serialization writeObject method in the
persistent class to first instantiate the desired relationships. Use caution for objects
with many or deep relationships to avoid serializing large object graphs: ideally, only
the relationships required by the client should be instantiated.
When serializing JPA entities, any lazy relationships that have not been instantiated
prior to serialization will trigger errors if they are accessed. If weaving is used on the
server, and the entities are serialized to a client, the same weaved classes must exist on
the client, either through static weaving of the jar, or through launching the client JVM
using the EclipseLink agent.
For more information, see Section 3.3.1.4, "Using Java Byte-code Weaving".
7.3 Object-XML Mapping Concepts
This section describes concepts for nonrelational mappings that are unique to
EclipseLink:
7.3.1 Simple Type Translation
The simple type translation can be used with direct and direct collection mappings,
allowing you to automatically translate an XML element value to an appropriate Java
type based on the elements <type> attribute as defined in your XML schema.
In code, this is set up when building a mapping using the setIsTypedTextField
method on XMLField, for example:
XMLDirectMapping mapping = new XMLDirectMapping();
XMLField tef = new XMLField();
tef.setIsTypedTextField(true);
tef.setXPath("NUMBER/text()");
mapping.setField(tef);
mapping.setAttributeName("number");
xmlDescriptor.addMapping(mapping);
You can use simple type translation only when the mappings XPath goes to a text
node. You cannot use a simple type translation if the mappings XPath goes to an
attribute.
Using simple type translation, you can make the XML document preserve type
information. This is useful when your object model specifies generic object attributes
such as java.lang.Object and java.io.Serializable, since they do not trigger
specific type conversions in EclipseLink as do specific object attributes such as java.
lang.Integer or java.util.Calendar.
Figure 712 illustrates a type translation XML mapping for the number attribute of the
PhoneNumber class. Notice that the Java attribute is not specific enough to preserve the
typing. Simple type translation adds the type information to the resulting document to
preserve the typing.
Note: Simple type translation is applicable only for XML projects.
Object-XML Mapping Concepts
Understanding Mappings 7-13
Figure 712 Simple Type Translation
By default, EclipseLink uses built-in read and write conversion pairs (see Section 7.3.1.
1, "Default Read Conversions" and Section 7.3.1.2, "Default Write Conversions").
You can override this behavior by specifying and configuring your own simple type
translation, for example, to write XML binary data as Base64.
7.3.1.1 Default Read Conversions
Table 72 lists the built-in conversion pairs for reading XML elements. When the
schema <type> attribute is specified and simple type translation is enabled, the value
read is converted to the corresponding Java type.
Table 72 Simple Type Translation Read Conversions
Schema Type Java Type
base64Binary Byte[]
boolean Boolean
byte Byte
date Calendar
dateTime Calendar
double Double
float Float
hexBinary Byte[]
int int
integer BigInteger
long Long
short Short
Object-JSON Mapping Concepts
7-14 Understanding EclipseLink
7.3.1.2 Default Write Conversions
Table 73 lists the built-in conversion pairs for writing XML. When a Java class
attribute is of a type in Table 73 and the simple type translation is enabled, the
corresponding schema type is specified on the element written.
7.4 Object-JSON Mapping Concepts
EclipseLink MOXy supports the ability to convert objects to and from JSON
(JavaScript Object Notation). This feature is useful when creating RESTful services;
JAX-RS services can accept both XML and JSON messages.
EclipseLink supports all MOXy object-to-XML options when reading and writing
JSON, including:
I EclipseLinks advanced and extended mapping features (in addition to the JAXB
specification)
I Storing mappings in external bindings files
I Creating dynamic models with Dynamic JAXB
I Building extensible models that support multitenant applications
EclipseLink provides the following support for mapping JSON documents:
string String
time Calendar
unsignedByte Short
unsignedInt Long
unsignedShort Integer
Table 73 Simple Type Translation Write Conversions
Java Type Schema Type
Byte[] hexBinary
BigInteger integer
Boolean boolean
Byte byte
Calendar dateTime
GregorianCalendar dateTime
Double double
Float float
Integer int
Long long
int int
short short
String string
Table 72 (Cont.) Simple Type Translation Read Conversions
Schema Type Java Type
About JPA Mapping Types
Understanding Mappings 7-15
I JSON bindings that do not require compile time dependencies, in addition to those
required for normal JAXB use. You can also write MOXy External Bindings files as
JSON documents.
I Although XML has a single datatype, JSON differentiates between strings,
numbers, and booleans. EclipseLink supports these datatypes automatically.
I JSON does not use attributes; anything mapped with a @XmlAttribute annotation
will be marshalled as an element. By default, EclipseLink triggers both the
attribute and element events, thereby allowing either the mapped attribute or
element to handle the value.
I EclipseLink supports JSON documents without a root element. By default, if no
@XmlRootElement annotation exists, the marshalled JSON document will not have
a root element. With EclipseLink, you can override this behavior (that is, omit the
root element from the JSON output).
I Because JSON does not use namespaces, all namespaces and prefixes are ignored
by default when marshaling and unmarshaling. With EclipseLink, you can supply
a Map of namespace-to-prefix (or an instance of NamespacePrefixMapper) to the
marshaller and unmarshaller. The namespace prefix will appear in the marshalled
document prepended to the element name.
I By default, when marshalling to JSON, EclipseLink marshals empty collections as
[ ], EclipseLink allows you to override this behavior, so that empty collections are
not marshalled at all.
I You can marshal and unmarshal root-level collections.
For more information on EclipseLink support for JSON documents, see "Using JSON
Documents" in Developing JAXB Applications Using EclipseLink MOXy
7.5 About JPA Mapping Types
To map entity classes to relational tables you must configure a mapping per persistent
field. The following sections describe EclipeLink's JPA mapping types:
I Basic Mappings
I Default Conversions and Converters
I Collection Mappings
I Using Optimistic Locking
7.5.1 Basic Mappings
Simple Java types are mapped as part of the immediate state of an entity in its fields or
properties. Mappings of simple Java types are called basic mappings.
By default, the EclipseLink persistence provider automatically configures a basic
mapping for simple types.
Use the following annotations to fine-tune how your application implements these
mappings:
I @Basic
I @Enumerated
I @Temporal
I @Lob
About JPA Mapping Types
7-16 Understanding EclipseLink
I @Transient
I @Column
I Lazy Basics (See Section 7.1.3, "Using Lazy Loading")
For all mapping types there are a common set of options:
I Read-Only: Specifies that the mapping should populate the value on read and
copy. Required when multiple mappings share the same database column.
I Converters: Allows custom data types and data conversions to be used with most
mapping types
Annotations: @Converter, @TypeConverter, @ObjectTypeConverter,
@StructConverter, @Convert
External Metadata: <converter>, <type-converter>, <object-type-
converter>, <struct-converter>, <convert>
For more information on these annotations, see Java Persistence API (JPA) Extensions
Reference for EclipseLink.
7.5.2 Default Conversions and Converters
EclipseLink defines the following converter annotations (in addition to JPA-defined
annotations):
I @Converter
I @TypeConverter
I @ObjectTypeConverter
I @StructConverter
I @Convert
The EclipseLink persistence provider searches the converter annotations in the
following order:
I @Convert
I @Enumerated
I @Lob
I @Temporal
I Serialized (automatic)
You can define converters at the class, field and property level. You can specify
EclipseLink converters on the following types of classes:
I @Entity
I @MappedSuperclass
I @Embeddable
You can use EclipseLink converters with the following mappings:
I @Basic
I @Id
I @Version
I @BasicMap
About JPA Mapping Types
Understanding Mappings 7-17
I @BasicCollection
If you specify a converter with any other type of mapping annotation, EclipseLink will
throw an exception.
For more information on these annotations, see Java Persistence API (JPA) Extensions
Reference for EclipseLink.
7.5.3 Collection Mappings
You can access additional advanced mappings and mapping options through the
EclipseLink descriptor and mapping API using a DescriptorCustomizer class.
I One-to-Many Mapping
I Many-to-Many Mapping
7.5.3.1 One-to-Many Mapping
One-to-many mappings are used to represent the relationship between a single source
object and a collection of target objects. They are a good example of something that is
simple to implement in Java using a Collection (or other collection types) of target
objects, but difficult to implement using relational databases.
In a Java Collection, the owner references its parts. In a relational database, the parts
reference their owner. Relational databases use this implementation to make querying
more efficient.
Figure 713 One-to-Many Relationships
7.5.3.1.1 JPA Mapping By default, JPA automatically defines a OneToMany mapping
for a many-valued association with one-to-many multiplicity.
Use the @OneToMany annotation to do the following:
Note: The phone attribute shown in the One-to-Many Relationships
is of type Vector. You can use a Collection interface (or any class that
implements the Collection interface) for declaring the collection
attribute.
About JPA Mapping Types
7-18 Understanding EclipseLink
I configure the fetch type to EAGER
I configure the associated target entity, because the Collection used is not defined
using generics
I configure the operations that must be cascaded to the target of the association: for
example, if the owning entity is removed, ensure that the target of the association
is also removed
I configure the details of the join table used by the persistence provider for
unidirectional one-to-many relationships. For a one-to-many using a mappedBy or
JoinColumn, the deletion of the related objects is cascaded on the database. For a
one-to-many using a JoinTable, the deletion of the join table is cascaded on the
database (target objects cannot be cascaded even if private because of constraint
direction).
For more information, see Section 11.1.23 "JoinTable Annotation" in the JPA
Specification.
http://jcp.org/en/jsr/detail?id=317
7.5.3.2 Many-to-Many Mapping
Many-to-many mappings represent the relationships between a collection of source
objects and a collection of target objects. They require the creation of an intermediate
table for managing the associations between the source and target records.
Figure 714 illustrates a many-to-many mapping in Java and in relational database
tables.
About JPA Mapping Types
Understanding Mappings 7-19
Figure 714 Many-to-many Relationships
7.5.3.2.1 JPA Mapping By default, JPA automatically defines a ManyToMany mapping
for a many-valued association with many-to-many multiplicity.
Use the @ManyToMany annotation to do the following:
I configure the Fetch Type to EAGER;
I configure the mapping to forbid null values (for nonprimitive types) in case null
values are inappropriate for your application;
I configure the associated target entity because the Collection used is not defined
using generics;
I configure the operations that must be cascaded to the target of the association (for
example, if the owning entity is removed, ensure that the target of the association
is also removed).
For a list of supported attributes for the @ManyToMany annotation, see the Java
Persistence specification:
http://jcp.org/en/jsr/detail?id=317
Note: For the projects attribute shown in the Many-to-many
Relationships you can use a Collection interface (or any class that
implements the Collection interface) for declaring the collection
attribute.
About JPA Mapping Types
7-20 Understanding EclipseLink
7.5.4 Using Optimistic Locking
Oracle recommends using optimistic locking. With optimistic locking, all users have
read access to the data. When a user attempts to write a change, the application checks
to ensure the data has not changed since the user read the data.
7.5.4.1 Optimistic Locking in a Stateless Environment
In a stateless environment, take care to avoid processing out-of-date (stale) data. A
common strategy for avoiding stale data is to implement optimistic locking, and store
the optimistic lock values in the object. This solution requires careful implementation if
the stateless application serializes the objects, or sends the contents of the object to the
client in an alternative format. In this case, transport the optimistic lock values to the
client in the HTTP contents of an edit page. You must then use the returned values in
any write transaction to ensure that the data did not change while the client was
performing its work.
You can use optimistic version locking or optimistic field locking policies. We
recommend using version locking policies.
7.5.4.2 Optimistic Version Locking
Use the @Version annotation to enable the JPA-managed optimistic locking by
specifying the version field or property of an entity class that serves as its optimistic
lock value (recommended).
When choosing a version field or property, ensure that the following is true:
I there is only one version field or property per entity;
I you choose a property or field persisted to the primary table;
I your application does not modify the version property or field.
For more information, see Section 11.1.45 "Table Annotation" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
The @Version annotation does not have attributes. The @Version annotation supports
the use of EclipseLink converters. See Section 7.5.2, "Default Conversions and
Converters."
For more information, see Section 11.1.9 "Column Annotation" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
Note: The field or property type must either be a numeric type (such
as Number, long, int, BigDecimal, and so on), or a java.sql.
Timestamp. EclipseLink recommends using a numeric type.
8
Understanding Data Access 8-1
8Understanding Data Access
One of the most important functions of a session is to provide access to a data source.
This chapter explains session components specific to accessing a data source.
This chapter describes data access concepts unique to EclipseLink, including the
following:
I About Externally Managed Transactional Data Sources
I About Data Source Login Types
I About Data Source Platform Types
I About Authentication
I About Connections
I About Connection Pools
I About Data Partitioning Policies
I About Clustered Databases and Oracle RAC
8.1 About Externally Managed Transactional Data Sources
EclipseLink transactional data sources are externally managed if the connection pool is
managed by a transaction service (such as an application server controlled transaction
or a JTA transaction). A JTA managed data source or connection pool is commonly
used in Java EE applications and normally required in EJB applications. Use an
externally-managed connection pool as follows:
I Configure the session to use an ExternalTransactionController to integrate
EclipseLinks unit of work with the external transaction service.
I Use the external-transaction-control option to specify the connections login
and inform EclipseLink that the connection is maintained by the external
controller.
I You may need to configure the EclipseLink read connection pool or sequence
connection pool to use a non-JTA connection pool in order to avoid transactional
overhead.
8.2 About Data Source Login Types
The login (if any) associated with a session determines how the EclipseLink runtime
connects to the projects data source.
About Data Source Platform Types
8-2 Understanding EclipseLink
A login includes details of data source access, such as authentication, use of connection
pools, and use of external transaction controllers. A Login owns a data source
platform.
A data source platform includes options specific to a particular data source including
binding, use of native SQL, use of batch writing, and sequencing.
For projects that do not persist to a data source, a login is not required. For projects
that do persist to a data source, a login is always required.
You can use a login in a variety of roles. A logins role determines where and how you
create it. The login role you choose depends on the type of project you are creating and
how you intend to use the login.
There is a session login type for each project type that persists to a data source.
Note that there is no XML login. EclipseLink XML projects are used for nonpersistent,
in-memory object to XML data transformation and consequently there is no data
source to log in to.
If you are creating a project that accesses a relational database, you must configure the
project with a DatabaseLogin. Your choice of DatabasePlatform further customizes
your project for a particular type of database.
8.3 About Data Source Platform Types
EclipseLink abstracts the details of your underlying data source using data source
platform classes. A data source platform is owned by your projects Login.
To configure most platform options, you must use an amendment method, or a
preLogin event listener.
EclipseLink interacts with databases using structured query language (SQL). Because
each database platform uses its own variation on the basic SQL language, EclipseLink
must adjust the SQL it uses to communicate with the database to ensure that the
application runs smoothly.
The type of database platform you choose determines the specific means by which the
EclipseLink runtime accesses the database, including the type of Java Database
Connectivity (JDBC) driver to use. JDBC is an application programming interface
(API) that gives Java applications access to a database. EclipseLink relational projects
rely on JDBC connections to read objects from, and write objects to, the database.
EclipseLink applications use either individual JDBC connections or a JDBC connection
pool, depending on the application architecture.
EclipseLink provides a variety of database-specific platforms that let you customize
your project for your target database. For a list of supported database platforms, see
Section A.1, "Database Support."
Specify your database platform at the project level for all sessions, or override this
project-level configuration at the session level.
8.4 About Authentication
Authentication is the means by which a data source validates a users identity and
determines whether or not the user has sufficient privileges to perform a given action.
Authentication plays a central role in data security and user accountability and
auditing.
For two-tier applications, simple JDBC authentication is usually sufficient.
About Authentication
Understanding Data Access 8-3
The following sections describe the different authentication strategies:
I Simple JDBC Authentication
I Oracle Database Proxy Authentication
I Auditing
8.4.1 Simple JDBC Authentication
When you configure an EclipseLink database login with a user name and password,
EclipseLink provides these credentials to the JDBC driver that you configure your
application to use.
By default, EclipseLink writes passwords to and reads them from the sessions.xml
file in encrypted form using JCE encryption. Optionally, you can configure a different
encryption class.
8.4.2 Oracle Database Proxy Authentication
EclipseLink supports proxy authentication with Oracle Database in Java SE
applications and Java EE applications with the Oracle JDBC driver and external
connection pools only.
Oracle Database proxy authentication delivers the following security benefits:
I A limited trust model, by controlling the users on whose behalf middle tiers can
connect, and the roles the middle tiers can assume for the user.
I Scalability, by supporting user sessions through Oracle Call Interface (OCI) and
thick JDBC, and eliminating the overhead of reauthenticating clients.
I Accountability, by preserving the identity of the real user through to the database,
and enabling auditing of actions taken on behalf of the real user.
I Flexibility, by supporting environments in which users are known to the database,
and in which users are merely "application users" of which the database has no
awareness.
For more information about authentication in Oracle Database, see "Preserving User
Identity in Multitiered Environments" in the Oracle Database Security Guide.
Configure your EclipseLink database login to use proxy authentication to do the
following:
I address the complexities of authentication in a three-tier architecture (such as
client-to-middle-tier and middle-tier-to-database authentication, and client
reauthentication through the middle -tier to the database)
I enhance database audit information (for even triggers and stored procedures) by
using a specific user for database operations, rather than the generic pool user
Note: EclipseLink does not support Oracle Database proxy
authentication with JTA.
Note: Oracle Database supports proxy authentication in three-tiers
only; it does not support it across multiple middle tiers.
About Connections
8-4 Understanding EclipseLink
I simplify VPD/OLS configuration by using a proxy user, rather than setting user
information directly in the session context with stored procedures
8.4.3 Auditing
Regardless of what type of authentication you choose, EclipseLink logs the name of
the user associated with all database operations. Example 81 shows the CONFIG level
EclipseLink logs when a ServerSession connects through the main connection for the
sample user "scott", and a ClientSession uses proxy connection "jeff"
Example 81 Logs with Oracle Database Proxy Authentication
[EclipseLink
Config]--ServerSession(13)--Connection(14)--Thread(Thread[main,5,main])--connecting(DatabaseL
ogin( platform=>Oracle9Platform user name=> "scott" connector=>OracleJDBC10_1_0_
2ProxyConnector datasource name=>DS))
[EclipseLink
Config]--ServerSession(13)--Connection(34)--Thread(Thread[main,5,main])--Connected:
jdbc:oracle:thin:@localhost:1521:orcl
User: SCOTT
[EclipseLink
Config]--ClientSession(53)--Connection(54)--Thread(Thread[main,5,main])--connecting(DatabaseL
ogin(platform=>Oracle9Platform user name=> "scott" connector=>OracleJDBC10_1_0_
2ProxyConnector datasource name=>DS))
[EclipseLink
Config]--ClientSession(53)--Connection(56)--Thread(Thread[main,5,main])--Connected:
jdbc:oracle:thin:@localhost:1521:orcl
User: jeff
Your database server likely provides additional user auditing options. Consult your
database server documentation for details.
Alternatively, you may consider using the EclipseLink unit of work in conjunction
with your database schema for auditing purposes.
8.5 About Connections
A connection is an object that provides access to a data source by way of the driver
you configure your application to use. Relational projects use JDBC to connect to the
data source; EIS projects use JCA. EclipseLink uses the interface org.eclipse.
persistence.internal.databaseaccess.Accessor to wrap data source connections.
This interface is accessible from certain events.
Typically, when using a server session, EclipseLink uses a different connection for both
reading and writing. This lets you use nontransactional connections for reading and
avoid maintaining connections when not required.
By default, an EclipseLink server session acquires connections lazily: that is, only
during the commit operation of a unit of work. Alternatively, you can configure
EclipseLink to acquire a write connections at the time you acquire a client sessions.
Connections can be allocated from internal or external connection pools.
8.6 About Connection Pools
A connection pool is a service that creates and maintains a shared collection (pool) of
data source connections on behalf of one or more clients. The connection pool provides
a connection to a process on request, and returns the connection to the pool when the
process is finished using it. When it is returned to the pool, the connection is available
for other processes. Because establishing a connection to a data source can be
About Connection Pools
Understanding Data Access 8-5
time-consuming, reusing such connections in a connection pool can improve
performance.
EclipseLink uses connection pools to manage and share the connections used by server
and client sessions. This feature reduces the number of connections required and
allows your application to support many clients.
You can configure your session to use internal connection pools provided by
EclipseLink or external connection pools provided by a JDBC driver or Java EE
container.
You can use connection pools in your EclipseLink application for a variety of
purposes, such as reading, writing, sequencing, and other application-specific
functions.
This section describes the following types of connection pools:
I Internal Connection Pools
I External Connection Pools
I Default (Write) and Read Connection Pools
I Sequence Connection Pools
I Application-Specific Connection Pools
8.6.1 Internal Connection Pools
For non-Java EE applications, you typically use internal connection pools. By default,
EclipseLink sessions use internal connection pools.
Using internal connection pools, you can configure the default (write) and read
connection pools and you can create additional connection pools for object identity, or
any other purpose.
Using internal connection pools, you can optimize the creation of read connections for
applications that read data only to display it and only infrequently modify data.
8.6.2 External Connection Pools
For Java EE applications, you typically use external connection pools.
If you are using an external transaction controller (JTA), you must use external
connection pools to integrate with the JTA.
Using external connection pools, you can use Java to configure the default (write) and
read connection pools and create additional connection pools for object identity, or any
other purpose.
8.6.3 Default (Write) and Read Connection Pools
A server session provides a read connection pool and a write connection pool. These
could be different pools, or if you use external connection pooling, the same
connection pool.
All read queries use connections from the read connection pool and all queries that
write changes to the data source use connections from the write connection pool. You
can configure attributes of the default (write) and read connection pools.
Whenever a new connection is established, EclipseLink uses the connection
configuration you specify in your sessions DatasourceLogin. Alternatively, when you
use an external transaction controller, you can define a separate connection
About Data Partitioning Policies
8-6 Understanding EclipseLink
configuration for a read connection pool to avoid the additional overhead, if
appropriate.
8.6.4 Sequence Connection Pools
An essential part of maintaining object identity is sequencingmanaging the
assignment of unique values to distinguish one instance from another. For more
information, see Section 9.2, "About Cache Type and Size".
Sequencing involves reading and writing a special sequence resource maintained by
your data source.
By default, EclipseLink includes sequence operations in a separate transaction. This
avoids complications during the write transaction, which may lead to deadlocks over
the sequence resource. However, when using an external transaction controller (such
as a JTA data source or connection pool), EclipseLink cannot use a different transaction
for sequencing. Use a sequence connection pool to configure a non-JTA transaction
pool for sequencing. This is required only for table sequencingnot native sequencing.
In each server session, you can create one connection pool, called a sequence
connection pool, that EclipseLink uses exclusively for sequencing. With a sequence
connection pool, EclipseLink satisfies a request for a new object identifier outside of
the transaction from which the request originates. This allows EclipseLink to
immediately commit an update to the sequence resource, which avoids deadlocks.
You should use a sequence connection pool, if the following applies:
I You use table sequencing (that is, non-native sequencing).
I You use external transaction controller (JTA).
You should not use a sequence connection pool, if the following applies:
I You do not use sequencing, or use the data sources native sequencing.
I You have configured the sequence table to avoid deadlocks.
I You use non-JTA data sources.
8.6.5 Application-Specific Connection Pools
When you use internal EclipseLink connection pools in a session, you can create one or
more connection pools that you can use for any application purpose. These are called
named connection pools, as you can give them any name you want and use them for
any purpose.
Typically, use these named connection pools to provide pools of different security
levels. For example, the "default" connection pool may only allow access to specific
tables but the "admin" connection pool may allow access to all tables.
8.7 About Data Partitioning Policies
Data partitioning allows for an application to scale its data across more than a single
database machine. EclipseLink supports data partitioning at the Entity level to allow a
different set of entity instances for the same class to be stored in a different physical
database or different node within a database cluster. Both regular databases and
Note: If you use a sequence connection pool and the original
transaction fails, the sequence operation does not roll back.
About Data Partitioning Policies
Understanding Data Access 8-7
clustered databases are supported. Data can be partitioned both horizontally and
vertically.
Partitioning can be enabled on an entity, a relationship, a query, or a persistence unit.
To configure data partitioning, use the @Partitioned annotation and one or more
partitioning policy annotations. The annotations for defining the different kinds of
policies are:
I @HashPartitioning; Partitions access to a database cluster by the hash of a field
value from the object, such as the object's ID, location, or tenant. The hash indexes
into the list of connection pools/nodes. All write or read requests for objects with
that hash value are sent to the same server. If a query does not include the hash
field as a parameter, it can be sent to all servers and unioned, or it can be left to the
session's default behavior.
I @PinnedPartitioning; Pins requests to a single connection pool/node. This allows
for vertical partitioning.
I @RangePartitioning; Partitions access to a database cluster by a field value from
the object, such as the object's ID, location, or tenant. Each server is assigned a
range of values. All write or read requests for objects with that value are sent to
the same server. If a query does not include the field as a parameter, then it can
either be sent to all servers and unioned, or left to the session's default behavior.
I @ReplicationPartitioning; Sends requests to a set of connection pools/nodes.
This policy is for replicating data across a cluster of database machines. Only
modification queries are replicated.
I @RoundRobinPartitioning; Sends requests in a round-robin fashion to the set of
connection pools/nodes. It is for load balancing read queries across a cluster of
database machines. It requires that the full database be replicated on each
machine, so it does not support partitioning. The data should either be read-only,
or writes should be replicated.
I @UnionPartitioning; Sends queries to all connection pools and unions the results.
This is for queries or relationships that span partitions when partitioning is used,
such as on a ManyToMany cross partition relationship.
I @ValuePartitioning; Partitions access to a database cluster by a field value from
the object, such as the object's location or tenant. Each value is assigned a specific
server. All write or read requests for objects with that value are sent to the same
server. If a query does not include the field as a parameter, then it can be sent to all
servers and unioned, or it can be left to the session's default behavior.
I @Partitioning; Partitions access to a database cluster by a custom partitioning
policy. A PartitioningPolicy class must be provided and implemented.
Partitioning policies are globally-named objects in a persistence unit and are reusable
across multiple descriptors or queries. This improves the usability of the configuration,
specifically with JPA annotations and metadata.
The persistence unit properties support adding named connection pools in addition to
the existing configuration for read/write/sequence. A named connection pool must be
defined for each node in the database cluster.
If a transaction modifies data from multiple partitions, JTA should be used to ensure
2-phase commit of the data. An exclusive connection can also be configured in the
EntityManager to ensure only a single node is used for a single transaction.
About Clustered Databases and Oracle RAC
8-8 Understanding EclipseLink
8.8 About Clustered Databases and Oracle RAC
Some databases support clustering the database across multiple machines. Oracle RAC
allows for a single database to span multiple different server nodes. Oracle RAC also
supports table and node partitioning of data. A database cluster allows for any of the
data to be accessed from any node in the cluster. However, it is generally more efficient
to partition the data access to specific nodes, to reduce cross node communication.
EclipseLink partitioning can be used in conjunction with a clustered database to
reduce cross node communication, and improve scalability.
To use partitioning with a database cluster to following is required:
I The partition policy should not enable replication, as the database cluster makes
data available to all nodes.
I The partition policy should not use unions, as the database cluster returns the
complete query result from any node.
I A data source and EclipseLink connection pool should be defined for each node in
the cluster.
I The application's data access and data partitioning should be designed to have
each transaction only require access to a single node.
I Use of an exclusive connection for an EntityManager is recommended to avoid
having multiple nodes in a single transaction and avoid 2-phase commit.
9
Understanding Caching 9-1
9Understanding Caching
The EclipseLink cache is an in-memory repository that stores recently read or written
objects based on class and primary key values. The cache improves performance by
holding recently read or written objects and accessing them in-memory to minimize
database access, manage locking and isolation level, and manage object identity.
EclipseLink defines the following entity caching annotations:
I @Cache
I @TimeOfDay
I @ExistenceChecking
EclipseLink also provides a number of persistence unit properties that you can specify
to configure the EclipseLink cache. These properties may compliment or provide an
alternative to annotations. For more information on these annotations and properties,
see Java Persistence API (JPA) Extensions Reference for EclipseLink.
This chapter contains the following sections:
I About Cache Architecture
I About Cache Type and Size
I About Queries and the Cache
I About Handling Stale Data
I About Explicit Query Refreshes
I About Cache Expiration and Invalidation
I About Cache Indexes
I About Query Results Cache
I About Cache Locking and Transaction Isolation
I About Cache Optimization
I About Cache Coordination
9.1 About Cache Architecture
EclipseLink uses two types of cache: the shared persistence unit cache (L2) maintains
objects retrieved from and written to the data source; and the isolated persistence
context cache (L1) holds objects while they participate in transactions. When a
persistence context (entity manager) successfully commits to the data source,
EclipseLink updates the persistence unit cache accordingly. Conceptually the
About Cache Architecture
9-2 Understanding EclipseLink
persistence context cache is represented by the EntityManager and the persistence unit
cache is represented by the EntityManagerFactory.
Internally, EclipseLink stores the persistence unit cache on a EclipseLink session, and
the persistence context cache on a EclipseLink unit of work. As Figure 91 shows, the
persistence unit cache (session) cache and the persistence context cache (unit of work
cache) work together with the data source connection to manage objects in a
EclipseLink application. The object life cycle relies on these three mechanisms.
Figure 91 Object Life Cycle and the EclipseLink Caches
9.1.1 Persistence Unit Cache
The persistence unit cache is a shared cache (L2) that services clients attached to a
given persistence unit. When you read objects from or write objects to the data source
using an EntityManager object, EclipseLink saves a copy of the objects in the
persistence unit's cache and makes them accessible to all other processes accessing the
same persistence unit.
EclipseLink adds objects to the persistence unit cache from the following:
I The data store, when EclipseLink executes a read operation
I The persistence context cache, when a persistence context successfully commits a
transaction
EclipseLink defines three cache isolation levels: Isolated, Shared and Protected. For
more information on these levels, see Section 9.1.3, "Shared, Isolated, Protected, Weak,
and Read-only Caches."
There is a separate persistence unit cache for each unique persistence unit name.
Although the cache is conceptually stored with the EntityManagerFactory, two
factories with the same persistence unit name will share the same cache (and
effectively be the same persistence unit instance). If the same persistence unit is
deployed in two separate applications in Java EE, their full persistence unit name will
normally still be unique, and they will use separate caches. Certain persistence unit
properties, such as data-source, database URL, user, and tenant id can affect the
unique name of the persistence unit, and result in separate persistence unit instances
and separate caches. The eclipselink.session.name persistence unit property can be
used to force two persistence units to resolve to the same instance and share a cache.
About Cache Architecture
Understanding Caching 9-3
9.1.2 Persistence Context Cache
The persistence context cache is an isolated cache (L1) that services operations within
an EntityManager. It maintains and isolates objects from the persistence unit cache,
and writes changed or new objects to the persistence unit cache after the persistence
context commits changes to the data source.
The life-cycle for the persistence context cache differs between application managed,
and container managed persistence contexts. The unit of work cache services
operations within the unit of work. It maintains and isolates objects from the session
cache, and writes changed or new objects to the session cache after the unit of work
commits changes to the data source.
9.1.2.1 Application Managed Persistence Contexts
An application managed persistence context is created by the application from an
EntityManagerFactory. The application managed persistence context's cache will
remain until the EntityManager is closed or clear() is called. It is important to keep
application managed persistence units short lived, or to make use of clear() to avoid
the persistence context cache from growing too big, or from becoming out of sync with
the persistence unit cache and the database. Typically a separate EntityManager
should be created for each transaction or request.
An extended persistence context has the same caching behavior as an application
managed persistence context, even if it is managed by the container.
EclipseLink also supports a WEAK reference mode option for long lived persistence
contexts, such as two-tier applications. See Section 9.1.3.4, "Weak Reference Mode."
9.1.2.2 Container Managed Persistence Contexts
A container managed persistence context is typically injected into a SessionBean or
other managed object by a Java EE container, or frameworks such as Spring. The
container managed persistence context's cache will only remain for the duration of the
transaction. Entities read in a transaction will become detached after the completion of
the transaction and will require to be merged to be edited in subsequent transactions.
9.1.3 Shared, Isolated, Protected, Weak, and Read-only Caches
EclipseLink defines three cache isolation levels. The cache isolation level defines how
caching for an entity is performed by the persistence unit and the persistence context.
The cache isolation levels are:
I Isolatedentities are only cached in the persistence context, not in the persistence
unit. See Section 9.1.3.1, "Isolated Cache."
I Sharedentities are cached both in the persistence context and persistence unit,
read-only entities are shared and only cached in the persistence unit. See Section 9.
1.3.2, "Shared Cache."
Note: Only committed changes are merged into the shared
persistence unit cache, flush or other operations do not affect the
persistence unit cache until the transaction is committed.
Note: EclipseLink supports accessing an entity's LAZY relationships
after the persistence context has been closed.
About Cache Architecture
9-4 Understanding EclipseLink
I Protectedentities are cached both in the persistence context and persistence unit,
read-only entities are isolated and cached in the persistence unit and persistence
context. See Section 9.1.3.3, "Protected Cache."
9.1.3.1 Isolated Cache
The isolated cache (L1) is the cache stored in the persistence context. It is a
transactional or user session based cache. Setting the cache isolation to ISOLATED for an
entity disables its shared cache. With an isolated cache all queries and find operations
will access the database unless the object has already been read into the persistence
context and refreshing is not used.
Use a isolated cache to do the following:
I avoid caching highly volatile data in the shared cache
I achieve serializable transaction isolation
Each persistence context owns an initially empty isolated cache. The persistence
context's isolated cache is discarded when the persistence context is closed, or the
EntityManager.clear() operation is used.
When you use an EntityManager to read an isolated entity, the EntityManager reads
the entity directly from the database and stores it in the persistence context's isolated
cache. When you read a read-only entity it is still stored in the isolated cache, but is not
change tracked.
The persistence context can access the database using a connection pool or an
exclusive connection. The persistence unit property eclipselink.jdbc.
exclusive-connection.mode can be used to use an exclusive connection. Using an
exclusive connection provides improved user-based security for reads and writes.
Specific queries can also be configured to use the persistence context's exclusive
connection.
9.1.3.2 Shared Cache
The shared cache (L2) is the cache stored in the persistence unit. It is a shared object
cache for the entire persistence unit. Setting the cache isolation to SHARED for an entity
enables its shared cache. With a shared cache queries and find operations will resolve
against the shared cache unless refreshing is used.
Use a shared cache to do the following:
I improve performance by avoiding database access when finding or querying an
entity by Id or index;
I improve performance by avoiding database access when accessing an entity's
relationships;
I preserve object identity across persistence contexts for read-only entities.
When you use an EntityManager to find a shared entity, the EntityManager first
checks the persistence unit's shared cache. If the entity is not in the persistence unit's
shared cache, it will be read from the database and stored in the persistence unit's
shared cache, a copy will also be stored in the persistence context's isolated cache. Any
Note: If an EntityManager contains an exclusive connection, you
must close the EntityManager when you are finished using it. We do
not recommend relying on the finalizer to release the connection when
the EntityManager is garbage-collected. If you are using a managed
persistence context, then you do not need to close it.
About Cache Architecture
Understanding Caching 9-5
query not by Id, and not by an indexed attribute will first access the database. For each
query result row, if the object is already in the shared cache, the shared object (with its
relationships) will be used, otherwise a new object will be built from the row and put
into the shared cache, and a copy will be put into the isolated cache. The isolated copy
is always returned, unless read-only is used. For read-only the shared object is
returned as the isolated copy is not required.
The size and memory usage of the shared cache depends on the entities cache type.
The JPA Cache and EclipseLink JpaCache annotations can also be used to invalidate or
clear the cache.
9.1.3.3 Protected Cache
The protected cache option allows for shared objects to reference isolated objects.
Setting the cache isolation to PROTECTED for an entity enables its shared cache. The
protected option is mostly the same as the shared option, except that protected entities
can have relationships to isolated entities, whereas shared cannot.
Use a protected cache to do the following:
I improve performance by avoiding database access when finding or querying an
entity by Id or index;
I improve performance by avoiding database access when accessing an entity's
relationships to shared entities;
I ensure read-only entities are isolated to the persistence context;
I allow relationships to isolated entities.
Protected entities have the same life-cycle as shared entities, except for relationships,
and read-only. Protected entities relationships to shared entities are cached in the
shared cache, but their relationships to isolated entities are isolated and not cached in
the shared cache. The @Noncacheable annotation can also be used to disable caching of
a relationship to shared entities. Protected entities that are read-only are always copied
into the isolated cache, but are not change tracked.
9.1.3.4 Weak Reference Mode
EclipseLink offers a specialized persistence context cache for long-lived persistence
contexts. Normally it is best to keep persistence contexts short-lived, such as creating a
new EntityManager per request, or per transaction. This is referred to as a stateless
model. This ensures the persistence context does not become too big, causing memory
and performance issues. It also ensures the objects cached in the persistence context do
not become stale or out of sync with their committed state.
Some two-tier applications, or stateful models require long-lived persistence contexts.
EclipseLink offers a special weak reference mode option for these types of
applications. A weak reference mode maintains weak references to the objects in the
persistence context. This allows the objects to garbage-collected if not referenced by
the application. This helps prevent the persistence context from becoming too big,
reducing memory usage and improving performance. Any new, removed or changed
objects will be held with strong references until a commit occurs.
A weak reference mode can be configured through the eclipselink.
persistence-context.reference-mode persistence unit property. The following
options can be used:
I HARDThis is the default, weak references are not used. The persistence context
will grow until cleared or closed.
About Cache Type and Size
9-6 Understanding EclipseLink
I WEAKWeak references are used. Unreferenced unchanged objects will be eligible
for garbage collection. Objects that use deferred change tracking will not be
eligible for garbage collection.
I FORCE_WEAKWeak references are used. Unreferenced, unchanged objects will be
eligible for garbage collection. Changed (but unreferenced) objects that use
deferred change tracking will also be eligible for garbage collection, causing any
changes to be lost.
9.1.3.5 Read-Only Entities
An entity can be configured as read-only using the @ReadOnly annotation or the
read-only XML attribute. A read-only entity will not be tracked for changes and any
updates will be ignored. Read-only entities cannot be persisted or removed. A
read-only entity must not be modified, but EclipseLink does not currently enforce this.
Modification to read-only objects can corrupt the persistence unit cache.
Queries can also be configured to return read-only objects using the eclipselink.
read-only query hint.
A SHARED entity that is read-only will return the shared instance from queries. The
same entity will be returned from all queries from all persistence contexts. Shared
read-only entities will never be copied or isolated in the persistence context. This
improves performance by avoiding the cost of copying the object, and tracking the
object for changes. This both reduces memory, reduces heap usage, and improves
performance. Object identity is also maintained across the entire persistence unit for
read-only entities, allowing the application to hold references to these shared objects.
An ISOLATED or PROTECTED entity that is read-only will still have an isolated copy
returned from the persistence context. This gives some improvement in performance
and memory usage from avoid tracking the object for changes, but it is not as
significant as SHARED entities.
9.2 About Cache Type and Size
EclipseLink provides several different cache types which have different memory
requirements. The size of the cache (in number of cached objects) can also be
configured. The cache type and size to use depends on the application, the possibility
of stale data, the amount of memory available in the JVM and on the machine, the
garbage collection cost, and the amount of data in the database.
By default, EclipseLink uses a SOFT_CACHE with an initial size of 100 objects. The cache
size is not fixed, but just the initial size, EclipseLink will never eject an object from the
cache until it has been garbage collected from memory. It will eject the object if the
CACHE type is used, but this is not recommended. The cache size of the SOFT_CACHE and
HARD_CACHE is also the size of the soft or hard sub-cache that can determine a
minimum number of objects to hold in memory.
You can configure how object identity is managed on a class-by-class basis. The
ClassDescriptor object provides the cache and identity map options described in
Table 91.
Table 91 Cache and Identity Map Options
Option (Cache Type) Caching Guaranteed Identity Memory Use
FULL Cache Type Yes Yes Very High
WEAK Cache Type Yes Yes Low
About Cache Type and Size
Understanding Caching 9-7
There are two other options, NONE, and CACHE. These options are not recommend.
9.2.1 FULL Cache Type
This option provides full caching and guaranteed identity: objects are never flushed
from memory unless they are deleted.
It caches all objects and does not remove them. Cache size doubles whenever the
maximum size is reached. This method may be memory-intensive when many objects
are read. Do not use this option on batch operations.
Oracle recommends using this identity map when the data set size is small and
memory is in large supply.
9.2.2 WEAK Cache Type
This option only caches objects that have not been garbage collected. Any object still
referenced by the application will still be cached.
The weak cache type uses less memory than full identity map but also does not
provide a durable caching strategy across client/server transactions. Objects are
available for garbage collection when the application no longer references them on the
server side (that is, from within the server JVM).
9.2.3 SOFT Cache Type
This option is similar to the weak cache type, except that the cache uses soft references
instead of weak references. Any object still referenced by the application will still be
cached, and objects will only be removed from the cache when memory is low.
The soft identity map allows for optimal caching of the objects, while still allowing the
JVM to garbage collect the objects if memory is low.
9.2.4 SOFT_CACHE and HARD_CACHE Cache Type
These options are similar to the weak cache except that they maintain a most
frequently used sub-cache. The sub-cache uses soft or hard references to ensure that
these objects are not garbage collected, or only garbage collected only if the JVM is low
on memory.
The soft cache and hard cache provide more efficient memory use. They release objects
as they are garbage-collected, except for a fixed number of most recently used objects.
Note that weakly cached objects might be flushed if the transaction spans multiple
client/server invocations. The size of the sub-cache is proportional to the size of the
cache as specified by the size option. You should set the cache size to the number of
objects you wish to hold in your transaction.
Oracle recommends using this cache in most circumstances as a means to control
memory used by the cache.
SOFT Cache Type Yes Yes High
SOFT_CACHE and HARD_CACHE
Cache Type
Yes Yes Medium-high
Table 91 (Cont.) Cache and Identity Map Options
Option (Cache Type) Caching Guaranteed Identity Memory Use
About Cache Type and Size
9-8 Understanding EclipseLink
9.2.5 NONE and CACHE
NONE and CACHE options do not preserve object identity and should only be used in
very specific circumstances. NONE does not cache any objects. CACHE only caches a fixed
number of objects in an LRU fashion. These cache types should only be used if there are
no relationships to the objects.
Oracle does not recommend using these options. To disable caching set the cache
isolation to ISOLATED instead.
9.2.6 Guidelines for Configuring the Cache and Identity Maps
Use the following guidelines when configuring your cache type:
I For objects with a long life span, use a SOFT, SOFT_CACHE or HARD_CACHE cache type.
For more information on when to choose one or the other, see Section 9.2.6.1,
"About the Internals of Weak, Soft, and Hard Cache Types.".
I For objects with a short life span, use a WEAK cache type.
I For objects with a long life span, that have few instances, such as reference data,
use a FULL cache type.
I If caching is not required or desired, disable the shared cache by setting the cache
isolation to ISOLATED.
See Section 9.2.6.1, "About the Internals of Weak, Soft, and Hard Cache Types."
9.2.6.1 About the Internals of Weak, Soft, and Hard Cache Types
The WEAK and SOFT cache types use JVM weak and soft references to ensure that any
object referenced by the application is held in the cache. Once the application releases
its reference to the object, the JVM is free to garbage collection the objects. When a
weak or a soft reference is garbage collected is determined by the JVM. In general,
expect a weak reference to be garbage collected with each JVM garbage-collection
operation.
The SOFT_CACHE and HARD_CACHE cache types contain the following two caches:
I Reference cache: implemented as a LinkedList that contains soft or hard
references, respectively.
I Weak cache: implemented as a Map that contains weak references.
When you create a SOFT_CACHE or HARD_CACHE cache with a specified size, the reference
cache LinkedList is exactly this size. The weak cache Map has the size as its initial size:
the weak cache will grow when more objects than the specified size are read in.
Because EclipseLink does not control garbage collection, the JVM can reap the weakly
held objects whenever it sees fit.
Because the reference cache is implemented as a LinkedList, new objects are added to
the end of the list. Because of this, it is by nature a least recently used (LRU) cache:
Note: Use the FULL cache type only if the class has a small number of
finite instances. Otherwise, a memory leak will occur.
Note: Oracle does not recommend the use of CACHE and NONE cache
types.
About Handling Stale Data
Understanding Caching 9-9
fixed size, object at the top of the list is deleted, provided the maximum size has been
reached.
The SOFT_CACHE and HARD_CACHE are essentially the same type of cache. The HARD_
CACHE was constructed to work around an issue with some JVMs.
If your application reaches a low system memory condition frequently enough, or if
your platform's JVM treats weak and soft references the same, the objects in the
reference cache may be garbage-collected so often that you will not benefit from the
performance improvement provided by it. If this is the case, Oracle recommends that
you use the HARD_CACHE. It is identical to the SOFT_CACHE except that it uses hard
references in the reference cache. This guarantees that your application will benefit
from the performance improvement provided by it.
When an object in a HARD_CACHE or SOFT_CACHE is pushed out of the reference cache, it
gets put in the weak cache. Although it is still cached, EclipseLink cannot guarantee
that it will be there for any length of time because the JVM can decide to
garbage-collect weak references at anytime.
9.3 About Queries and the Cache
A query that is run against the shared session cache is known as an in-memory query.
Careful configuration of in-memory querying can improve performance.
By default, a query that looks for a single object based on primary key attempts to
retrieve the required object from the cache first, and searches the data source only if
the object is not in the cache. All other query types search the database first, by default.
You can specify whether a given query runs against the in-memory cache, the
database, or both.
9.4 About Handling Stale Data
Stale data is an artifact of caching, in which an object in the cache is not the most
recent version committed to the data source. To avoid stale data, implement an
appropriate cache locking strategy.
By default, EclipseLink optimizes concurrency to minimize cache locking during read
or write operations. Use the default EclipseLink isolation level, unless you have a very
specific reason to change it. For more information on isolation levels in EclipseLink,
see Section 9.1.3, "Shared, Isolated, Protected, Weak, and Read-only Caches".
Cache locking regulates when processes read or write an object. Depending on how
you configure it, cache locking determines whether a process can read or write an
object that is in use within another process.
A well-managed cache makes your application more efficient. There are very few cases
in which you turn the cache off entirely, because the cache reduces database access,
and is an important part of managing object identity.
To make the most of your cache strategy and to minimize your applications exposure
to stale data, Oracle recommends the following:
I Configuring a Locking Policy
I Configuring the Cache on a Per-Class Basis
I Forcing a Cache Refresh when Required on a Per-Query Basis
I Configuring Cache Invalidation
I Configuring Cache Coordination
About Handling Stale Data
9-10 Understanding EclipseLink
9.4.1 Configuring a Locking Policy
Make sure you configure a locking policy so that you can prevent or at least identify
when values have already changed on an object you are modifying. Typically, this is
done using optimistic locking. EclipseLink offers several locking policies such as
numeric version field, time-stamp version field, and some or all fields. Optimistic and
pessimistic locking are described in the following sections.
9.4.1.1 Optimistic Locking
Oracle recommends using EclipseLink optimistic locking. With optimistic locking, all
users have read access to the data. When a user attempts to write a change, the
application checks to ensure the data has not changed since the user read the data.
You can use version or field locking policies. Oracle recommends using version
locking policies. For more information, see Section 6.2.4.1, "Optimistic Version Locking
Policies" and Section 6.2.4.1.3, "Optimistic Field Locking Policies".
9.4.1.2 Pessimistic Locking
With pessimistic locking, the first user who accesses the data with the purpose of
updating it locks the data until completing the update. The disadvantage of this
approach is that it may lead to reduced concurrency and deadlocks.
Consider using pessimistic locking support at the query level. See Section 6.2.4.2,
"Pessimistic Locking Policies."
9.4.2 Configuring the Cache on a Per-Class Basis
If other applications can modify the data used by a particular class, use a weaker style
of cache for the class. For example, the SoftCacheWeakIdentityMap or
WeakIdentityMap minimizes the length of time the cache maintains an object whose
reference has been removed.
9.4.3 Forcing a Cache Refresh when Required on a Per-Query Basis
Any query can include a flag that forces EclipseLink to go to the data source for the
most up-to-date version of selected objects and update the cache with this information.
9.4.4 Configuring Cache Invalidation
Using the Descriptor API, you can designate an object as invalid: when any query
attempts to read an invalid object, EclipseLink will go to the data source for the most
up to date version of that object and update the cache with this information. You can
manually designate an object as invalid or use a CacheInvalidationPolicy to control
the conditions under which an object is designated invalid. For more information, see
Section 9.6, "About Cache Expiration and Invalidation".
9.4.5 Configuring Cache Coordination
If your application is primarily read-based and the changes are all being performed by
the same Java application operating with multiple, distributed sessions, you may
consider using the EclipseLink cache coordination feature. Although this will not
prevent stale data, it should greatly minimize it. For more information, see Section 9.
11, "About Cache Coordination".
About Cache Expiration and Invalidation
Understanding Caching 9-11
9.5 About Explicit Query Refreshes
Some distributed systems require only a small number of objects to be consistent
across the servers in the system. Conversely, other systems require that several specific
objects must always be guaranteed to be up-to-date, regardless of the cost. If you build
such a system, you can explicitly refresh selected objects from the database at
appropriate intervals, without incurring the full cost of distributed cache coordination.
To implement this type of strategy, do the following:
1. Configure a set of queries that refresh the required objects.
2. Establish an appropriate refresh policy.
3. Invoke the queries as required to refresh the objects.
9.5.1 Refresh Policy
When you execute a query, if the required objects are in the cache, EclipseLink returns
the cached objects without checking the database for a more recent version. This
reduces the number of objects that EclipseLink must build from database results, and
is optimal for noncoordinated cache environments. However, this may not always be
the best strategy for a coordinated cache environment.
To override this behavior, set a refresh policy that specifies that the objects from the
database always take precedence over objects in the cache. This updates the cached
objects with the data from the database.
You can implement this type of refresh policy on each EclipseLink descriptor, or just
on certain queries, depending upon the nature of the application.
9.6 About Cache Expiration and Invalidation
By default, objects remain in the shared cache until they are explicitly deleted or
garbage collected.
You can configure any entity with an expiry that lets you specify either the number of
milliseconds after which an entity instance should expire from the cache, or a time of
day that all instances of the entity class should expire from the cache. Expiry is set on
the @Cache annotation or <cache> XML element, and can be configured in two ways:
I expiryThe number of milliseconds after which an entity instance will expire.
I expiryTimeOfDayA @TimeOfDay representing the 24-hour time at which all
instances of the entity class will expire from the cache.
When an instance expires, it is only invalidated in the cache. It is not removed from the
cache, but when next accessed it will be refreshed from the database as part of the
query that was used to access it.
The application can also explicitly invalidate objects in the cache using the JPA Cache
API, or the EclipseLink JpaCache API.
Expiry can also be used in the query results cache. See Section 9.8, "About Query
Results Cache."
Invalidation can also be used in a cluster through cache coordination, or from database
events using database event notification. See Section 9.11.4, "Coordinated Cache and
Clustering."
About Cache Indexes
9-12 Understanding EclipseLink
9.6.1 Advanced Cache Invalidation
Alternatively, you can configure any object with a CacheInvalidationPolicy that lets
you specify, either with annotations or XML, under what circumstances a cached
object is invalid. When any query attempts to read an invalid object, EclipseLink will
go to the data source for the most up-to-date version of that object, and update the
cache with this information.
For descriptions of the available CacheInvalidationPolicy instances, see "Setting
Cache Expiration" in Solutions Guide for EclipseLink.
You can configure a cache invalidation policy in the following ways:
I At the project level that applies to all objects
I At the descriptor level to override the project level configuration on a per-object
basis
I At the query level that applies to the results returned by the query
If you configure a query to cache results in its own internal cache, the cache
invalidation policy you configure at the query level applies to the querys internal
cache in the same way it would apply to the session cache.
If you are using a coordinated cache you can customize how EclipseLink
communicates the fact that an object has been declared invalid. See Section 9.11,
"About Cache Coordination".
The EclipseLink CacheInvalidationPolicy API offers a few advanced features that
are not available through annotations or XML. It is also possible to define your own
expiry or invalidation policy by defining your own CacheInvalidationPolicy.
Advanced configuration can be done through using a DescriptorCustomizer to
customize your entity's ClassDescriptor.
Here are a few of the CacheInvalidationPolicy advanced options:
I isInvalidationRandomizedThis allows the invalidation time to be randomized
by 10% to avoid a large number of instances becoming invalid at the same time
and causing a bottleneck in the database load. This is not used by default.
I shouldRefreshInvalidObjectsOnCloneThis ensures that an invalid object
accessed through a relationship from another object will be refreshed in the
persistence context. This is enabled by default.
I shouldUpdateReadTimeOnUpdateThis updates an objects read time when the
object is successfully updated. This is not enabled by default.
9.7 About Cache Indexes
The EclipseLink cache is indexed by the entities Id. This allows the find() operation,
relationships, and queries by Id to obtain cache hits and avoid database access. The
cache is not used by default for any non-Id query. All non-Id queries will access the
database then resolve with the cache for each row returned in the result-set.
Applications tend to have other unique keys in their model in addition to their Id. This
is quite common when a generated Id is used. The application frequently queries on
these unique keys, and it is desirable to be able to obtain cache hits to avoid database
access on these queries.
Cache indexes allow an in-memory index to be created in the EclipseLink cache to
allow cache hits on non-Id fields. The cache index can be on a single field, or on a set
of fields. The indexed fields can be updateable, and although they should be unique,
About Cache Coordination
Understanding Caching 9-13
this is not a requirement. Queries that contain the indexed fields will be able to obtain
cache hits. Only single results can be obtained from indexed queries.
Cache indexes can be configured using the @CacheIndex and @CacheIndexes
annotations and <cache-index> XML element. A @CacheIndex can be defined on the
entity, or on an attribute to index the attribute. Indexes defined on the entity must
define the columnNames used for the index. An index can be configured to be
re-indexed when the object is updated using the updateable attribute.
It is still possible to cache query results for non-indexed queries using the query result
cache. For more information, see Section 9.8, "About Query Results Cache."
9.8 About Query Results Cache
The EclipseLink query results cache allows the results of named queries to be cached,
similar to how objects are cached.
By default in EclipseLink all queries access the database, unless they are by Id, or by
cache-indexed fields. The resulting rows will still be resolved with the cache, and
further queries for relationships will be avoided if the object is cached, but the original
query will always access the database. EclipseLink does have options for querying the
cache, but these options are not used by default, as EclipseLink cannot assume that all
of the objects in the database are in the cache. The query results cache allows for
non-indexed and result list queries to still benefit from caching.
The query results cache is indexed by the name of the query, and the parameters of the
query. Only named queries can have their results cached, dynamic queries cannot use
the query results cache. As well, if you modify a named query before execution, such
as setting hints or properties, then it cannot use the cached results.
The query results cache does not pick up committed changes from the application as
the object cache does. It should only be used to cache read-only objects, or should use
an invalidation policy to avoid caching stale results. Committed changes to the objects
in the result set will still be picked up, but changes that affect the results set (such as
new or changed objects that should be added/removed from the result set) will not be
picked up.
The query results cache supports a fixed size, cache type, and invalidation options.
9.9 About Cache Locking and Transaction Isolation
By default, EclipseLink optimizes concurrency to minimize cache locking during read
or write operations. Use the default EclipseLink transaction isolation configuration
unless you have a very specific reason to change it.
9.10 About Cache Optimization
Tune the EclipseLink cache for each class to help eliminate the need for distributed
cache coordination. Always tune these settings before implementing cache
coordination. For more information, see "Monitoring and Optimizing
EclipseLink-Enabled Applications" in Solutions Guide for EclipseLink.
9.11 About Cache Coordination
The need to maintain up-to-date data for all applications is a key design challenge for
building a distributed application. The difficulty of this increases as the number of
About Cache Coordination
9-14 Understanding EclipseLink
servers within an environment increases. EclipseLink provides a distributed cache
coordination feature that ensures data in distributed applications remains current.
Cache coordination reduces the number of optimistic lock exceptions encountered in a
distributed architecture, and decreases the number of failed or repeated transactions in
an application. However, cache coordination in no way eliminates the need for an
effective locking policy. To effectively ensure working with up-to-date data, cache
coordination must be used with optimistic or pessimistic locking. Oracle recommends
that you use cache coordination with an optimistic locking policy.
You can use cache invalidation to improve cache coordination efficiency. For more
information, see Section 9.6, "About Cache Expiration and Invalidation".
As Figure 92 shows, cache coordination is a session feature that allows multiple,
possibly distributed, instances of a session to broadcast object changes among each
other so that each session's cache is either kept up-to-date or notified that the cache
must update an object from the data source the next time it is read.
Figure 92 Coordinated Session Caches
When sessions are distributed, that is, when an application contains multiple sessions
(in the same JVM, in multiple JVMs, possibly on different servers), as long as the
servers hosting the sessions are interconnected on the network, sessions can
participate in cache coordination. Coordinated cache types that require discovery
services also require the servers to support User Datagram Protocol (UDP)
communication and multicast configuration. For more information, see Section 9.11.2,
"Coordinated Cache Architecture and Types."
This section describes the following:
Note: You cannot use isolated client sessions with cache
coordination. For more information, see Section 9.1.3, "Shared,
Isolated, Protected, Weak, and Read-only Caches."
About Cache Coordination
Understanding Caching 9-15
I When to Use Cache Coordination
I Coordinated Cache Architecture and Types
I Custom Coordinated Cache
I Coordinated Cache and Clustering
9.11.1 When to Use Cache Coordination
Cache coordination can enhance performance and reduce the likelihood of stale data
for applications that have the following characteristics:
I Changes are all being performed by the same Java application operating with
multiple, distributed sessions
I Primarily read-based
I Regularly requests and updates the same objects
To maximize performance, avoid cache coordination for applications that do not have
these characteristics.
For other options to reduce the likelihood of stale data, see Section 9.4, "About
Handling Stale Data."
9.11.2 Coordinated Cache Architecture and Types
You can configure a coordinated cache to broadcast changes using any of the following
communication protocols:
I JMS Coordinated Cache, for the Java Message Service (JMS)
I RMI Coordinated Cache, for Remote Method Invocation (RMI)
9.11.2.1 JMS Coordinated Cache
For a JMS coordinated cache, when a particular session's coordinated cache starts up, it
uses its JNDI naming service information to locate and create a connection to the JMS
server. The coordinated cache is ready when all participating sessions are connected to
the same topic on the same JMS server. At this point, sessions can start sending and
receiving object change messages. You can then configure all sessions that are
participating in the same coordinated cache with the same JMS and JNDI naming
service information.
Example 91 illustrates a persistence.xml file configured for a JMS coordinated
cache.
Example 91 persistence.xml File for JMS Cache Coordination
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
persistence_2_0.xsd"
version="2.0">
<persistence-unit name="acme" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.cache.coordination.protocol" value="jms"/>
<property name="eclipselink.cache.coordination.jms.topic"
value="jms/ACMETopic"/>
About Cache Coordination
9-16 Understanding EclipseLink
<property name="eclipselink.cache.coordination.jms.factory"
value="jms/ACMETopicConnectionFactory"/>
</properties>
</persistence-unit>
</persistence>
For more information on configuring JMS, see "Configuring JMS Cache Coordination
Using Persistence Properties" in Solutions Guide for EclipseLink. See also your JMS
provider's documentation.
9.11.2.2 RMI Coordinated Cache
For an RMI coordinated cache, when a particular session's coordinated cache starts up,
the session binds its connection in its naming service (either an RMI registry or JNDI),
creates an announcement message (that includes its own naming service information),
and broadcasts the announcement to its multicast group. When a session that belongs
to the same multicast group receives this announcement, it uses the naming service
information in the announcement message to establish bidirectional connections with
the newly announced session's coordinated cache. The coordinated cache is ready
when all participating sessions are interconnected in this way, at which point sessions
can start sending and receiving object change messages. You can then configure each
session with naming information that identifies the host on which the session is
deployed.
Example 92 illustrates a persistence.xml file configured for a RMI coordinated
cache.
Example 92 persistence.xml File for RMI Cache Coordination
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
persistence_2_0.xsd"
version="2.0">
<persistence-unit name="acme" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.cache.coordination.protocol" value="rmi"/>
</properties>
</persistence-unit>
</persistence>
For more information, see "Configuring RMI Cache Coordination Using Persistence
Properties" in Solutions Guide for EclipseLink.
9.11.3 Custom Coordinated Cache
Using the classes in org.eclipse.persistence.sessions.coordination package, you
can define your own coordinated cache for custom solutions.
9.11.4 Coordinated Cache and Clustering
An application cluster is a set of middle tier server machines or VMs servicing
requests for a single application, or set of applications. Multiple servers are used to
increase the scalability of the application and/or to provide fault tolerance and high
availability. Typically the same application will be deployed to all of the servers in the
About Cache Coordination
Understanding Caching 9-17
cluster and application requests will be load balanced across the set of servers. The
application cluster will access a single database, or a database cluster. An application
cluster may allow new servers to be added to increase scalability, and for servers to be
removed such as for updates and servicing.
Application clusters can consist of Java EE servers, Web containers, or Java server
applications.
EclipseLink can function in any clustered environment. The main issue in a clustered
environment is utilizing a shared persistence unit (L2) cache. If you are using a shared
cache (enabled by default in EclipseLink projects), then each server will maintain its
own cache, and each caches data can get out of sync with the other servers and the
database.
EclipseLink provides cache coordination in a clustered environment to ensure the
servers caches are is sync.
There are also many other solutions to caching in a clustered environment, including:
I Disable the shared cache (through setting @Cacheable(false), or
@Cache(isolation=ISOLATED)).
I Only cache read-only objects.
I Set a cache invalidation timeout to reduce stale data.
I Use refreshing on objects/queries when fresh data is required.
I Use optimistic locking to ensure write consistency (writes on stale data will fail,
and will automatically invalidate the cache).
I Use database events to invalidate changed data in the cache (such as EclipseLink's
support for Oracle Query Change Notification).
Cache coordination enables a set of persistence units deployed to different servers in
the cluster (or on the same server) to synchronize their changes. Cache coordination
works by each persistence unit on each server in the cluster being able to broadcast
notification of transactional object changes to the other persistence units in the cluster.
EclipseLink supports cache coordination over RMI and JMS. The cache coordination
framework is also extensible so other options could be developed.
Cache coordination works by broadcasting changes for each transaction to the other
servers in the cluster. Each other server will receive the change notification, and either
invalidate the changed objects in their cache, or update the cached objects state with
the changes. Cache coordination occurs after the database commit, so only committed
changes are broadcast.
Cache coordination greatly reduces to chance of an application getting stale data, but
does not eliminate the possibility. Optimistic locking should still be used to ensure
data integrity. Even in a single server application stale data is still possible within a
persistence context unless pessimistic locking is used. Optimistic (or pessimistic)
locking is always required to ensure data integrity in any multi-user system.
9.11.4.1 Persistence Property Extensions for Cache Coordination
EclipseLink includes the following persistence property extensions for caching. For
more information on these extensions, see Java Persistence API (JPA) Extensions Reference
for EclipseLink.
I cache.coordination.channel
I cache.coordination.jms.factory
I cache.coordination.jms.host
About Cache Coordination
9-18 Understanding EclipseLink
I cache.coordination.jms.reuse-topic-publisher
I cache.coordination.jms.topic
I cache.coordination.jndi.initial-context-factory
I cache.coordination.jndi.password
I cache.coordination.jndi.user
I cache.coordination.naming-service
I cache.coordination.propagate-asynchronously
I cache.coordination.protocol
I cache.coordination.remove-connection-on-error
I cache.coordination.rmi.announcement-delay
I cache.coordination.rmi.multicast-group
I cache.coordination.rmi.multicast-group.port
I cache.coordination.rmi.packet-time-to-live
I cache.coordination.rmi.url
I cache.coordination.thread.pool.size
9.11.4.2 Cache Coordination and Oracle WebLogic
Both RMI and JMS cache coordination work with Oracle WebLogic. When a WebLogic
cluster is used JNDI is replicated among the cluster servers, so a cache.coordination.
rmi.url or a cache.coordination.jms.host option is not required. For JMS cache
coordination, the JMS topic should only be deployed to only one of the servers (as of
Oracle WebLogic 10.3.6). It may be desirable to have a dedicated JMS server if the JMS
messaging traffic is heavy.
Use of other JMS services in WebLogic may have other requirements.
9.11.4.3 Cache Coordination and Glassfish
JMS cache coordination works with Glassfish. When a Glassfish cluster is used, JNDI
is replicated among the cluster servers, so a cache.coordination.jms.host option is
not required.
Use of other JMS services in Glassfish may have other requirements.
RMI cache coordination does not work when the JNDI naming service option is used
in a Glassfish cluster. RMI will work if the eclipselink.cache.coordination.
naming-service option is set to rmi. Each server must provide its own eclipselink.
cache.coordination.rmi.url option, either by having a different persistence.xml
file for each server, or by setting the URL as a System property in the server, or
through a customizer.
9.11.4.4 Cache Coordination and IBM WebSphere
JMS cache coordination may have issues on IBM WebSphere. Use of a Message Driven
Bean (MDB) may be required to allow access to JMS. To use an MDB with cache
coordination, set the eclipselink.cache.coordination.protocol option to the value
jms-publishing. The application will also have to deploy an MDB that processes
cache coordination messages in its EAR file.
Example 93 illustrates the Java code required to configure an MDB.
About Cache Coordination
Understanding Caching 9-19
Example 93 Cache Coordination Message Driven Bean
@MessageDriven
public class JMSCacheCoordinationMDB implements MessageListener {

private JMSTopicRemoteConnection connection;

@PersistenceUnit(unitName="acme")
private EntityManagerFactory emf;

public void ejbCreate() {
this.connection = new JMSTopicRemoteConnection(this.emf.
unwrap(ServerSession.class).getCommandManager());
}

public void onMessage(Message message) {
this.connection.onMessage(message);
}

}
About Cache Coordination
9-20 Understanding EclipseLink
10
Understanding Queries 10-1
10Understanding Queries
EclipseLink enables you to create, read, update, and delete persistent objects or data
using queries in both Java EE and non-Java EE applications for both relational and
nonrelational data sources.
This chapter includes the following sections:
I Query Concepts
I About JPQL Queries
I About SQL Query Language
I About the Criteria API
I About Native SQL Queries
I About Advanced Native Query Support
I About JPA Query Hints
I About Query Casting
I About Oracle Extensions for Queries
10.1 Query Concepts
In general, querying a data source means performing an action on or interacting with
the contents of the data source. To do this, you must be able to perform the following:
I Define an action in a syntax native to the data source being queried.
I Apply the action in a controlled fashion.
I Manage the results returned by the action (if any).
You must also consider how the query affects the EclipseLink cache.
This section introduces query concepts unique to EclipseLink, including the following:
I Call Objects
I DatabaseQuery Objects
I Data-Level and Object-Level Queries
I Summary Queries
I Descriptor Query Manager
I EclipseLink Expressions
I Query Keys
Query Concepts
10-2 Understanding EclipseLink
10.1.1 Call Objects
The Call object encapsulates an operation or action on a data source. The EclipseLink
API provides a variety of Call types such as structured query language (SQL), Java
Persistence Query Language (JPQL), and Extensible Markup Language (XML).
You can execute a Call directly or in the context of a DatabaseQuery.
10.1.2 DatabaseQuery Objects
A DatabaseQuery object is an abstraction that associates additional customization and
optimization options with the action encapsulated by a Call. By separating these
options from the Call, EclipseLink can provide sophisticated query capabilities across
all Call types.
10.1.3 Data-Level and Object-Level Queries
Queries can be defined for objects or data, as follows:
I Object-level queries are object-specific and return data as objects in your domain
model. They are the preferred type of query for mapped data. By far, object-level
DatabaseQuery queries are the most common query used in EclipseLink.
I Data-level queries are used to query database tables directly, and are an
appropriate way to work with unmapped data.
10.1.4 Summary Queries
While data-level queries return raw data and object-level queries return objects in your
domain model, summary queries return data about objects. EclipseLink provides
partial object queries to return a set of objects with only specific attributes populated,
and report queries to return summarized (or rolled-up) data for specific attributes of a
set of objects.
10.1.5 Descriptor Query Manager
In addition to storing named queries applicable to a particular class, you can also use
the DescriptorQueryManager to override the default action that EclipseLink defines
for common data source operations.
10.1.6 EclipseLink Expressions
EclipseLink expressions let you specify query search criteria based on your domain
object model. When you execute the query, EclipseLink translates these search criteria
into the appropriate query language for your platform.
The EclipseLink API provides the following two public classes to support expressions:
I The Expression class represents an expression that can be anything from a simple
constant to a complex clause with boolean logic. You can manipulate, group, and
integrate expressions.
I The ExpressionBuilder class is the factory for constructing new expressions.
You can specify a selection criterion as an Expression with DatabaseQuery method
setSelectionCriteria, and in a finder that takes an Expression.
For more information about using EclipseLink expressions, see Chapter 11,
"Understanding EclipseLink Expressions".
About JPQL Queries
Understanding Queries 10-3
10.1.7 Query Keys
A query key is a schema-independent alias for a database field name. Using a query
key, you can refer to a field using a schema-independent alias. In relational projects
only, EclipseLink automatically creates query keys for all mapped attributes. The name
of the query key is the name of the class attribute specified in your object model.
You can configure query keys in a class descriptor or interface descriptor. You can use
query keys in expressions and to query variable one-to-one mappings.
By default, EclipseLink creates query keys for all mapped attributes, but in some
scenarios you may find it beneficial to add your own.
10.2 About JPQL Queries
The Java Persistence Query Language (JPQL) is the query language defined by JPA.
JPQL is similar to SQL, but operates on objects, attributes and relationships instead of
tables and columns. JPQL can be used for reading (SELECT), as well as bulk updates
(UPDATE) and deletes (DELETE). JPQL can be used in a NamedQuery (through annotations
or XML) or in dynamic queries using the EntityManager createQuery() API.
The disadvantage of JPQL is that dynamic queries require performing string
concatenations to build queries dynamically from web forms or dynamic content.
JPQL is also not checked until runtime, making typographical errors more common.
These disadvantages are reduced by using the query criteria API, described in the next
section.
For more information, see Chapter 4 "Query Language" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
10.2.1 Select Queries
Select queries can be used to read objects from the database. Select queries can return a
single object or data element, a list of objects or data elements, or an object array of
multiple objects and data.
10.2.1.1 SELECT Clause
The SELECT clause can contain object expressions, attribute expressions, functions,
sub-selects, constructors and aggregation functions.
10.2.1.1.1 Aggregation functions Aggregation functions can include summary
information on a set of objects. These include MIN, MAX, AVG, SUM, COUNT. These functions
can be used to return a single result, or can be used with a GROUP BY to return multiple
results.
10.2.1.1.2 Constructors The NEW operator can be used with the fully-qualified class
name to return data objects from a JPQL query. These will not be managed objects, and
the class must define a constructor that matches the arguments of the constructor and
their types. Constructor queries can be used to select partial data or reporting data on
objects, and get back a class instance instead of an object array.
10.2.1.2 FROM Clause
The FROM clause defines what is being queried. A typical FROM clause will contain the
entity name being queried and assign it an alias.
About JPQL Queries
10-4 Understanding EclipseLink
JPQL allows for multiple root level objects to be queried. Caution should be used
when doing this, as it can result in Cartesian products of the two tables. The WHERE or
ON clause should ensure the two objects are joined in some way.
The entity name used in JPQL comes from the name attribute of the @Entity
annotation or XML. It defaults to the simple entity class name. EclipseLink also allows
for the fully-qualified class name of the entity to be used.
10.2.1.2.1 JOIN A JOIN clause can also be used in the FROM clause. The JOIN clause
allows any of the object's relationships to be joined into the query so they can be used
in the WHERE clause. JOIN does not mean the relationships will be fetched, unless the
FETCH option is included.
JOIN can be used with OneToOne, ManyToOne, OneToMany, ManyToMany and
ElementColleciton mappings. When used with a collection relationship you can join
the same relationship multiple times to query multiple independent values.
10.2.1.2.2 JOIN FETCH The FETCH option can be used on a JOIN to fetch the related
objects in a single query. This avoids additional queries for each of the object's
relationships, and ensures that the relationships have been fetched if they were LAZY.
EclipseLink also supports batch fetching through query hints.
JOIN FETCH normally allows an alias. The alias should be used with caution, as it can
affect how the resulting objects are built. Objects should normally always have the
same data, no matter how they were queried, this is important for caching and
consistency. This is only an issue if the alias is used in the WHERE clause on a collection
relationship to filter the related objects that will be fetched. This should not be done,
but is sometimes desirable, in which case the query should ensure it has been set to
BYPASS the cache.
10.2.1.2.3 LEFT JOIN By default all joins in JPQL are INNER joins. This means that
results that do not have the relationship will be filtered from the query results. To
avoid this, a join can be defined as an OUTER join using the LEFT options.
10.2.1.2.4 ON The JOIN condition used for a join comes from the mapping's join
columns. This means that the JPQL user is normally free from having to know how
every relationship is joined. In some cases it is desirable to append additional
conditions to the join condition, normally in the case of outer joins. This can be done
through the ON clause. EclipseLink also supports usage of the ON clause between two
root level objects.
For INNER joins, EclipseLink will normally append the join condition to the WHERE
clause, but this can be configured in the DatabasePlatform.
10.2.1.2.5 Sub-selects in FROM clause Sub-selects are supported in the FROM clause. This
requires that the database supports this functionality.
10.2.1.3 ORDER BY clause
ORDER BY allows the ordering of the results to be specified. Multiple values can be
ordered, either ascending (ASC) or descending (DESC). EclipseLink allows functions,
sub-selects and other operations in the ORDER BY clause. EclipseLink allows objects
expressions to be used in the ORDER BY. In the case of entity objects, they are ordered by
their Id, in case of embeddable objects, they are ordered by all of their fields.
EclipseLink also allows for NULL ordering to be specified (either FIRST or LAST).
About JPQL Queries
Understanding Queries 10-5
10.2.1.4 GROUP BY Clause
GROUP BY allows for summary information to be computed on a set of objects. GROUP BY
is normally used in conjunction with aggregation functions. EclipseLink supports
using objects, functions and sub-selects in the GROUP BY clause.
10.2.1.5 HAVING Clause
The HAVING clause allows for the results of a GROUP BY to be filtered. EclipseLink
supports using comparisons, objects, functions and sub-selects in the HAVING clause.
10.2.1.6 UNION
EclipseLink supports UNION, INTERSECT and EXCEPT operations. UNION allows the
results of two queries with equivalent result structures to be combined into a single
query. The unique results from both queries will be returned. If the ALL option is used,
then results found in both queries will be duplicated.
INTERSECT returns only the results that are found in both queries. EXCEPT removes the
results from the second query from the results from the first query.
The JPA spec does not support union operations.
10.2.2 WHERE Clause
The WHERE clause is normally the main part of the query as it defines the conditions
that filter what is returned. The WHERE clause can use any comparison operation,
logical operation, functions, attributes, objects, and sub-selects. The comparison
operations include =, <, >, <=, >=, <>, LIKE, BETWEEN, IS NULL, and IN. NOT can also be
used with any comparison operation (NOT LIKE, NOT BETWEEN, IS NOT NULL, NOT IN). The
logical operations include AND, OR, and NOT.
EclipseLink also supports the REGEXP operation to perform regular expression
comparisons (requires database to support regular expressions). EclipseLink allows for
functions and sub-selects to be used with any operation.
The IN operation allows for a list of values or parameters, a single list parameter, or a
sub-select.
A sub-select can be used with any operation provided it returns a single value, or if the
ALL or ANY options are used. ALL indicates the operation must be true for all elements
returned by the sub-select, ANY indicates the operation must be true for any of the
elements returned by the sub-select.
EclipseLink allows the =, <>, IS NULL, IS NOT NULL, IN and NOT IN operations on objects.
If IN is used on an object and the object has a composite Id, this requires the database
to support nested IN lists.
10.2.3 Update Queries
You can perform bulk update of entities with the UPDATE statement. This statement
operates on a single entity type and sets one or more single-valued properties of the
entity subject to the condition in the WHERE clause. Update queries provide an
equivalent to the SQL UPDATE statement, but with JPQL conditional expressions.
Update queries do not allow joins, but do support sub-selects. OneToOne and
ManyToOne relationships can be traversed in the WHERE clause. Collection
relationships can still be queried through using an EXISTS in the WHERE clause with a
sub-select. Update queries can only update attributes of the object or its embeddables,
About JPQL Queries
10-6 Understanding EclipseLink
its relationships cannot be updated. Complex update queries are dependent on the
database's update support, and may make use of temp tables on some databases.
Update queries should only be used for bulk updates, regular updates to objects
should be made by using the object's set methods within a transaction and committing
the changes.
Update queries return the number of modified rows on the database (row count).
The persistence context is not updated to reflect results of update operations. If you
use a transaction-scoped persistence context, you should either execute the bulk
operation in a transaction all by itself, or be the first operation in the transaction. That
is because any entity actively managed by the persistence context will remain unaware
of the actual changes occurring at the database level.
The objects in the shared cache that match the update query will be invalidated to
ensure subsequent persistence contexts see the updated data.
10.2.4 Delete Queries
You can perform bulk removal of entities with the DELETE statement. Delete queries
provide an equivalent to the SQL DELETE statement, but with JPQL conditional
expressions.
Delete queries do not allow joins, but do support sub-selects. OneToOne and
ManyToOne relationships can be traversed in the WHERE clause. Collection
relationships can still be queried through using an EXISTS in the WHERE clause with a
sub-select. Complex delete queries are dependent on the database's delete support,
and may make use of temp tables on some databases.
Delete queries should only be used for bulk deletes, regular deletes to objects should
be performed through calling the EntityManager remove() API.
Delete queries return the number of deleted rows on the database (row count).
The persistence context is not updated to reflect results of delete operations. If you use
a transaction-scoped persistence context, you should either execute the bulk operation
in a transaction all by itself, or be the first operation in the transaction. That is because
any entity actively managed by the persistence context will remain unaware of the
actual changes occurring at the database level.
The objects in the shared cache that match the delete query will be invalidated to
ensure subsequent persistence contexts do not see the removed objects.
10.2.5 Parameters
JPA defines named parameters, and positional parameters. Named parameters can be
specified in JPQL using the syntax :<name>. Positional parameters can be specified in
JPQL using the syntax ? or ?<position>. Positional parameters start at position 1 not
0.
Note: Delete queries are polymorphic: any entity subclass instances
that meet the criteria of the delete query will be deleted. However,
delete queries do not honor cascade rules: no entities other than the
type referenced in the query and its subclasses will be removed, even
if the entity has relationships to other entities with cascade removes
enabled. Delete queries will delete the rows from join and collection
tables.
About JPQL Queries
Understanding Queries 10-7
10.2.5.1 Literals
Literal values can be in-lined in JPQL for standard Java types. In general it is normally
better to use parameters instead of in-lining values. In-lined arguments will prevent
the JPQL from benefiting from the JPQL parser cache, and can potentially make the
application vulnerable to JPQL injections attacks.
Each Java type defines its own in-lining syntax:
I String - '<string>'
To define a ' (quote) character in a string, the quote is double quoted, i.e.
'Baie-D''Urf'.
I Integer - +|-<digits>
I Long - +|-<digits>L
I Float - +|-<digits>.<decimal><exponent>F
I Double - +|-<digits>.<decimal><exponent>D
I Boolean - TRUE | FALSE
I Date - {d'yyyy-mm-dd'}
I Time - {t'hh:mm:ss'}
I Timestamp - {ts'yyyy-mm-dd hh:mm:ss.nnnnnnnnn'} -
I Enum - package.class.enum
I null - NULL
10.2.6 Functions
JPQL supports several database functions. These functions are database independent
in name and syntax, but require database support. If the database supports an
equivalent function, then the standard JPQL function is supported. If the database
does not provide any way to perform the function, then it is not supported. For
mathematical functions (+, -, /, *) BEDMAS rules apply.
In JPQL, support functions can be used in the SELECT, WHERE, ORDER BY, GROUP BY and
HAVING clauses, as well as inside other functions, with comparison operators, and in
constructors.
EclipseLink provides support for several functions beyond the JPA spec. EclipseLink
also supports calling specific database functions through FUNCTION, FUNC, and
OPERATOR.
10.2.7 EclipseLink Special Operators
EclipseLink defines several special JPQL operators that allow performing database
operations that are not possible in basic JPQL. These include:
I FUNCTION
I OPERATOR
I SQL
I COLUMN
For descriptions of these operators, see "Special Operators" in Java Persistence API (JPA)
Extensions Reference for EclipseLink.
About SQL Query Language
10-8 Understanding EclipseLink
10.2.8 EclipseLink Extensions
EclipseLink provides many extensions to the standard JPA JPQL. These extensions
provide access to additional database features many of which are part of the SQL
standard, provide access to native database features and functions, and provide access
to EclipseLink specific features.
EclipseLink's JPQL extensions include:
I Less restrictions than JPQL, allows sub-selects and functions within operations
such as LIKE, IN, ORDER BY, constructors, functions etc.
I Allow != in place of <>
I FUNCTION operation to call database specific functions
I TREAT operation to downcast related entities with inheritance
I OPERATOR operation to call EclipseLink database independent functions
I SQL operation to mix SQL with JPQL
I CAST and EXTRACT functions
I REGEXP function for regular expression querying
I Usage of sub-selects in the SELECT and FROM clause
I ON clause support for defining JOIN and LEFT JOIN conditions
I Joins between independent entities
I Usage of an alias on a JOIN FETCH
I COLUMN operation to allow querying on non mapped columns
I TABLE operation to allow querying on non mapped tables
I UNION, INTERSECT, EXCEPT support
I Usage of object variables in =, <>, IN, IS NULL, and ORDER BY
For descriptions of these extensions, see "EclipseLink Query Language" in Java
Persistence API (JPA) Extensions Reference for EclipseLink.
10.3 About SQL Query Language
Using EclipseLink, you can express a query using the following query languages:
I SQL Queries
I EclipseLink Expressions (see Chapter 11, "Understanding EclipseLink
Expressions")
In most cases, you can compose a query directly in a given query language or,
preferably, you can construct a DatabaseQuery with an appropriate Call and specify
selection criteria using an Expression object. Although composing a query directly in
SQL appears to be the simplest approach (and for simple operations or operations on
unmapped data, it is), using the DatabaseQuery approach offers the compelling
advantage of confining your query to your domain object model and avoiding
dependence on data source schema implementation details.
Oracle recommends that you compose your queries using Expression.
SQL is the most common query language for applications that use a relational
database data source.
About the Criteria API
Understanding Queries 10-9
You can execute custom SQL directly using Session methods executeSelectingCall
and executeNonSelectingCall, or you can construct a DatabaseQuery with an
appropriate Call.
EclipseLink provides a variety of SQL Call objects for use with stored procedures and,
with Oracle Database, stored functions.
EclipseLink also supports PL/SQL call for Oracle stored procedures with PL/SQL
data types.
10.4 About the Criteria API
The Java Persistence Criteria API is used to define dynamic queries through the
construction of object-based query definition objects, rather than use of the
string-based approach of JPQL. The criteria API allows dynamic queries to be built
programmatically offering better integration with the Java language than a
string-based 4th GL approach.
The Criteria API has two modes, the type-restricted mode, and the non-typed mode.
The type-restricted mode uses a set of JPA meta-model generated classes to define the
query-able attributes of a class, see Section 10.4.8, "Metamodel." The non-typed mode
uses strings to reference attributes of a class.
The criteria API is only for dynamic queries, and cannot be used in meta-data or
named queries. Criteria queries are dynamic queries and do not perform as well as
static named queries, or even dynamic parametrized JPQL which benefit from
EclipseLink's parse cache.
For more information, see Chapter 6 "Criteria API" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
10.4.1 CriteriaBuilder
CriteriaBuilder is the main interface into the Criteria API. A CriteriaBuilder is
obtained from an EntityManager or an EntityManagerFactory using the
getCriteriaBuilder() API. CriteriaBuilder is used to construct CriteriaQuery
objects and their expressions. The Criteria API currently only supports select queries.
10.4.2 CriteriaQuery
CriteriaQuery defines a database select query. A CriteriaQuery models all of the
clauses of a JPQL select query. Elements from one CriteriaQuery cannot be used in
other CriteriaQuerys. A CriteriaQuery is used with the EntityManager
createQuery() API to create a JPA Query.
10.4.3 Where
The where clause is normally the main part of the query as it defines the conditions
(predicates) that filter what is returned. The where clause is defined using the where
API on CriteriaQuery with any Predicate objects. A Predicate is obtained using a
comparison operation, or a logical operation on CriteriaBuilder. The isNull,
isNotNull, and in operations can also be called on Expression objects. The not
operation can also be called on Predicate objects.
About the Criteria API
10-10 Understanding EclipseLink
10.4.4 Subquery
Subqueries can be used in the Criteria API in the select, where, order, group by, or
having clauses. A subquery is created from a CriteriaQuery using the subquery
operation. Most subquery usage restricts the subquery to returning a single result and
value, unless used with the CriteriaBuilder exists, all, any, or some operations, or
with an in operation.
10.4.5 Parameters
Parameters can be defined using the parameter API on CriteriaBuilder. JPA defines
named parameters, and positional parameters. For named parameters the parameter
type and name are specified. For positional parameters only the parameter type is
specified. Positional parameters start at position 1 not 0.
10.4.6 Functions
Several database functions are supported by the Criteria API. All supported
functions are defined on CriteriaBuilder. Some functions may not be supported by
some databases, if they are not SQL compliant, and offer no equivalent function.
10.4.7 Special Operations
The Criteria API defines several special operations that are not database functions,
but have special meaning in JPA. Some of these operations are defined on
CriteriaBuilder and some are on specific Expression interfaces.
10.4.8 Metamodel
JPA defines a meta-model that can be used at runtime to query information about the
ORM mapping metadata. The meta-model includes the list of mapped attributes for a
class, and their mapping types and cardinality. The meta-model can be used with the
Criteria API in place of using strings to reference the class attributes.
JPA defines a set of "_" classes ("_MyEntity.java", for example) that are to be
generated by the JPA provider, or IDE, that give compile time access to the
meta-model. This allows typed static variables to be used in the Criteria API. This can
reduce the occurrence of typos, or invalid queries in application code, by catching
query issues at compile time, instead of during testing. It does however add
complexity to the development process, as the meta-model static class needs to be
generated, and be part of the development cycle.
10.4.9 Tuple Queries
A Tuple defines a multi-select query result. Normally an object array is returned by
JPA multi-select queries, but an object array is not a very useful data structure. A Tuple
is a map-like structure that allows the results to be retrieved by name or index.
10.4.10 JpaCriteriaBuilder and EclipseLink Extensions
EclipseLink's Criteria API support has fewer restrictions than specified by JPA. In
general, sub-queries and object path expressions are allowed in most places, including:
I Sub-queries in the select, group by, and order clauses;
I Sub-query usage with functions;
I in usage with object path expressions;
About Native SQL Queries
Understanding Queries 10-11
I Order by usage with object path expressions.
EclipseLink's Criteria API support is built on top of EclipseLink native
Expression API. EclipseLink provides the JpaCriteriaBuilder interface to allow the
conversion of native Expression objects to and from JPA Expression objects. This
allows the EclipseLink native Expression API to be mixed with the JPA Criteria
API.
The EclipseLink native Expression API provides the following additional
functionality:
I Additional database functions (over 80 database functions are supported)
I Usage of custom ExpressionOperators
I Embedding of SQL within an Expression query
I Usage of sub-selects in the from clause
I ON clause support
I Access to unmapped columns and tables
I Historical querying
EclipseLink Expressions can be combined with EclipseLink DatabaseQuerys to
provide additional functionality:
I Unions, intersect and except clauses;
I Hierarchical connect by clauses;
I Batch fetching.
10.5 About Native SQL Queries
JPA allows SQL to be used for querying entity objects, or data. SQL queries are not
translated, and passed directly to the database. SQL queries can be used for advanced
queries that require database specific syntax, or by users who are more comfortable in
the SQL language than JPQL or Java.
SQL queries are created from the EntityManager using the createNativeQuery API or
via named queries. A Query object is returned and executed the same as any other JPA
query. An SQL query can be created for an entity class, or return an object array of
data. If returning entities, the SQL query must return the column names that the
entity's mappings expect, or an SqlResultSetMapping can be used. An
SqlResultSetMapping allows the SQL result set to be mapped to an entity, or set of
entities and data.
SQL queries can be used to execute SQL or DML (Data Manipulation Language)
statements. For SQL queries that return results, getSingleResult or getResultList
can be used. For SQL queries that do not return results, executeUpdate must be used.
executeUpdate can only be used within a transaction. SQL queries can be used to
execute database operations and some stored procedures and functions. Stored
procedures that return output parameters, or certain complex stored procedures,
cannot be executed with SQL queries. EclipseLink supports stored procedures through
stored procedure queries.
Query settings and query hints that affect the generated SQL are not supported with
SQL queries. Unsupported query hints include:
I batch
I history.as-of
About Advanced Native Query Support
10-12 Understanding EclipseLink
I inheritance.outer-join
I sql.hint
I join-fetchjoin-fetch is supported, but requires that the SQL selects all of the
joined columns.
I fetch-groupfetch-group is supported, but requires that the SQL selects all of
the fetched columns.
I pessimistic-lockpessimistic-lock is supported, but requires that the SQL
locks the result rows.
For descriptions of these extensions, see "EclipseLink Query Language" in Java
Persistence API (JPA) Extensions Reference for EclipseLink.
10.5.1 Parameters
Parameters to SQL queries are delimited using the question mark (?) character. Only
indexed parameters are supported, named parameters are not supported. The index
can be used in the delimiter, such as ?1. Parameter values are set on the Query using
the setParameter API. Indexed parameters start at the index 1 not 0.
10.5.2 Named Native SQL Queries
Native SQL queries can be defined as named queries in annotations or XML using the
NamedNativeQuery annotation or <named-native-query> XML element. Named native
SQL queries are executed the same as any named query.
10.5.3 SQL Result Set Mapping
An SqlResultSetMapping can be used to map the results of an SQL query to an entity
if the result column names do not match what the entity mappings expect. It can also
be used to return multiple entities, or entities and data from a single SQL query.
EntityResult and FieldResult are used to map the SQL query result column to the
entity attribute. ColumnResult can be used to add a data element to the result.
SqlResultSetMappings are defined through annotations or XML using the
@SqlResultSetMapping annotation or <sql-result-set-mapping> XML element. They
are referenced from native SQL queries by name.
10.6 About Advanced Native Query Support
EclipseLink provides an expression framework (also known as EclipseLink Native
Query Support) with which you can express queries in a database-neutral fashion as an
alternative to SQL when writing queries not supported by JPQL. EclipseLink
expressions offer the following advantages over SQL when you access a database:
I Expressions are easier to maintain because the database is abstracted.
I Changes to descriptors or database tables do not affect the querying structures in
the application.
I Expressions enhance readability by standardizing the Query interface so that it
looks similar to traditional Java calling conventions.
I Expressions enable read queries to transparently query between two classes that
share a relationship. If these classes are stored in multiple tables in the database,
EclipseLink automatically generates the appropriate join statements to return
information from both tables.
About JPA Query Hints
Understanding Queries 10-13
I Expressions simplify complex operations.
EclipseLink automatically generates the appropriate SQL from the specified
expression.
The expression framework lets you work with expressions, database queries, call
objects, and native queries.
I JPA Query Using a EclipseLink DatabaseQuery
EclipseLink DatabaseQuery is a query object that provides a robust API for
handling a variety of database query requirements, including reading and writing
at the object level and at the data level.
I JPA Query Using a EclipseLink Call Object
Using the DatabaseQuery method setCall, you can define your own EclipseLink
Call to accommodate a variety of data source options, such as SQL stored
procedures and stored functions.
I Named Parameters in a Native Query
Using EclipseLink, you can specify a named parameter in a native query using the
EclipseLink # convention.
I JPQL Positional Parameters in a Native Query
Using EclipseLink, you can specify positional parameters in a native query using
the Java Persistence Query Language (JPQL) positional parameter ?n convention
to specify a parameter by number.
I JDBC-Style Positional Parameters in a Native Query
Using EclipseLink, you can specify positional parameters in a native query using
the JDBC-style positional parameter ? convention.
10.7 About JPA Query Hints
You can use a query hint to customize or optimize a JPA query. All EclipseLink query
hints are defined in the QueryHints class in the org.eclipse.persistence.config
package.
For descriptions of the query hints available in EclipseLink, see "JPA Query
Customization Extensions" in Java Persistence API (JPA) Extensions Reference for
EclipseLink. See also Section 10.3.1 "NamedQuery Annotation" in the JPA Specification.
http://jcp.org/en/jsr/detail?id=317
Use EclipseLink JPA query hints to:
I Construct a JPA query
I Specify a JPA query using the @QueryHint annotation
When you set a hint, you can set the value using the public static final field in the
appropriate configuration class in org.eclipse.persistence.config package,
including the following:
I HintValues
I CacheUsage
I PessimisticLock
I QueryType
About Query Casting
10-14 Understanding EclipseLink
10.8 About Query Casting
Use query casting to query across attributes in subclasses when using JPA or ORM.
This feature is available in JPQL, EclipseLink Expressions, and Criteria API.
10.8.1 JPA 2.0 Type
Starting with JPA 2.0, it is possible to limit the results or a query to those of a specific
subclass. For example, the expression framework provides Expression.type(Class).
10.8.2 Downcasting in JPQL
In JPQL, downcasting is accomplished in the FROM clause, using TREAT...AS in the JOIN
clause.
10.8.3 JPA Criteria API
Starting with JPA 2.0, the JPA Criteria API includes the casting operator
Expression.as(type). This expression does a simple cast that allows matching of
types within the generics.
EclipseLink extends the Criteria API to allow a cast using Expression.as(type). The
as method checks the hierarchy; and if type is a subclass of the type for the expression
that is being called on, a cast is implemented.
Calling a cast on a JOIN node permanently alters that node. For example, in the
example above, after calling join.as(LargeProject.class), the join refers to a
LargeProject.
10.8.4 EclipseLink Expression Support for Downcast
The Expression.as(Class) can also be used for downcasting. The behavior of using
Expression.as(Class) is as follows:
I An exception is thrown at query execution time if the class that is cast to is not a
subclass of the class of the query key being cast.
I Casts are only allowed on ObjectExpressions (QueryKeyExpression and
ExpressionBuilder). The parent expression of a cast must be an
ObjectExpression.
I Casts use the same outer join settings as the ObjectExpression they modify
I Casts modify their parent expression. As a result, when using a cast with a parallel
expression, you must use a new instance of the parent expression.
I Casting is not supported for TablePerClass inheritance
I It is prudent to do a check for type in a query that does a cast.
I EclipseLink automatically appends type information for cases where the cast
results in a single type; but for classes in the middle of a hierarchy, no type
information is appended to the SQL
10.9 About Oracle Extensions for Queries
When you use EclipseLink with Oracle Database, you can make use of the following
Oracle-specific query features from within your EclipseLink applications:
I Query Hints
About Oracle Extensions for Queries
Understanding Queries 10-15
I Hierarchical Queries
I Flashback Queries
I Stored Functions
10.9.1 Query Hints
Oracle lets you specify SQL query additions called hints that can influence how the
database server SQL optimizer works. This lets you influence decisions usually
reserved for the optimizer. You use hints to specify things such as join order for a join
statement, or the optimization approach for a SQL call.
You specify hints using the DatabaseQuery method setHintString.
For more information, see the performance tuning guide for your database.
10.9.2 Hierarchical Queries
Oracle Database Hierarchical Queries mechanism lets you select database rows based
on hierarchical order. For example, you can design a query that reads the row of a
given employee, followed by the rows of people the employee manages, followed by
their managed employees, and so on.
You specify a hierarchical query clause using DatabaseQuery subclass ReadAllQuery
method setHierarchicalQueryClause.
10.9.3 Flashback Queries
When using EclipseLink with Oracle9i Database (or later), you can acquire a special
historical session where all objects are read as of a past time, and then you can express
read queries depending on how your objects are changing over time.
10.9.4 Stored Functions
A stored function is an Oracle Database mechanism that provides all the capabilities of
a stored procedure in addition to returning a value.
About Oracle Extensions for Queries
10-16 Understanding EclipseLink
11
Understanding EclipseLink Expressions 11-1
11Understanding EclipseLink Expressions
Using the EclipseLink expressions framework, you can specify query search criteria
based on your domain object model.
This chapter includes the following sections:
I About the Expression Framework
I About Expression Components
11.1 About the Expression Framework
The EclipseLink expression framework provides methods through the following
classes:
I The Expression class provides most general functions, such as toUpperCase.
I The ExpressionMath class supplies mathematical methods.
This division of functionality enables EclipseLink expressions to provide similar
mathematical functionality to the java.lang.Math class, but keeps both the
Expression and ExpressionMath classes from becoming unnecessarily complex.
11.1.1 Comparing Expressions to SQL
Expressions offer the following advantages over SQL when you access a database:
I Expressions are easier to maintain because the database is abstracted.
I Changes to descriptors or database tables do not affect the querying structures in
the application.
I Expressions enhance readability by standardizing the Query interface so that it
looks similar to traditional Java calling conventions.
I Expressions allow read queries to transparently query between two classes that
share a relationship. If these classes are stored in multiple tables in the database,
EclipseLink automatically generates the appropriate join statements to return
information from both tables.
I Expressions simplify complex operations.
11.2 About Expression Components
A simple expression usually consists of the following three parts:
I The attribute, which represents a mapped attribute or query key of the persistent
class
About Expression Components
11-2 Understanding EclipseLink
I The operator, which is an expression method that implements boolean logic, such
as GreaterThan, Equal, or Like
I The constant or comparison, which refers to the value used to select the object
In the following code fragment:
expressionBuilder.get("lastName").equal("Smith");
I The attribute is lastName.
I The operator is equal.
I The constant is the string "Smith".
The expressionBuilder substitutes for the object or objects to be read from the
database. In this example, expressionBuilder represents employees.
You can use the following components when constructing an Expression:
I Boolean Logic
I Database Functions and Operators
I Mathematical Functions
I XMLType Functions
I Platform and User-Defined Functions
I Expressions for One-to-One and Aggregate Object Relationships
I Expressions for Joining and Complex Relationships
11.2.1 Boolean Logic
Expressions use standard boolean operators, such as AND, OR, and NOT, and you can
combine multiple expressions to form more complex expressions.
11.2.2 Database Functions and Operators
EclipseLink supports many database functions using standard operator names that are
translated to different databases. EclipseLink operators are supported on any database
that has an equivalent function (or set of functions). For more information and a list of
all supported functions and operators see "OPERATOR" and "FUNCTION" in Java
Persistence API (JPA) Extensions Reference for EclipseLink
11.2.2.1 Database Functions
EclipseLink expressions support a variety of database functions, including, but not
limited to, the following:
I toUpperCase
I toLowerCase
I toDate
I decode
I locate
I monthsBetween
I nextDay
I replace
About Expression Components
Understanding EclipseLink Expressions 11-3
I reverse
I substring
I translate
Database functions let you define more flexible queries. You can use these functions in
either a report query using a SELECT clause, or with comparisons in a querys selection
criteria using a WHERE clause.
You access most functions using Expression methods such as toUpperCase.
Some functions have very specific purpose: you can use ascending and descending
functions only within an ordering expression to place the result in ascending or
descending order.
You can use aggregate functions, such as average, minimum, maximum, sum and so forth,
with the ReportQuery.
11.2.2.2 Database Operators
Operators are relation operations that compare two values. EclipseLink expressions
support the following operators:
I like
I notLike
I equal
I notEqual
I lessThan
I lessThanEqual
I equalsIgnoreCase
I greaterThan
I greaterThanEqual
I in
I notIn
I between
I notBetween
11.2.2.3 Mathematical Functions
Mathematical functions are available through the ExpressionMath class. Mathematical
function support in expressions is similar to the support provided by the Java class
java.lang.Math.
Note: Some functions may be database platform specific.
Note: Ordering is not supported for in-memory queries.
About Expression Components
11-4 Understanding EclipseLink
11.2.2.4 XMLType Functions
You can use the following operators when constructing queries against data mapped
to Oracle Database XMLType column:
I extractTakes an XPath string and returns an XMLType which corresponds to
the part of the original document that matches the XPath.
I extractValueTakes an XPath string and returns either a numerical or string
value based on the contents of the node pointed to by the XPath.
I existsNodeTakes an XPath expression and returns the number of nodes that
match the XPath.
I getStringValGets the string representation of an XMLType object.
I getNumberValGets the numerical representation of an XMLType object.
I isFragmentEvaluates to 0 if the XML is a well formed document. Evaluates to 1
if the document is a fragment.
11.2.3 Platform and User-Defined Functions
You can use the Expression method getFunction to access database functions that
EclipseLink does not support directly. The Expression API includes additional forms
of the getFunction method that allow you to specify arguments. You can also create
your own custom functions. For more information, see Java API Reference for
EclipseLink.
11.2.4 Expressions for One-to-One and Aggregate Object Relationships
Expressions can include an attribute that has a one-to-one relationship with another
persistent class. A one-to-one relationship translates naturally into an SQL join that
returns a single row.
11.2.5 Expressions for Joining and Complex Relationships
You can query against complex relationships, such as one-to-many, many-to-many,
direct collection, and aggregate collection relationships. Expressions for these types of
relationships are more complex to build, because the relationships do not map directly
to joins that yield a single row per object.
This section describes the following:
I About Joins
I Using EclipseLink Expression API for Joins
11.2.5.1 About Joins
A join is a relational database query that combines rows from two or more tables.
Relational databases perform a join whenever multiple tables appear in the query's
FROM clause. The query's select list can select any columns from any of these tables.
An inner join (sometimes called a "simple join") is a join of two or more tables that
returns only those rows that satisfy the join condition.
An outer join extends the result of an inner join. An outer join returns all rows that
satisfy the join condition and also returns some or all of those rows from one table for
which no rows from the other satisfy the join condition. Outer joins can be categorized
as left or right:
About Expression Components
Understanding EclipseLink Expressions 11-5
I A query that performs a left outer join of tables A and B returns all rows from A.
For all rows in A that have no matching rows in B, the database returns null for
any select list expressions containing columns of B.
I A query that performs a right outer join of tables A and B returns all rows from B.
For all rows in B that have no matching rows in A, the database returns null for
any select list expressions containing columns of A.
When you query with a join expression, EclipseLink can use joins to check values from
other objects or other tables that represent parts of the same object. Although this
works well under most circumstances, it can cause problems when you query against a
one-to-one relationship, in which one side of the relationship is not present.
For example, Employee objects may have an Address object, but if the Address is
unknown, it is null at the object level and has a null foreign key at the database level.
When you attempt a read that traverses the relationship, missing objects cause the
query to return unexpected results. Consider the following expression:
(emp.get("firstName").equal("Steve")).or(emp.get("address"). get("city").equal("Ottawa"))
In this case, employees with no address do not appear in the result set, regardless of
their first name. Although not obvious at the object level, this behavior is fundamental
to the nature of relational databases.
Outer joins rectify this problem in the databases that support them. In this example,
the use of an outer join provides the expected result: all employees named Steve
appear in the result set, even if their address is unknown.
To implement an outer join, use Expression method getAllowingNull, rather than
get, and Expression method anyOfAllowingNone, rather than anyOf.
For example:
(emp.get("firstName").equal("Steve")).or(
emp.getAllowingNull("address").get("city").equal("Ottawa"))
Support and syntax for outer joins vary widely between databases and database
drivers. EclipseLink supports outer joins for most databases.
11.2.5.2 Using EclipseLink Expression API for Joins
You can use joins anywhere expressions are used, including: selection-criteria,
ordering, report queries, partial objects, one-to-one relational mappings, and join
reading.
Use the expression API shown in Table 111 to configure inner and outer join
expressions.
To query across a one-to-many or many-to-many relationship, use the anyOf operation.
As its name suggests, this operation supports queries that return all items on the
"many" side of the relationship that satisfy the query criteria.
Table 111 Expression API for Joins
Expression API Type of Join Type of Mapping
get inner one-to-one
getAllowingNull outer one-to-one
anyOf inner one-to-many, many-to-many
anyOfAllowingNone outer one-to-many, many-to-many
About Expression Components
11-6 Understanding EclipseLink
12
Understanding Non-relational Data Sources 12-1
12Understanding Non-relational Data Sources
This chapter describes how to set up your JPA applications to work with a
non-relational data source. There are many types of non-relational data sources. These
include document databases, key-value stores, and various other non-standard
databases, such as MongoDB, Cassandra, and Google BigTable. This chapter focuses
on the NoSQL data source. NoSQL is a classification of database systems that do not
support the SQL standard. EclipseLink supports persistence of Java objects to NoSQL
databases through the Java Persistence API (JPA). EclipseLink native API is also
supported with NoSQL databases.
This chapter contains the following sections:
I NoSQL Platform Concepts
I About NoSQL Persistence Units
I About JPA Applications on the NoSQL Platform
I About Mapping NoSQL Objects
I About Queries and the NoSQL Platform
I About Transactions and the NoSQL Platform
12.1 NoSQL Platform Concepts
NoSQL is a classification of database systems that do not support the SQL standard.
The NoSQL classification can be expanded to include Enterprise Information Systems
(EIS) including application databases, legacy databases, messaging systems, and
transaction processing monitors, such as IMS, VSAM, and ADABASE.
EclipseLink's NoSQL support includes:
I MongoDB
I Oracle NoSQL
I XML files
I JMS
I Oracle AQ
A complete description of EclipseLink support for NoSQL is described in Section A.3,
"Non-SQL Standard Database Support: NoSQL."
NoSQL and EIS data-sources have a Java Connector Architecture (JCA) resource
adapter that supports the Java Connector Architecture Common Client Interface (JCA
CCI).
About NoSQL Persistence Units
12-2 Understanding EclipseLink
There are many different ways to access NoSQL and EIS data-sources. Many NoSQL
data-sources provide a Java API. For EIS data-sources, there are many third party and
custom Java adapters. These APIs are normally non-standard, and low-level, similar to
JDBC. EclipseLink NoSQL support is built on top of such APIs, and offers the rich,
high-level and standard JPA API.
Some NoSQL data-sources support the JDBC API and a subset of the SQL language.
Many third-party vendors provide JDBC drivers for EIS data-sources. EclipseLink
regular JPA support can be used with any compliant JDBC driver. So, if JDBC access is
an option, EclipseLink's NoSQL support is not required, as EclipseLink standard JPA
support can be used.
Some NoSQL data-sources may support JCA. JCA is a Java Enterprise Edition API that
allows connecting to more generic systems than JDBC. JCA is composed of two parts,
a resource adapter layer, and the Common Client Interface (CCI). EclipseLink NoSQL
and EIS support is based on the JCA CCI. For MongoDB, Oracle NoSQL, XML files,
JMS, and Oracle AQ, EclipseLink provides the JCA adapter and EclipseLink
EISPlatform and ConnectionSpec classes. Third party JCA adapters can also be used
with EclipseLink as long as they support the CCI. There are third party JCA vendors,
such as Attunity, that support various EIS data-sources such as IMS, VSAM and
ADABASE.
12.2 About NoSQL Persistence Units
NoSQL persistence units are configured the same as JPA persistence units. The
persistence.xml file is used to define the persistence unit. NoSQL persistence units
can be application managed, JTA managed, injected, or created through Persistence the
same as regular JPA persistence units. NoSQL persistence units do have some specific
persistence unit properties that are required, and have some limitations.
NoSQL defines the following persistence unit properties:
I eclipselink.nosql.connection-spec
I eclipselink.nosql.connection-factory
I eclipselink.nosql.property
I eclipselink.target-databasethis is used to set the NoSQL platform class, or
use org.eclipse.persistence.eis.EISPlatform for a generic platform.
For more information on these properties, see "Persistence Property Extensions
Reference"in Java Persistence API (JPA) Extensions Reference for EclipseLink.
NoSQL persistence units have the following restrictions:
I <jta-data-source>, <non-jta-data-source>these elements are not supported,
as they refer to JDBC DataSources.
I JTAJTA-managed persistence units are supported, but XA transactions may not
be provided unless the NoSQL JCA resource adapter supports JTA.
I javax.jdbc, eclipselink.jdbcJDBC-specific properties are not supported as
NoSQL does not use JDBC.
12.2.1 Persistence Unit Properties for NoSQL Platforms
To use a NoSQL platform you must set both the eclipselink.nosql.connection-spec
to the connection spec class name and the eclipselink.target-database to the
platform class name. Each NoSQL platform also supports platform-specific properties
that can be set using eclipselink.nosql.property. For more information on values
About JPA Applications on the NoSQL Platform
Understanding Non-relational Data Sources 12-3
for MongoDB, Oracle NoSQL, XML, JMS, and Oracle AQ, see "@NoSql" in Java
Persistence API (JPA) Extensions Reference for EclipseLink. See also Section A.3, "Non-SQL
Standard Database Support: NoSQL."
12.3 About JPA Applications on the NoSQL Platform
Mapping to NoSQL data is configured through the EclipseLink @NoSql annotation,
and <no-sql> XML element. @NoSql defines the class as mapping to non-relational
data. @NoSql can be specified with @Entity or @Embeddable classes.
The @NoSql annotation defines a dataType and a dataFormat attribute. The dataType
attribute is the name for the entitys structure; the meaning of the dataType is
dependent on the NoSQL platform. For MongoDB, it is the collection name that the
JSON documents are stored to. For Oracle NoSQL the dataType is the first part of the
major key value. For the XML file adapter it is the file name.
The dataFormat attribute specifies the type of structure the data is stored as. The
dataFormat attribute is defined by the DataFormatType enum.
For examples of configuring an application with the @NoSql annotation, see "@NoSql"
in Java Persistence API (JPA) Extensions Reference for EclipseLinkk
12.3.1 Mapping Restrictions on JPA Annotations
NoSQL supports most JPA annotations and others have different restrictions than
mapping relational data.
Supported mapping annotations:
I @Entitydefines a root level object in the NoSQL data-store.
I @Embeddabledefines an object embedded in another object's data structure.
I @Basic, @Temporal, @Enumerated, @Lob
I @Convert, @Converter, @TypeConverter, @ObjectTypeConverter
I @Access, @Transient, @Mutable
I @Id, @EmbeddedId
I @GeneratedValue, @UuidGenerator
I @Versionis supported, but dependent on the NoSQL data-source to validate
version write conflicts.
I @Embeddeddefines a reference that will be embedded in the parent's data
structure as a nested structure.
I @ElementCollectiondefines a collection of values or embeddables that will be
embedded in the parent's data structure as a list of nested structures.
I @OneToOne, @ManyToOnedefine a relationship to another root level object stored as
a foreign key in the source object's data structure.
I @OneToMany, @ManyToManydefine a relationship to a collection of other root level
object stored as a list of foreign keys in the source object's data structure.
I @Inheritance, @MappedSuperclass, @ClassExtractor
I @Cacheable, @Cache, @ReadOnly, @Noncacheable
I @NamedQueryis supported on NoSQL data-sources that support querying.
About Mapping NoSQL Objects
12-4 Understanding EclipseLink
I @NamedNativeQueryis supported on NoSQL data-sources that support native
querying. The query language is not SQL, but specific to the NoSQL data-store.
I @EntityListeners, @PrePersist, @PreUpdate, @PreRemove, @PreLoad,
@PostPersist, @PostUpdate, @PostRemove, @PostLoad
I @Customizer
Unsupported mapping annotations:
I @Table, @SecondaryTableare not supported, as objects are not mapped to tables,
it is replaced by the dataType on the @NoSql annotation.
I @Column@Field should be used, as data is not stored in table columns, however
@Column is still allowed, but just the name will be used.
I @JoinColumnis not supported; it is replaced by @JoinField.
I @JoinTableis not required or supported; OneToManys and ManyToManys are
stored as collections of Ids embedded in the source object's data structure.
I @CollectionTableis not required or supported; ElementCollections are
embedded in the parent object's data structure.
I @MapKeyColumn, @MapKeyClass, @MapKeyJoinColumnare not currently supported.
I @OrderBy, @OrderColumnare not normally required or supported, as order is
normally maintained by the object's data structure.
I @SequenceGenerator, @TableGeneratorare not directly supported.
I @AttributeOverride, @AssociationOverrideare supported with inheritance,
but are not supported or required with embedded relationships as embedded
objects are nested in their parent object's data structure, not flattened as in the case
of relational data.
I @JoinFetch, @BatchFetchare not supported.
12.4 About Mapping NoSQL Objects
NoSQL maps objects to structured data such as XML or JSON. NoSQL supports
embedded data, embedded collections, and all of the existing JPA mapping
annotations.
To map NoSQL objects, you must define IDs, mapping, embedded objects,
relationships, and locking. For more information, see "Implementing the Solution" in
Solutions Guide for EclipseLink.
12.5 About Queries and the NoSQL Platform
Whether querying is supported in NoSQL depends on the NoSQL platform you are
using. Some NoSQL data-sources may support dynamic querying through their own
query language, others may not support querying at all. The following types of queries
are supported by NoSQL.
I JPQL Queries
I Native Queries
I Interaction Queries
For more information on support for these queries, see "Defining Queries" in Solutions
Guide for EclipseLink.
About Transactions and the NoSQL Platform
Understanding Non-relational Data Sources 12-5
12.6 About Transactions and the NoSQL Platform
The JPA transaction API is supported with NoSQL data-sources. Some NoSQL
data-sources might not support transactions, so the level of transaction support is
dependent on the NoSQL platform. JTA persistence units and transactions are also
supported, but unless the NoSQL adapter is integrated with JTA, no XA or transaction
support will be available.
If the NoSQL data-source does not support transactions, then any database change
such as flush() will be committed directly to the database, and rollback() will not
have any affect. A commit operation that fails will not roll back any successful changes
written before the error. JPA normally does not write to the database until commit or
flush() are called, so there will still be some level of transaction support offered by
the persistence context.
JPA operations persist(), merge(), and remove() are supported.
I MongoDBTransactions are not supported.
I Oracle NoSQLTransactions are not supported.
About Transactions and the NoSQL Platform
12-6 Understanding EclipseLink
13
Understanding Performance Monitoring and Profiling 13-1
13Understanding Performance Monitoring and
Profiling
EclipseLink provides a diverse set of features to measure and optimize application
performance. You can enable or disable most features in the descriptors or session,
making any resulting performance gains global.
Performance considerations are present at every step of the development cycle.
Although this implies an awareness of performance issues in your design and
implementation, it does not mean that you should expect to achieve the best possible
performance in your first pass.
For example, if optimization complicates the design, leave it until the final
development phase. You should still plan for these optimizations from your first
iteration, to make them easier to integrate later.
EclipseLink provides the following means to monitor and profile performance.
I Performance Profiling
I Fetch Group Monitoring
I Performance Monitoring
I Query Monitoring
13.1 Performance Profiling
The EclipseLink performance profiler helps you identify performance problems by
logging performance statistics for every executed query in a given session. The Profiler
is described in "Monitoring and Optimizing EclipseLink-Enabled Applications" in
Solutions Guide for EclipseLink.
13.2 Fetch Group Monitoring
Use the Fetch Group Monitor to measure fetch group field usage. This can be useful
for performance analysis in a complex system.
Enable this monitor using the System property
org.eclipse.persistence.fetchgroupmonitor=true.
The monitor dumps the attribute used for a class every time a new attribute is
accessed.
For more information about fetch groups, see Section 6.2.1, "Fetch Groups".
Performance Monitoring
13-2 Understanding EclipseLink
13.3 Performance Monitoring
Use the Performance Monitor to provide detailed profiling and monitoring
information in a multithreaded server environment.
Enable the monitor in persistence.xml as follows:
<property name="eclipselink.profiler" value="PerformanceMonitor"/>
The performance monitor can also be enabled through code using a
SessionCustomizer.
The performance monitor will output a dump of cumulative statistics every minute to
the EclipseLink log.
The statistics contains three sets of information:
I Info; statistics that are constant informational data, such as the session name, or
time of login.
I Counter; statistics that are cumulative counters of total operations, such as cache
hits, or query executions.
I Timer; statistics that are cumulative measurements of total time (in nano seconds)
for a specific type of operation, reading, writing, database operations.
Statistics are generally grouped in total and also by query type, query class, and query
name. Counters and timers are generally recorded for the same operations, so the time
per operation could also be calculated.
The time in between statistic dumps can be configured through the
PerformanceMonitor API using the setDumpTime(long) API. If dumping the results is
not desired, then the dumpTime attribute can be set to be very large such as Long.MAX_
VALUE. The statistic can also be accessed in a Java program by using the
getOperationTime(String) API.
The performance monitor can also be configured with a profile weight.
The profile weights are defined on SessionProfiler and include:
I NONE; No statistics are recorded.
I NORMAL; Informational statistics are recorded.
I HEAVY; Informational, counter and timer statistics are recorded.
I ALL; All statistics are recorded (this is the default).
Example 131 illustrates sample output from the Performance Monitor.
Example 131 Example Output
Performance Monitor:1279113281664
Operation Value (ns)
Counter:CacheHits 1,375,664
Counter:CacheMisses 127
Counter:ClientSessionCreates 1,204,817
Counter:ConnectCalls 2
Counter:DataModifyQuery 48
Counter:DataModifyQuery:inventory 21
Counter:DataModifyQuery:order 27
Counter:DeleteObjectQuery 67,792
Counter:DeleteObjectQuery:Customer 1
...
Counter:ReadAllQuery 1,041,767.
Query Monitoring
Understanding Performance Monitoring and Profiling 13-3
Counter:ReadAllQuery:Item.findByCategory 733,827
Counter:ReadAllQuery:Item.findByCategory:CacheHits 733,779
Counter:ReadAllQuery:Item.findByCategory:CacheMisses 50
...
Counter:ReadObjectQuery 1,058,273
Counter:ReadObjectQuery:Item:item 130,063
Counter:ReadObjectQuery:Item:item:CacheHits 130,063
Counter:ReadObjectQuery:Item:item:CacheMisses 1
Counter:UnitOfWorkCommits 72,568
Counter:UnitOfWorkCreates 471,491
Counter:UnitOfWorkRollbacks 1
Counter:UpdateObjectQuery 71,498
Counter:UpdateObjectQuery:Customer 62,531
...
Info:LoginTime Wed Jul 14 08:55:41 EDT 2010
Info:SessionName file:/scratch/user_domains/servers/mt-1/app.jar
Timer:Caching 6,411,372,000
Timer:ConnectionManagement 17,225,641,000
Timer:DeleteObjectQuery 41,351,430,000
Timer:DeleteObjectQuery:Customer 4,441,000
Timer:DeleteObjectQuery:Customer:QueryPreparation 86,000
Timer:DeleteObjectQuery:Customer:SqlGeneration 28,000
Timer:DeleteObjectQuery:Customer:SqlPrepare 72,000
Timer:DeleteObjectQuery:Customer:StatementExecute 2,265,000
...
Timer:InsertObjectQuery 69,111,086,000
Timer:Logging 4,236,000
Timer:Merge 1,144,400,000
Timer:ObjectBuilding 31,914,397,000
Timer:QueryPreparation 984,396,000
Timer:ReadAllQuery 260,943,930,000
Timer:ReadAllQuery:Item:Item.findByCategory 14,790,333,000
Timer:ReadAllQuery:Item:Item.findByCategory:ObjectBuilding 250,959,000
Timer:ReadAllQuery:Item:Item.findByCategory:QueryPreparation 1,880,000
Timer:ReadAllQuery:Item:Item.findByCategory:RowFetch 113,552,000
Timer:ReadAllQuery:Item:Item.findByCategory:SqlGeneration 522,000
Timer:ReadAllQuery:Item:Item.findByCategory:SqlPrepare 2,055,000
Timer:ReadAllQuery:Item:Item.findByCategory:StatementExecute 107,382,000
...
Timer:Register 3,272,443,000
Timer:RowFetch 25,340,990,000
Timer:Sequencing 1,352,326,000
Timer:SqlGeneration 6,646,000
Timer:SqlPrepare 19,536,031,000
Timer:StatementExecute 508,589,220,000
Timer:TXAfterCompletion 1,854,152,000
Timer:TXBeforeCompletion 169,381,843,000
Timer:UnitOfWorkCommit 167,483,825,000
Timer:UpdateObjectQuery 46,440,589,000
Timer:UpdateObjectQuery:Customer 40,466,433,000
Timer:UpdateObjectQuery:Customer:QueryPreparation 867,496,000
Timer:UpdateObjectQuery:Customer:SqlGeneration 98,000
Timer:UpdateObjectQuery:Customer:SqlPrepare 1,319,333,000
Timer:UpdateObjectQuery:Customer:StatementExecute 32,901,366,000
13.4 Query Monitoring
Use the Query Monitor to measure query executions and cache hits. This can be useful
for performance analysis in a complex system.
Query Monitoring
13-4 Understanding EclipseLink
Enable the Query Monitor in either of these ways:
I Set the System property org.eclipse.persistence.querymonitor=true.
I In persistence.xml, set <property name="eclipselink.profiler"
value="QueryMonitor"/>
The monitor dumps the number of query cache hits and executions (misses) once
every 100 seconds.
For more information about querying, see Chapter 10, "Understanding Queries."
A
Database and Application Server Support A-1
ADatabase and Application Server Support
EclipseLink supports a number of database platforms and application servers, as
described in the following sections:
I Section A.1, "Database Support"
I Section A.2, "Application Server Support"
I Section A.3, "Non-SQL Standard Database Support: NoSQL"
A.1 Database Support
EclipseLink supports any relational database that is compliant with SQL and has a
compliant JDBC driver. EclipseLink has extended support for several database
platforms. The extended support mainly consists of providing native sequencing
support, schema creation, and certain database functions.
The databases in Table A1 are supported. The Java classes are in the org.eclipse.
persistence.platform.database package and are described in Java API Reference for
EclipseLink.
Table A1 Supported Database Platforms
Database Java Class Features
Apache Derby org.eclipse.persistence.platform.
database.DerbyPlatform
Provides Derby-specific behavior.
Attunity org.eclipse.persistence.platform.
database.AttunityPlatform
Platform class that works with Attunity's Connect
JDBC driver.
dBASE org.eclipse.persistence.platform.
database.DBasePlatform
Provides dBASE-specific behavior, including:
I Writes Time and Timestamp as strings (dBASE
does not support Times or Timestamps)
Firebird org.eclipse.persistence.platform.
database.FirebirdPlatform
Provides Firebird-specific behavior.
H2 org.eclipse.persistence.platform.
database.H2Platform
Provides H2-specific behavior.
Database Support
A-2 Understanding EclipseLink
HyperSQL
DataBase (HSQL)
org.eclipse.persistence.platform.
database.HSQLPlatform
Provides HSQL-specific behavior. Supports HSQL
functionality as of 1.8.1. Features include:
I DDL creation
I IDENTITY sequencing
I SEQUENCE objects
I Functions
I Pagination
IBM Cloudscape org.eclipse.persistence.platform.
database.CloudscapePlatform
Provides CloudScape DBMS-specific behavior.
IBM DB2
Mainframe
org.eclipse.persistence.platform.
database.DB2MainframePlatform
Provides DB2 Mainframe-specific behavior. This
provides for some additional compatibility in certain
DB2 versions on OS390. Features include:
I Specialized CONCAT syntax
IBM DB2 org.eclipse.persistence.platform.
database.DB2Platform
Provides DB2-specific behavior, including:
I Schema creation
I Native SQL for byte[], Date, Time, and
Timestamp
I Table qualified names.
I Stored procedures
I Temporary tables
I Casting
I Database functions
I Identity sequencing
I SEQUENCE sequencing
IBM Informix org.eclipse.persistence.platform.
database.InformixPlatform
Provides Informix-specific behavior, including:
I Types for schema creation.
I Native sequencing using @SERIAL.
Microsoft Access org.eclipse.persistence.platform.
database.AccessPlatformPlatform
Provides Microsoft Access-specific behavior.
Microsoft
SQLServer
org.eclipse.persistence.platform.
database.SQLServerPlatform
Provides Microsoft SQL Server-specific behavior,
including:
I Native SQL for byte[], Date, Time, and
Timestamp.
I Native sequencing using @IDENTITY.
MySQL org.eclipse.persistence.platform.
database.MySQLPlatform
Provides MySQL-specific behavior, including:
I Native SQL for Date, Time, and Timestamp
I Native sequencing
I Mapping of class types to database types for the
schema framework
I Pessimistic locking
I Platform specific operators
Table A1 (Cont.) Supported Database Platforms
Database Java Class Features
Database Support
Database and Application Server Support A-3
Oracle org.eclipse.persistence.platform.
database.OraclePlatform
Provides Oracle Database-specific behavior,
including:
I LOB
I NChar
I XMLType
I TIMESTAMP (TZ, LTZ)
I Native batch writing
I Structured object-relational data-types
I PLSQL datatypes and stored procedures
I VPD, RAC, proxy authentication
I XDK XML parser
I Hierarchical selects (Select by prior)
I Returning clause
I Flashback history and queries
I Stored procedures, output parameters and
output cursors
I Stored functions
I Oracle AQ
Oracle JavaDB org.eclipse.persistence.platform.
database.JavaDBPlatform
Allows the use of JavaDBPlatform as a synonym for
DerbyPlatform.
Oracle TimesTen org.eclipse.persistence.platform.
database.TimesTenPlatform
Provides Oracle TimesTen database-specific behavior.
Oracle TimesTen7 org.eclipse.persistence.platform.
database.TimesTen7Platform
Provides Oracle TimesTen 7 database-specific
behavior.
PointBase org.eclipse.persistence.platform.
database.PointBasePlatform
Provides PointBase database-specific behavior.
PostgreSQL org.eclipse.persistence.platform.
database.PostgreSQLPlatform
Provides PostgreSQL database-specific behavior,
including:
I Native SQL for Date, Time, and Timestamp
I Native sequencing
I Mapping of class types to database types for the
schema framework
I Pessimistic locking
I Platform specific operators
I LIMIT/OFFSET query syntax for select statements
See also PostgreSQL: http://wiki.eclipse.
org/EclipseLink/FAQ/JPA/PostgreSQL
SAP MaxDB org.eclipse.persistence.platform.
database.MaxDBPlatform
Provides MaxDB database-specific behavior.
SAP SyBase
SQLAnywhere
org.eclipse.persistence.platform.
database.SQLAnywherePlatform
Provides SQL Anywhere-specific behavior.
Table A1 (Cont.) Supported Database Platforms
Database Java Class Features
Application Server Support
A-4 Understanding EclipseLink
It also possible to extend EclipseLink to add extended support for additional
platforms. There are also several user-contributed platforms in the EclipseLink
incubator project. See Platform Incubator:
http://wiki.eclipse.
org/EclipseLink/Development/Incubator/Platform
A.2 Application Server Support
EclipseLink can be used with any Java EE application server that meets the software
requirements through the EclipseLink API.
Table A2 lists the application servers for which EclipseLink provides integration
support. The classes listed in the table are concrete subclasses of the EclipseLink org.
eclipse.persistence.platform.server.ServerPlatformBase class, which is
responsible for representing server-specific behavior. These classes determine the
following behavior for the server:
I Which external transaction controller to use
I Whether to enable JTA (external transaction control)
I How to register or unregister for runtime services (JMX or MBean)
I Whether to enable runtime services
I How to launch container Threads
For more information on the Java classes listed in the table, see Java API Reference for
EclipseLink.
Sybase org.eclipse.persistence.platform.
database.SybasePlatform
Provides Sybase-specific behavior, including:
I Native SQL for byte[], Date, Time, and
Timestamp
I Native sequencing using @IDENTITY
Fujitsu Symfoware org.eclipse.persistence.platform.
database.SymfowarePlatform
Provides Symfoware-specific behavior, including:
I DDL Generation
I Outer Join
I Subquery (with limitations)
I Stored Procedure Calls
I Stored Procedure Generation
I Native Sequences/Identifier fields
I JPA Bulk Update/Delete (with limitations)
I Batch Reading
I Batch Writing
I Pessimistic Locking (with limitations)
I First Result/Limit (with limitations)
I Expression Framework (with limitations)
I Delimiters
I Auto Detection
Table A1 (Cont.) Supported Database Platforms
Database Java Class Features
Non-SQL Standard Database Support: NoSQL
Database and Application Server Support A-5
A.2.1 EclipseLink MOXy as the JAXB Provider for Application Servers
EclipseLink MOXy is integrated into the GlassFish and WebLogic application servers
as the JAXB provider. For more information, see the following links:
I GlassFish Server: http://blog.bdoughan.
com/2012/02/glassfish-312-is-full-of-moxy.html
I WebLogic Server: http://blog.bdoughan.
com/2011/12/eclipselink-moxy-is-jaxb-provider-in.html
A.3 Non-SQL Standard Database Support: NoSQL
EclipseLink JPA can be used with NoSQL databases. A Java class can be mapped to a
NoSQL datasource using the @NoSQL annotation or <no-sql> XML element.
EclipseLink also provides JPA access to EIS (Enterprise Information Systems) such as
legacy databases and systems (CICS, ADA, VSAM, IMS, MQ, AQ).
EclipseLinks NoSQL support allows complex hierarchical data to be mapped,
including XML, indexed, and hierarchical mapped data such as JSON data. CRUD
operations, embedded objects and collections, inheritance, and relationships are
supported. A subset of JPQL and the Criteria API are supported, dependent on the
NoSQL database's query support.
It is also possible to add support for other NoSQL data-sources by defining your own
EISPlatform subclass and JCA adapter. There are also several user-contributed
platforms in the EclipseLink incubator project. See "Platform Incubator" at this URL:
http://wiki.eclipse.
org/EclipseLink/Development/Incubator/Platform
Table A3 lists the NoSQL and EIS data-sources that are supported by EclipseLink. For
more information on the Java classes listed in the table, see Java API Reference for
EclipseLink.
Table A2 Supported Application Servers
Server Name Java Classes
IBM WebSphere Application
Server
I org.eclipse.persistence.platform.server.was.WebSphere_6_1_Platform
I org.eclipse.persistence.platform.server.was.WebSphere_7_Platform
I org.eclipse.persistence.platform.server.was.WebSpherePlatform
JBoss Application Server I org.eclipse.persistence.platform.server.jboss.JBossPlatform
Oracle Containers for J2EE
(OC4J)
I org.eclipse.persistence.platform.server.oc4j.Oc4jPlatform
Oracle Sun Application
Server
I org.eclipse.persistence.platform.server.sunas
Oracle WebLogic Server I org.eclipse.persistence.platform.server.wls.WebLogic_10_Platform
I org.eclipse.persistence.platform.server.wls.WebLogic_9_Platform
I org.eclipse.persistence.platform.server.wls.WebLogicPlatform
SAP NetWeaver Application
Server
I org.eclipse.persistence.platform.server.sap.SAPNetWeaver_7_1_
Platform
Non-SQL Standard Database Support: NoSQL
A-6 Understanding EclipseLink
Table A3 Supported NoSQL and EIS Platforms
Data-source Java Class Features
MongoDB org.eclipse.persistence.nosql.
adapters.mongo.MongoPlatform
Provides MongoDB support including:
I MAPPED JSON data
I JPQL and Criteria queries
I Native queries
I hints for READ_PREFERENCE, WRITE_CONCERN, OPTIONS,
SKIP, LIMIT, BATCH_SIZE
Oracle NoSQL org.eclipse.persistence.nosql.
adapters.nosql.
OracleNoSQLPlatform
Provides Oracle NoSQL support including:
I MAPPED key/value data
I XML data
I find() and SELECT all queries
I hints for CONSISTENCY, DURABILITY, TIMEOUT, VERSION
XML files org.eclipse.persistence.eis.
adapters.xmlfile.
XMLFilePlatform
Provides support for persistence to XML file including:
I XML data
I find() and SELECT all queries
I XPath interactions
JMS org.eclipse.persistence.eis.
adapters.jms.JMSPlatform
Provides support for persistence through JMS messaging:
I XML data
I send/receive operations
Oracle AQ org.eclipse.persistence.eis.
adapters.aq.AQPlatform
Provides support for persistence through Oracle AQ
messaging:
I XML data
I enqueue/dequeue operations

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy