blob: 7b7c258bc2b8ae3d023955300189cdbc940cbc90 [file] [log] [blame]
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Apache OpenJPA 3.0 User's Guide</title><link rel="stylesheet" type="text/css" href="css/docbook.css"><meta name="generator" content="DocBook XSL Stylesheets V1.79.1"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="book" id="manual"><div class="titlepage"><div><div><h1 class="title">Apache OpenJPA 3.0 User's Guide</h1></div><div><p class="releaseinfo">Built from OpenJPA version revision 66d2a72cb2252a59086d76983979b6512c887a3b.</p></div><div><p class="copyright">Copyright &copy; 2006-2016 The Apache Software Foundation</p></div><div><p class="pubdate">Last updated on September 3, 2020 at 11:53 AM.</p></div></div><hr></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="part"><a href="#introduction">1. Introduction</a></span></dt><dd><dl><dt><span class="chapter"><a href="#openjpa_intro">1.
About
</a></span></dt><dt><span class="chapter"><a href="#openjpa_legal">2.
Legal
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa_legal_license">1.
License
</a></span></dt><dt><span class="section"><a href="#openjpa_legal_notice">2.
Notice
</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright">3.
Copyrights
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa_legal_copyright_apache">3.1. Apache</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_serp">3.2. Serp</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_sun">3.3. Sun</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_other">3.4. Other</a></span></dt></dl></dd></dl></dd></dl></dd><dt><span class="part"><a href="#jpa_overview">2. Java Persistence API</a></span></dt><dd><dl><dt><span class="chapter"><a href="#jpa_overview_intro">1.
Introduction
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_intro_audience">1.
Intended Audience
</a></span></dt><dt><span class="section"><a href="#jpa_overview_intro_transpers">2.
Lightweight Persistence
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_why">2.
Why JPA?
</a></span></dt><dt><span class="chapter"><a href="#jpa_overview_arch">3.
Java Persistence API Architecture
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_arch_exceptions">1.
JPA Exceptions
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_pc">4.
Entity
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_restrict">1.
Restrictions on Persistent Classes
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_no_arg">1.1.
Default or No-Arg Constructor
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_final">1.2.
Final
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_id">1.3.
Identity Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_version">1.4.
Version Field
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_inheritance">1.5.
Inheritance
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_fields">1.6.
Persistent Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_conclusion">1.7.
Conclusions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_identity">2.
Entity Identity
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_identitycls">2.1.
Identity Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_identity_hierarchy">2.1.1.
Identity Hierarchies
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_callbacks">3.
Lifecycle Callbacks
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_callbacks_methods">3.1.
Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_callbacks_using">3.2.
Using Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_using">3.3.
Using Entity Listeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_exclude">3.4.
Entity Listeners Hierarchy
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_conclusion">4.
Conclusions
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_meta">5.
Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_class">1.
Class Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_entity">1.1.
Entity
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_idclass">1.2.
Id Class
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddablesuper">1.3.
Mapped Superclass
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddable">1.4.
Embeddable
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_entity_listeners">1.5.
EntityListeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_classex">1.6.
Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_field">2.
Field and Property Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_explicit_access">2.1.
Explicit Access
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_transient">2.2.
Transient
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_id">2.3.
Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_gen">2.4.
Generated Value
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embedid">2.5.
Embedded Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_version">2.6.
Version
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_basic">2.7.
Basic
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_fetch">2.7.1.
Fetch Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_embedded">2.8.
Embedded
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytoone">2.9.
Many To One
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_cascade">2.9.1.
Cascade Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetomany">2.10.
One To Many
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_mappedby">2.10.1.
Bidirectional Relations
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetoone">2.11.
One To One
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytomany">2.12.
Many To Many
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_orderby">2.13.
Order By
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_mapkey">2.14.
Map Key
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_fielddefaults">2.15.
Persistent Field Defaults
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_xml">3.
XML Schema
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_complete">4.
Conclusion
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_persistence">6.
Persistence
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_persistence_xml">1.
persistence.xml
</a></span></dt><dt><span class="section"><a href="#jpa_overview_persistence_use">2.
Non-EE Use
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_emfactory">7.
EntityManagerFactory
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_emfactory_obtain">1.
Obtaining an EntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_em">2.
Obtaining EntityManagers
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext">3.
Persistence Context
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_trans">3.1.
Transaction Persistence Context
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_extend">3.2.
Extended Persistence Context
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_emf_properties">4.
Retrieving Properties Information
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_close">5.
Closing the EntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_puutil">6.
PersistenceUnitUtil
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_em">8.
EntityManager
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_em_trans">1.
Transaction Association
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_lifecycle">2.
Entity Lifecycle Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_lifeexamples">3.
Lifecycle Examples
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_identity">4.
Entity Identity Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_cache">5.
Cache Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_query">6.
Query Factory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_locking">7.
Entity Locking
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_properties">8.
Retrieving Properties Information
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_closing">9.
Closing
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_trans">9.
Transaction
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_trans_types">1.
Transaction Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_trans_local">2.
The EntityTransaction Interface
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_query">10.
JPA Query
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_query_api">1.
JPQL API
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_query_basic">1.1.
Query Basics
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_relations">1.2.
Relation Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_embeddables">1.3.
Embeddable Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_join_fetch">1.4.
Fetch Joins
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_functions">1.5.
JPQL Functions
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_inheritance">1.6.
Polymorphic Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_params">1.7.
Query Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_hints">1.8.
Query Hints
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_hints_locking">1.8.1.
Locking Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_locktimeout">1.8.2.
Lock Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_querytimeout">1.8.3.
Query Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_resultset">1.8.4.
Result Set Size Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_isolation">1.8.5.
Isolation Level Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_fetchplan">1.8.6.
Other Fetchplan Hints
</a></span></dt><dt><span class="section"><a href="#d5e3356">1.8.7.
Database-Specific Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_named">1.8.8.
Named Query Hints
</a></span></dt><dt><span class="section"><a href="#multi-hints-handling">1.8.9.
Handling of Multiple Similar Query Hints
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_query_ordering">1.9.
Ordering
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_aggregates">1.10.
Aggregates
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_named">1.11.
Named Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_delete">1.12.
Delete By Query
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_update">1.13.
Update By Query
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref">2.
JPQL Language Reference
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_stmnttypes">2.1.
JPQL Statement Types
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_select">2.1.1.
JPQL Select Statement
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk">2.1.2.
JPQL Update and Delete Statements
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_schematypes">2.2.
JPQL Abstract Schema Types and Query Domains
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_schemanaming">2.2.1.
JPQL Entity Naming
</a></span></dt><dt><span class="section"><a href="#jpa_langref_schemaexample">2.2.2.
JPQL Schema Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_fromclause">2.3.
JPQL FROM Clause and Navigational Declarations
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_from_identifiers">2.3.1.
JPQL FROM Identifiers
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_vars">2.3.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_range">2.3.3.
JPQL Range Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path">2.3.4.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_Joins">2.3.5.
JPQL Joins
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_inner_joins">2.3.5.1.
JPQL Inner Joins (Relationship Joins)
</a></span></dt><dt><span class="section"><a href="#jpa_langref_outer_joins">2.3.5.2.
JPQL Outer Joins
</a></span></dt><dt><span class="section"><a href="#jpa_langref_fetch_joins">2.3.5.3.
JPQL Fetch Joins
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_collection_dec">2.3.6.
JPQL Collection Member Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_clause_and_sql">2.3.7.
JPQL FROM Clause and SQL
</a></span></dt><dt><span class="section"><a href="#jpa_langref_polymorph">2.3.8.
JPQL Polymorphism
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_where">2.4.
JPQL WHERE Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_cond">2.5.
JPQL Conditional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_lit">2.5.1.
JPQL Literals
</a></span></dt><dt><span class="section"><a href="#jpa_langref_idvar">2.5.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path_exp">2.5.3.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_input_params">2.5.4.
JPQL Input Parameters
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_pos_params">2.5.4.1.
JPQL Positional Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_langref_named_params">2.5.4.2.
JPQL Named Parameters
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_cond_comp">2.5.5.
JPQL Conditional Expression Composition
</a></span></dt><dt><span class="section"><a href="#jpa_langref_operators">2.5.6.
JPQL Operators and Operator Precedence
</a></span></dt><dt><span class="section"><a href="#jpa_langref_comparison_expressions">2.5.7.
JPQL Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_between">2.5.8.
JPQL Between Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_in_expressions">2.5.9.
JPQL In Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_like">2.5.10.
JPQL Like Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null">2.5.11.
JPQL Null Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_empty_comp">2.5.12.
JPQL Empty Collection Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_collection_member">2.5.13.
JPQL Collection Member Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_exists">2.5.14.
JPQL Exists Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_all_any">2.5.15.
JPQL All or Any Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_subqueries">2.5.16.
JPQL Subqueries
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_scalar_expressions">2.6.
JPQL Scalar Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_math_expressions">2.6.1.
Arithmetic Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_functional_expressions">2.6.2.
String, Arithmetic, and Datetime Functional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_string_fun">2.6.2.1.
JPQL String Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_arithmetic">2.6.2.2.
JPQL Arithmetic Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_datetime">2.6.2.3.
JPQL Datetime Functions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_case_expressions">2.6.3.
Case Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_entity_type_expressions">2.6.4.
Entity Type Expressions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_group">2.7.
JPQL GROUP BY, HAVING
</a></span></dt><dt><span class="section"><a href="#jpa_langref_select_clause">2.8.
JPQL SELECT Clause
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_resulttype">2.8.1.
JPQL Result Type of the SELECT Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_constructor">2.8.2.
JPQL Constructor Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_select">2.8.3.
JPQL Null Values in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_embeddables">2.8.4.
JPQL Embeddables in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_aggregates">2.8.5.
JPQL Aggregate Functions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_agg_examples">2.8.5.1.
JPQL Aggregate Examples
</a></span></dt><dt><span class="section"><a href="#jpa_langref_numeric_expressions_in_select">2.8.5.2.
JPQL Numeric Expressions in the SELECT Clause
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_langref_orderby">2.9.
JPQL ORDER BY Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk_ops">2.10.
JPQL Bulk Update and Delete
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_values">2.11.
JPQL Null Values
</a></span></dt><dt><span class="section"><a href="#jpa_langref_equality">2.12.
JPQL Equality and Comparison Semantics
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bnf">2.13.
JPQL BNF
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#jpa_overview_criteria">11.
JPA Criteria
</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e5247">1. Constructing a CriteriaQuery</a></span></dt><dt><span class="section"><a href="#d5e5264">2. Executing a CriteriaQuery</a></span></dt><dt><span class="section"><a href="#d5e5271">3. Extension to Criteria API</a></span></dt><dt><span class="section"><a href="#d5e5275">4. Generation of Canonical MetaModel classes</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_sqlquery">12.
SQL Queries
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_sqlquery_create">1.
Creating SQL Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_sqlquery_obj">2.
Retrieving Persistent Objects with SQL
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_mapping">13.
Mapping Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_table">1.
Table
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_unq">2.
Unique Constraints
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_column">3.
Column
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_id">4.
Identity Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence">5.
Generators
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_sequence_seqgen">5.1.
Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_tablegen">5.2.
Table Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_genex">5.3.
Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher">6.
Inheritance
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_single">6.1.
Single Table
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_adv">6.1.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_disadv">6.1.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined">6.2.
Joined
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_adv">6.2.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_disadv">6.2.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc">6.3.
Table Per Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_adv">6.3.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_disadv">6.3.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_together">6.4.
Putting it All Together
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_discrim">7.
Discriminator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_field">8.
Field Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_basic">8.1.
Basic Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_lob">8.1.1.
LOBs
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_enum">8.1.2.
Enumerated
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_temporal">8.1.3.
Temporal Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_basic_example">8.1.4.
The Updated Mappings
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_secondary">8.2.
Secondary Tables
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_embed">8.3.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_rel">8.4.
Direct Relations
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_assoccoll">8.5.
Join Table
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_bidi">8.6.
Bidirectional Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_map">8.7.
Map Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_full">9.
The Complete Mappings
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_conclusion">14.
Conclusion
</a></span></dt></dl></dd><dt><span class="part"><a href="#ref_guide">3. Reference Guide</a></span></dt><dd><dl><dt><span class="chapter"><a href="#ref_guide_intro">1.
Introduction
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_intro_audience">1.
Intended Audience
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_conf">2.
Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_conf_intro">1.
Introduction
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_specify">2.
Runtime Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_devtools">3.
Command Line Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_conf_devtools_format">3.1.
Code Formatting
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_conf_plugins">4.
Plugin Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_openjpa">5.
OpenJPA Properties
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa.AutoClear">5.1.
openjpa.AutoClear
</a></span></dt><dt><span class="section"><a href="#openjpa.AutoDetach">5.2.
openjpa.AutoDetach
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerFactory">5.3.
openjpa.BrokerFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerImpl">5.4.
openjpa.BrokerImpl
</a></span></dt><dt><span class="section"><a href="#openjpa.Callbacks">5.5. openjpa.Callbacks</a></span></dt><dt><span class="section"><a href="#openjpa.ClassResolver">5.6.
openjpa.ClassResolver
</a></span></dt><dt><span class="section"><a href="#openjpa.Compatibility">5.7.
openjpa.Compatibility
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionDriverName">5.8.
openjpa.ConnectionDriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2DriverName">5.9.
openjpa.Connection2DriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory">5.10.
openjpa.ConnectionFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2">5.11.
openjpa.ConnectionFactory2
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryName">5.12.
openjpa.ConnectionFactoryName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Name">5.13.
openjpa.ConnectionFactory2Name
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryMode">5.14.
openjpa.ConnectionFactoryMode
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryProperties">5.15.
openjpa.ConnectionFactoryProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Properties">5.16.
openjpa.ConnectionFactory2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionPassword">5.17.
openjpa.ConnectionPassword
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Password">5.18.
openjpa.Connection2Password
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionProperties">5.19.
openjpa.ConnectionProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Properties">5.20.
openjpa.Connection2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionURL">5.21.
openjpa.ConnectionURL
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2URL">5.22.
openjpa.Connection2URL
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionUserName">5.23.
openjpa.ConnectionUserName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2UserName">5.24.
openjpa.Connection2UserName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionRetainMode">5.25.
openjpa.ConnectionRetainMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCache">5.26.
openjpa.DataCache
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheManager">5.27.
openjpa.DataCacheManager
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheMode">5.28.
openjpa.DataCacheMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheTimeout">5.29.
openjpa.DataCacheTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.DetachState">5.30.
openjpa.DetachState
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicDataStructs">5.31.
openjpa.DynamicDataStructs
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicEnhancementAgent">5.32. openjpa.DynamicEnhancementAgent</a></span></dt><dt><span class="section"><a href="#openjpa.FetchBatchSize">5.33.
openjpa.FetchBatchSize
</a></span></dt><dt><span class="section"><a href="#openjpa.EncryptionProvider">5.34.
openjpa.EncryptionProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.FetchGroups">5.35.
openjpa.FetchGroups
</a></span></dt><dt><span class="section"><a href="#openjpa.FlushBeforeQueries">5.36.
openjpa.FlushBeforeQueries
</a></span></dt><dt><span class="section"><a href="#openjpa.IgnoreChanges">5.37.
openjpa.IgnoreChanges
</a></span></dt><dt><span class="section"><a href="#openjpa.Id">5.38. openjpa.Id</a></span></dt><dt><span class="section"><a href="#openjpa.InitializeEagerly">5.39.
openjpa.InitializeEagerly
</a></span></dt><dt><span class="section"><a href="#openjpa.Instrumentation">5.40.
openjpa.Instrumentation
</a></span></dt><dt><span class="section"><a href="#openjpa.InverseManager">5.41.
openjpa.InverseManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockManager">5.42.
openjpa.LockManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockTimeout">5.43.
openjpa.LockTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.Log">5.44.
openjpa.Log
</a></span></dt><dt><span class="section"><a href="#openjpa.ManagedRuntime">5.45.
openjpa.ManagedRuntime
</a></span></dt><dt><span class="section"><a href="#openjpa.Mapping">5.46.
openjpa.Mapping
</a></span></dt><dt><span class="section"><a href="#openjpa.MaxFetchDepth">5.47.
openjpa.MaxFetchDepth
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataFactory">5.48.
openjpa.MetaDataFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataRepository">5.49.
openjpa.MetaDataRepository
</a></span></dt><dt><span class="section"><a href="#openjpa.Multithreaded">5.50.
openjpa.Multithreaded
</a></span></dt><dt><span class="section"><a href="#openjpa.Optimistic">5.51.
openjpa.Optimistic
</a></span></dt><dt><span class="section"><a href="#openjpa.OptimizeIdCopy">5.52.
openjpa.OptimizeIdCopy
</a></span></dt><dt><span class="section"><a href="#openjpa.OrphanedKeyAction">5.53.
openjpa.OrphanedKeyAction
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalRead">5.54.
openjpa.NontransactionalRead
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalWrite">5.55.
openjpa.NontransactionalWrite
</a></span></dt><dt><span class="section"><a href="#openjpa.ProxyManager">5.56.
openjpa.ProxyManager
</a></span></dt><dt><span class="section"><a href="#openjpa.PostLoadOnMerge">5.57.
openjpa.PostLoadOnMerge
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCache">5.58.
openjpa.QueryCache
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCompilationCache">5.59.
openjpa.QueryCompilationCache
</a></span></dt><dt><span class="section"><a href="#openjpa.ReadLockLevel">5.60.
openjpa.ReadLockLevel
</a></span></dt><dt><span class="section"><a href="#openjpa.RemoteCommitProvider">5.61.
openjpa.RemoteCommitProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.RestoreState">5.62.
openjpa.RestoreState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetainState">5.63.
openjpa.RetainState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetryClassRegistration">5.64.
openjpa.RetryClassRegistration
</a></span></dt><dt><span class="section"><a href="#openjpa.RuntimeUnenhancedClasses">5.65. openjpa.RuntimeUnenhancedClasses</a></span></dt><dt><span class="section"><a href="#openjpa.SavepointManager">5.66.
openjpa.SavepointManager
</a></span></dt><dt><span class="section"><a href="#openjpa.Sequence">5.67.
openjpa.Sequence
</a></span></dt><dt><span class="section"><a href="#openjpa.Specification">5.68.
openjpa.Specification
</a></span></dt><dt><span class="section"><a href="#openjpa.TransactionMode">5.69.
openjpa.TransactionMode
</a></span></dt><dt><span class="section"><a href="#openjpa.UseTCCLinSelectNew">5.70.
openjpa.UseTCCLinSelectNew
</a></span></dt><dt><span class="section"><a href="#openjpa.WriteLockLevel">5.71.
openjpa.WriteLockLevel
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_conf_jdbc">6.
OpenJPA JDBC Properties
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa.jdbc.ConnectionDecorators">6.1.
openjpa.jdbc.ConnectionDecorators
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DBDictionary">6.2.
openjpa.jdbc.DBDictionary
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DriverDataSource">6.3.
openjpa.jdbc.DriverDataSource
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.EagerFetchMode">6.4.
openjpa.jdbc.EagerFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.FetchDirection">6.5.
openjpa.jdbc.FetchDirection
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.JDBCListeners">6.6.
openjpa.jdbc.JDBCListeners
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.LRSSize">6.7.
openjpa.jdbc.LRSSize
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingDefaults">6.8.
openjpa.jdbc.MappingDefaults
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingFactory">6.9.
openjpa.jdbc.MappingFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.QuerySQLCache">6.10.
openjpa.jdbc.QuerySQLCache
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.ResultSetType">6.11.
openjpa.jdbc.ResultSetType
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schema">6.12.
openjpa.jdbc.Schema
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SchemaFactory">6.13.
openjpa.jdbc.SchemaFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schemas">6.14.
openjpa.jdbc.Schemas
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SQLFactory">6.15.
openjpa.jdbc.SQLFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SubclassFetchMode">6.16.
openjpa.jdbc.SubclassFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SynchronizeMappings">6.17.
openjpa.jdbc.SynchronizeMappings
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.TransactionIsolation">6.18.
openjpa.jdbc.TransactionIsolation
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.UpdateManager">6.19.
openjpa.jdbc.UpdateManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_spec_compatibility">6.20. Compatibility with Specification</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_logging">3.
Logging and Auditing
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_logging_channels">1.
Logging Channels
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_openjpa">2.
OpenJPA Logging
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_noop">3.
Disabling Logging
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_log4j">4.
Log4J
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_commons">5.
Apache Commons Logging
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_logging_jdk14">5.1.
JDK java.util.logging
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_logging_slf4j">6.
SLF4J
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_custom">7.
Custom Log
</a></span></dt><dt><span class="section"><a href="#ref_guide_audit">8. OpenJPA Audit</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e9423">8.1. Configuration</a></span></dt><dt><span class="section"><a href="#d5e9445">8.2. Developing custom auditing</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_dbsetup">4.
JDBC
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_builtin">1.
Using the OpenJPA DataSource
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_auto">1.1.
Optional Connection Pooling
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_config">1.2.
Configuring the OpenJPA DataSource
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbcp">1.3.
Configuring Apache Commons DBCP
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_thirdparty">2.
Using a Third-Party DataSource
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_thirdparty_enlist">2.1.
Managed and XA DataSources
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSatRuntime">2.2. Setting the DataSource at runtime</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSPerEM">2.2.1. Using different DataSources for each EntityManager</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSBenefits">2.2.1.1. Benefits</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSLimitations">2.2.1.2. Limitations</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSError">2.2.1.3. Error handling</a></span></dt></dl></dd></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_sqlconn">3.
Runtime Access to DataSource
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport">4.
Database Support
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_dbdictprops">4.1.
DBDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_firebird">4.2.
FirebirdDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_mysql">4.3.
MySQLDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_oracle">4.4.
OracleDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_sybase">4.5.
SybaseDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_db2">4.6.
DB2 Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_delim_id">4.7.
Delimited Identifiers Support
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_isolation">5.
Setting the Transaction Isolation
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_sql92">6.
Setting the SQL Join Syntax
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_multidb">7.
Accessing Multiple Databases
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_retain">8.
Configuring the Use of JDBC Connections
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_stmtbatch">9.
Statement Batching
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_lrs">10.
Large Result Sets
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_def">11.
Default Schema
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_info">12.
Schema Reflection
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_schema_info_list">12.1.
Schemas List
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_info_factory">12.2.
Schema Factory
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_schema_schematool">13.
Schema Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_xml">14.
XML Schema Format
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_pc">5.
Persistent Classes
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_pcclasses">1.
Persistent Class List
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance">2.
Enhancement
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_enhance_build">2.1.
Enhancing at Build Time
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime_container">2.2.
Enhancing JPA Entities on Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime">2.3.
Enhancing at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_dynamic">2.4.
Enhancing Dynamically at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_unenhanced_types">2.5.
Omitting the OpenJPA enhancer
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_interfaces">3. Managed Interfaces</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid">4.
Object Identity
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_oid_datastore">4.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_entitypk">4.2.
Entities as Identity Fields
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_application">4.3.
Application Identity Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_pkgen_autoinc">4.4.
Autoassign / Identity Strategy Caveats
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_inverses">5.
Managed Inverses
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos">6.
Persistent Fields
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_scos_restore">6.1.
Restoring State
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_order">6.2.
Typing and Ordering
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_calendar_timezone">6.3.
Calendar Fields and TimeZones
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy">6.4.
Proxies
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_smart">6.4.1.
Smart Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_lrs">6.4.2.
Large Result Set Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_custom">6.4.3.
Custom Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_serial">6.4.4.
Serialization
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_extern">6.5.
Externalization
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_extern_values">6.5.1.
External Values
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_fetch">7.
Fetch Groups
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_fetch_custom">7.1.
Custom Fetch Groups
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_conf">7.2.
Custom Fetch Group Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_single_field">7.3.
Per-field Fetch Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_impl">7.4.
Implementation Notes
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_perfpack_eager">8.
Eager Fetching
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_perfpack_eager_conf">8.1.
Configuring Eager Fetching
</a></span></dt><dt><span class="section"><a href="#ref_guide_perfpack_eager_consider">8.2.
Eager Fetching Considerations and Limitations
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_meta">6.
Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_factory">1.
Metadata Factory
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_repository">2. Metadata Repository</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa">3.
Additional JPA Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_jpa_datastoreid">3.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_version">3.2.
Surrogate Version
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent">3.3.
Persistent Field Values
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_coll">3.4. Persistent Collection Fields</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_map">3.5. Persistent Map Fields</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_ext">4.
Metadata Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_class">4.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#fetch-groups">4.1.1.
Fetch Groups
</a></span></dt><dt><span class="section"><a href="#data-cache">4.1.2.
Data Cache
</a></span></dt><dt><span class="section"><a href="#detached-state-field">4.1.3.
Detached State
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_field">4.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#dependent">4.2.1.
Dependent
</a></span></dt><dt><span class="section"><a href="#load-fetch-group">4.2.2.
Load Fetch Group
</a></span></dt><dt><span class="section"><a href="#lrs">4.2.3.
LRS
</a></span></dt><dt><span class="section"><a href="#inverse-logical">4.2.4.
Inverse-Logical
</a></span></dt><dt><span class="section"><a href="#read-only">4.2.5.
Read-Only
</a></span></dt><dt><span class="section"><a href="#type">4.2.6.
Type
</a></span></dt><dt><span class="section"><a href="#externalizer">4.2.7.
Externalizer
</a></span></dt><dt><span class="section"><a href="#factory">4.2.8.
Factory
</a></span></dt><dt><span class="section"><a href="#external-values">4.2.9.
External Values
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_example">4.3.
Example
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_xml">4.4.
XML extensions
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_mapping">7.
Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_mappingtool">1.
Forward Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_mappingtool_examples">1.1.
Using the Mapping Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_ddl_examples">1.2.
Generating DDL SQL
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_synch">1.3.
Runtime Forward Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_reverse">2.
Reverse Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_reverse_custom">2.1.
Customizing Reverse Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_middle">3.
Meet-in-the-Middle Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_defaults">4.
Mapping Defaults
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_factory">5.
Mapping Factory
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_notes_nonstdjoins">6.
Non-Standard Joins
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa">7.
Additional JPA Mappings
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_datastoreid">7.1.
Datastore Identity Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_version">7.2.
Surrogate Version Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_columns">7.3.
Multi-Column Mappings
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fieldjoin">7.4.
Join Column Attribute Targets
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_embed">7.5.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll">7.6.
Collections
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_table">7.6.1.
Container Table
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_joincols">7.6.2.
Element Join Columns
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_order">7.6.3.
Order Column
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_onemany">7.7.
One-Sided One-Many Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map">7.8.
Maps
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keycols">7.8.1. Key Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keyjoincols">7.8.2. Key Join Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_embedkey">7.8.3. Key Embedded Mapping</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_ex">7.8.4. Examples</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_constraints">7.9.
Indexes and Constraints
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_index">7.9.1.
Indexes
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fk">7.9.2.
Foreign Keys
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_unique">7.9.3.
Unique Constraints
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_xmlmapping">7.10.
XML Column Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_streamsupport">7.11.
LOB Streaming
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_limits">8.
Mapping Limitations
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_limits_tpc">8.1.
Table Per Class
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_ext">9.
Mapping Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_ext_cls">9.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#subclass-fetch-mode">9.1.1.
Subclass Fetch Mode
</a></span></dt><dt><span class="section"><a href="#class-strategy">9.1.2.
Strategy
</a></span></dt><dt><span class="section"><a href="#discriminator-strategy">9.1.3.
Discriminator Strategy
</a></span></dt><dt><span class="section"><a href="#version-strategy">9.1.4.
Version Strategy
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_ext_field">9.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#eager-fetch-mode">9.2.1.
Eager Fetch Mode
</a></span></dt><dt><span class="section"><a href="#nonpolymorphic">9.2.2.
Nonpolymorphic
</a></span></dt><dt><span class="section"><a href="#class-criteria">9.2.3.
Class Criteria
</a></span></dt><dt><span class="section"><a href="#strategy">9.2.4.
Strategy
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_custom">10.
Custom Mappings
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_custom_class">10.1.
Custom Class Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_versdiscrim">10.2.
Custom Discriminator and Version Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field">10.3.
Custom Field Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_custom_vhandler">10.3.1.
Value Handlers
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_fieldstrat">10.3.2.
Field Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field_conf">10.3.3.
Configuration
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_orphan">11.
Orphaned Keys
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_deploy">8.
Deployment
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_deploy_factory">1.
Factory Deployment
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_deploy_factory_standalone">1.1.
Standalone Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_deploy_inject">1.2.
EntityManager Injection
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_enterprise_trans">2.
Integrating with the Transaction Manager
</a></span></dt><dt><span class="section"><a href="#ref_guide_enterprise_xa">3.
XA Transactions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_enterprise_xa_req">3.1.
Using OpenJPA with XA Transactions
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_runtime">9.
Runtime Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_arch">1.
Architecture
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_broker_finalization">1.1.
Broker Finalization
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_broker_extension">1.2.
Broker Customization and Eviction
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_runtime_jpa">2.
JPA Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_emfactory">2.1.
OpenJPAEntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_em">2.2.
OpenJPAEntityManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquery">2.3.
OpenJPAQuery
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaextent">2.4.
Extent
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpacache">2.5.
StoreCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquerycache">2.6.
QueryResultCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpafetch">2.7.
FetchPlan
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpaentitytransaction">2.8.
OpenJPAEntityTransaction
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpapersistence">2.9.
OpenJPAPersistence
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_locking">3.
Object Locking
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_locking_default">3.1.
Configuring Default Locking
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_runtime">3.2.
Configuring Lock Levels at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_apis">3.3.
Object Locking APIs
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_lockmgr">3.4.
Lock Manager
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_rules">3.5.
Rules for Locking Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_issues">3.6.
Known Issues and Limitations
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_savepoints">4.
Savepoints
</a></span></dt><dd><dl><dt><span class="section"><a href="#reg_guide_savepoints_using">4.1.
Using Savepoints
</a></span></dt><dt><span class="section"><a href="#ref_guide_savepoints_conf">4.2.
Configuring Savepoints
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_enterprise_methodql">5.
MethodQL
</a></span></dt><dt><span class="section"><a href="#ref_guide_sequence">6.
Generators
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_sequence_runtime">6.1.
Runtime Access
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_runtime_pm_event">7.
Transaction Events
</a></span></dt><dt><span class="section"><a href="#ref_guide_enterprise_abstractstore">8.
Non-Relational Stores
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_caching">10.
Caching
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache">1.
Data Cache
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache_conf">1.1.
Data Cache Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_data_cache">1.1.1.
openjpa.DataCache Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_shared_cache_mode_integration">1.1.2.
Integration with JPA standard shared cache mode
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_distribution">1.1.3. Distributing instances across cache partitions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_use">1.2.
Data Cache Usage
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache_use_JPA">1.2.1. Using the JPA standard Cache interface</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_use_openJPA">1.2.2. Using the OpenJPA StoreCache extensions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_statistics">1.3.
Cache Statistics
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_query">1.4.
Query Cache
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_extension">1.5.
Cache Extension
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_notes">1.6.
Important Notes
</a></span></dt><dt><span class="section"><a href="#datastore_cache_issues">1.7.
Known Issues and Limitations
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_querycomp">2.
Query Compilation Cache
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_querysql">3. Prepared SQL Cache</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_encryption">11.
Encryption Provider
</a></span></dt><dt><span class="chapter"><a href="#ref_guide_remote">12.
Remote and Offline Operation
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach">1.
Detach and Attach
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach_behavior">1.1.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_attach_behavior">1.2.
Attach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_graph">1.3.
Defining the Detached Object Graph
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach_state">1.3.1.
Detached State
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_field">1.3.2.
Detached State Field
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_event">2.
Remote Event Notification Framework
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_event_conf">2.1.
Remote Commit Provider Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_event_conf_jms">2.1.1.
JMS
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_tcp">2.1.2.
TCP
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_common">2.1.3.
Common Properties
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_event_customization">2.2.
Customization
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_slice">13.
Slice: Distributed Persistence
</a></span></dt><dd><dl><dt><span class="section"><a href="#slice_overview">1. Overview</a></span></dt><dt><span class="section"><a href="#features_and_limitations">2. Salient Features</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e16891">2.1. Transparency</a></span></dt><dt><span class="section"><a href="#d5e16897">2.2. Scaling</a></span></dt><dt><span class="section"><a href="#d5e16903">2.3. Distributed Query</a></span></dt><dt><span class="section"><a href="#d5e16926">2.4. Data Distribution</a></span></dt><dt><span class="section"><a href="#d5e16945">2.5. Data Replication</a></span></dt><dt><span class="section"><a href="#d5e16954">2.6. Heterogeneous Database</a></span></dt><dt><span class="section"><a href="#d5e16957">2.7. Distributed Transaction</a></span></dt><dt><span class="section"><a href="#collocation_constraint">2.8. Collocation Constraint</a></span></dt></dl></dd><dt><span class="section"><a href="#slice_configuration">3. Usage</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e16974">3.1. How to activate Slice Runtime?</a></span></dt><dt><span class="section"><a href="#d5e16978">3.2. How to configure each database slice?</a></span></dt><dt><span class="section"><a href="#distribution_policy">3.3. Implement DistributionPolicy interface</a></span></dt><dt><span class="section"><a href="#replication_policy">3.4. Implement ReplicationPolicy interface</a></span></dt></dl></dd><dt><span class="section"><a href="#d5e17032">4. Configuration Properties</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e17037">4.1. Global Properties</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e17039">4.1.1. openjpa.slice.DistributionPolicy</a></span></dt><dt><span class="section"><a href="#d5e17045">4.1.2. openjpa.slice.Lenient</a></span></dt><dt><span class="section"><a href="#d5e17052">4.1.3. openjpa.slice.Master</a></span></dt><dt><span class="section"><a href="#d5e17060">4.1.4. openjpa.slice.Names</a></span></dt><dt><span class="section"><a href="#d5e17068">4.1.5. openjpa.slice.ThreadingPolicy</a></span></dt><dt><span class="section"><a href="#d5e17094">4.1.6. openjpa.slice.TransactionPolicy</a></span></dt></dl></dd><dt><span class="section"><a href="#d5e17112">4.2. Per-Slice Properties</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_integration">14.
Third Party Integration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_ant">1.
Apache Ant
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_conf">1.1.
Common Ant Configuration Options
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_enhance">1.2.
Enhancer Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_appidtool">1.3.
Application Identity Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_mappingtool">1.4.
Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_revmappingtool">1.5.
Reverse Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_schematool">1.6.
Schema Tool Ant Task
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_integration_dbcp">2.
Apache Commons DBCP
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_dbcp_conf">2.1.
Apache Commons DBCP Configuration Options
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_optimization">15.
Optimization Guidelines
</a></span></dt><dt><span class="chapter"><a href="#ref_guide_instrumentation">16.
Instrumentation
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_instrumentation_config">1.
Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_instrumentation_config_jmx">1.1.
JMX Platform MBean Enablement
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_instrumentation_custom">2.
Custom Providers and Instruments
</a></span></dt></dl></dd></dl></dd><dt><span class="part"><a href="#appendices">4. Appendices</a></span></dt><dd><dl><dt><span class="appendix"><a href="#jpa_resources">1.
JPA Resources
</a></span></dt><dt><span class="appendix"><a href="#supported_databases">2.
Supported Databases
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbappendix">1.
Overview
</a></span></dt><dt><span class="section"><a href="#dbsupport">2.
Verified Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbcompatible">3.
Compatible Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbunverified">4.
Unverified Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbsupport_derby">5.
Apache Derby
</a></span></dt><dt><span class="section"><a href="#dbsupport_interbase">6.
Borland Interbase
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_interbase_issues">6.1.
Known issues with Interbase
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_jdatastore">7.
JDataStore
</a></span></dt><dt><span class="section"><a href="#dbsupport_db2">8.
IBM DB2
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_db2_issues">8.1.
Known issues with DB2
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_empress">9.
Empress
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_empress_issues">9.1.
Known issues with Empress
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_h2">10.
H2 Database Engine
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_h2_issues">10.1.
Known issues with H2 Database Engine
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_hypersonic">11.
Hypersonic
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_hypersonic_issues">11.1.
Known issues with Hypersonic
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_firebird">12.
Firebird
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_firebird_issues">12.1.
Known issues with Firebird
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_informix">13.
Informix
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_informix_issues">13.1.
Known issues with Informix
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_ingres">14.
Ingres Database
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_ingres_issues">14.1.
Known issues with Ingres
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_intersystems_cache">15.
InterSystems Cache
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_intersystems_cache_issues">15.1.
Known issues with InterSystems Cache
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_access">16.
Microsoft Access
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_access_issues">16.1.
Known issues with Microsoft Access
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_sqlserver">17.
Microsoft SQL Server
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_sqlserver_issues">17.1.
Known issues with SQL Server
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_foxpro">18.
Microsoft FoxPro
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_foxpro_issues">18.1.
Known issues with Microsoft FoxPro
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_mysql">19.
MySQL
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_mysql_query_hints">19.1.
Using Query Hints with MySQL
</a></span></dt><dt><span class="section"><a href="#dbsupport_mysql_issues">19.2.
Known issues with MySQL
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_mariadb">20.
MariaDB
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_mariadb_issues">20.1.
Known issues with MariaDB
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_oracle">21.
Oracle
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_oracle_query_hints">21.1.
Using Query Hints with Oracle
</a></span></dt><dt><span class="section"><a href="#dbsupport_oracle_issues">21.2.
Known issues with Oracle
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_pointbase">22.
Pointbase
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_pointbase_issues">22.1.
Known issues with Pointbase
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_postgresql">23.
PostgreSQL
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_postgresql_issues">23.1.
Known issues with PostgreSQL
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_soliddb">24.
IBM solidDB
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_soliddb_table_types">24.1.
M-type tables vs. D-type tables
</a></span></dt><dt><span class="section"><a href="#dbsupport_soliddb_concurrency_control">24.2.
Concurrency control mechanism
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_sybase">25.
Sybase Adaptive Server
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_sybase_issues">25.1.
Known issues with Sybase
</a></span></dt></dl></dd></dl></dd><dt><span class="appendix"><a href="#migration_considerations">3.
Migration Considerations
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.0">1.
OpenJPA 2.0.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.0_incompatibilities">1.1.
Incompatibilities
</a></span></dt><dd><dl><dt><span class="section"><a href="#getProperties">1.1.1.
getProperties()
</a></span></dt><dt><span class="section"><a href="#migration_detach_behavior">1.1.2.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#private_persistent_properties">1.1.3.
Use of private persistent properties
</a></span></dt><dt><span class="section"><a href="#setParameter">1.1.4.
Query.setParameter()
</a></span></dt><dt><span class="section"><a href="#serialization">1.1.5.
Serialization of Entities
</a></span></dt><dt><span class="section"><a href="#QuerySQLCache">1.1.6.
openjpa.jdbc.QuerySQLCache
</a></span></dt></dl></dd><dt><span class="section"><a href="#Disabling AutoOff Collection Tracking">1.2.
Disabling AutoOff Collection Tracking
</a></span></dt><dt><span class="section"><a href="#internal_differences">1.3.
Internal Behavioral Differences
</a></span></dt><dd><dl><dt><span class="section"><a href="#prePostUpdate">1.3.1.
PreUpdate/PostUpdate Life Cycle Callbacks
</a></span></dt><dt><span class="section"><a href="#createemf">1.3.2.
createEntityManagerFactory Exceptions
</a></span></dt><dt><span class="section"><a href="#querycache">1.3.3.
openjpa.QueryCache default
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_2.2">2.
OpenJPA 2.2.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.2_incompatibilities">2.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.2_allocationSize">2.1.1.
allocationSize Property of Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_metamodelArrays">2.1.2.
MetaModel Attributes for Arrays
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_SupportsSetClob">2.1.3.
supportsSetClob Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_UseNativeSequenceCache">2.1.4.
useNativeSequenceCache Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_cascadePersist">2.1.5.
Cascade persist behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_LifecycleEventManager">2.1.6.
Life Cycle Event Manager Callback Behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_sharedCacheMode">2.1.7.
shared-cache-mode Property
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_2.3">3.
OpenJPA 2.3.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.3_incompatibilities">3.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.3_MappingTool">3.1.1.
MappingTool Behavior for DB2 and Derby
</a></span></dt><dt><span class="section"><a href="#jpa_2.3_RequiresSearchStringEscapeForLike">3.1.2.
RequiresSearchStringEscapeForLike DBDictionary Property
</a></span></dt><dt><span class="section"><a href="#ReturnNullOnEmptyAggregateResult">3.1.3.
Return value of aggregate functions in SELECT clause
</a></span></dt></dl></dd></dl></dd></dl></dd></dl></dd></dl></div><div class="list-of-tables"><p><b>List of Tables</b></p><dl><dt>2.1. <a href="#d5e131">
Persistence Mechanisms
</a></dt><dt>10.1. <a href="#d5e3309">
Interaction of ReadLockMode hint and LockManager
</a></dt><dt>2.1. <a href="#d5e6865">
Standard JPA Properties and OpenJPA equivalents
</a></dt><dt>4.1. <a href="#d5e11491">
Default delimiters for delimited identifiers
</a></dt><dt>4.2. <a href="#d5e11656">
OpenJPA Automatic Flush Behavior
</a></dt><dt>5.1. <a href="#d5e12730">
Externalizer Options
</a></dt><dt>5.2. <a href="#d5e12767">
Factory Options
</a></dt><dt>10.1. <a href="#d5e16030">
Data access methods
</a></dt><dt>10.2. <a href="#d5e16421">
Pre-defined aliases
</a></dt><dt>10.3. <a href="#d5e16475">
Pre-defined aliases
</a></dt><dt>15.1. <a href="#d5e17324">
Optimization Guidelines
</a></dt><dt>2.1. <a href="#d5e17649">
Supported Databases and JDBC Drivers
</a></dt><dt>2.2. <a href="#d5e17721">
Compatible Databases and JDBC Drivers
</a></dt><dt>2.3. <a href="#d5e17859">
Unverified Databases and JDBC Drivers
</a></dt></dl></div><div class="list-of-examples"><p><b>List of Examples</b></p><dl><dt>3.1. <a href="#jpa_overview_arch_interact_outside">
Interaction of Interfaces Outside Container
</a></dt><dt>3.2. <a href="#jpa_overview_arch_interact_inside">
Interaction of Interfaces Inside Container
</a></dt><dt>4.1. <a href="#jpa_overview_pc_pcclass">
Persistent Class
</a></dt><dt>4.2. <a href="#jpa_overview_pc_identity_appidcode">
Identity Class
</a></dt><dt>5.1. <a href="#jpa_overview_meta_classlisting">
Class Metadata
</a></dt><dt>5.2. <a href="#jpa_overview_meta_complete_ex">
Complete Metadata
</a></dt><dt>6.1. <a href="#jpa_overview_persistence_xmlex">
persistence.xml
</a></dt><dt>6.2. <a href="#jpa_overview_persistence_getemfactory">
Obtaining an EntityManagerFactory
</a></dt><dt>7.1. <a href="#jpa_overview_emfactory_perscontext_transex">
Behavior of Transaction Persistence Context
</a></dt><dt>7.2. <a href="#jpa_overview_emfactory_perscontext_extendex">
Behavior of Extended Persistence Context
</a></dt><dt>8.1. <a href="#jpa_overview_em_lifecycle_persist">
Persisting Objects
</a></dt><dt>8.2. <a href="#jpa_overview_em_lifecycle_update">
Updating Objects
</a></dt><dt>8.3. <a href="#jpa_overview_em_lifecycle_delete">
Removing Objects
</a></dt><dt>8.4. <a href="#jpa_overview_em_detachex">
Detaching and Merging
</a></dt><dt>9.1. <a href="#jpa_overview_trans_group">
Grouping Operations with Transactions
</a></dt><dt>10.1. <a href="#jpa_query_hint1">
Query Hints
</a></dt><dt>10.2. <a href="#jpa_query_hint2">
Named Query using Hints
</a></dt><dt>10.3. <a href="#multi-hints-example">
Setting Multiple Similar Query Hints
</a></dt><dt>10.4. <a href="#jpa_overview_query_deleteex">
Delete by Query
</a></dt><dt>10.5. <a href="#jpa_overview_query_updateex">
Update by Query
</a></dt><dt>12.1. <a href="#jpa_overview_sqlquery_createex">
Creating a SQL Query
</a></dt><dt>12.2. <a href="#jpa_overview_sqlquery_objex">
Retrieving Persistent Objects
</a></dt><dt>12.3. <a href="#jpa_overview_sqlquery_obj_paramex">
SQL Query Parameters
</a></dt><dt>13.1. <a href="#jpa_overview_mapping_classex">
Mapping Classes
</a></dt><dt>13.2. <a href="#jpa_overview_mapping_unq_attrex">
Defining a Unique Constraint
</a></dt><dt>13.3. <a href="#jpa_overview_mapping_identityex">
Identity Mapping
</a></dt><dt>13.4. <a href="#jpa_overview_mapping_sequenceex">
Generator Mapping
</a></dt><dt>13.5. <a href="#jpa_overview_mapping_inher_singleex">
Single Table Mapping
</a></dt><dt>13.6. <a href="#jpa_overview_mapping_inher_joinedex">
Joined Subclass Tables
</a></dt><dt>13.7. <a href="#jpa_overview_mapping_inher_tpcex">
Table Per Class Mapping
</a></dt><dt>13.8. <a href="#jpa_overview_mapping_inher_togetherex">
Inheritance Mapping
</a></dt><dt>13.9. <a href="#jpa_overview_mapping_discrimex">
Discriminator Mapping
</a></dt><dt>13.10. <a href="#jpa_overview_mapping_basicex">
Basic Field Mapping
</a></dt><dt>13.11. <a href="#jpa_overview_mapping_secondaryex">
Secondary Table Field Mapping
</a></dt><dt>13.12. <a href="#jpa_overview_mapping_embedex">
Embedded Field Mapping
</a></dt><dt>13.13. <a href="#jpa_overview_mapping_joined_overex">
Mapping Mapped Superclass Field
</a></dt><dt>13.14. <a href="#jpa_overview_mapping_relex">
Direct Relation Field Mapping
</a></dt><dt>13.15. <a href="#jpa_overview_mapping_assoccollex">
Join Table Mapping
</a></dt><dt>13.16. <a href="#jpa_overview_mapping_mapex">
Join Table Map Mapping
</a></dt><dt>13.17. <a href="#jpa_overview_mapping_fullex">
Full Entity Mappings
</a></dt><dt>2.1. <a href="#ref_guide_conf_devtools_format_ex">
Code Formatting with the Application Id Tool
</a></dt><dt>3.1. <a href="#ref_guide_logging_openjpa_std_ex">
Standard OpenJPA Log Configuration
</a></dt><dt>3.2. <a href="#ref_guide_logging_openjpa_sql_ex">
Standard OpenJPA Log Configuration + All SQL Statements
</a></dt><dt>3.3. <a href="#ref_guide_logging_openjpa_file">
Logging to a File
</a></dt><dt>3.4. <a href="#ref_guide_logging_log4j_ex">
Standard Log4J Logging
</a></dt><dt>3.5. <a href="#ref_guide_logging_jdk14_propfile">
JDK Log Properties
</a></dt><dt>3.6. <a href="#ref_guide_logging_custom_ex">
Custom Logging Class
</a></dt><dt>4.1. <a href="#ref_guide_dbsetup_builtin_ex">
Properties for the OpenJPA DataSource
</a></dt><dt>4.2. <a href="#ref_guide_dbsetup_thirdparty_ex">
Properties File for a Third-Party DataSource
</a></dt><dt>4.3. <a href="#ref_guide_enterprise_xa_conf_ex">
Managed DataSource Configuration
</a></dt><dt>4.4. <a href="#d5e9689">
Setting DataSource at Runtime
</a></dt><dt>4.5. <a href="#ref_guide_dbsetup_conn_jpa">
Using the EntityManager's Connection
</a></dt><dt>4.6. <a href="#ref_guide_dbsetup_conn_from_factory_jpa">
Using the EntityManagerFactory's DataSource
</a></dt><dt>4.7. <a href="#ref_guide_dbsetup_dbdict">
Specifying a DBDictionary
</a></dt><dt>4.8. <a href="#ref_guide_dbsetup_isoex">
Specifying a Transaction Isolation
</a></dt><dt>4.9. <a href="#ref_guide_dbsetup_sql92_conf">
Specifying the Join Syntax Default
</a></dt><dt>4.10. <a href="#ref_guide_dbsetup_sql92_fetch">
Specifying the Join Syntax at Runtime
</a></dt><dt>4.11. <a href="#ref_guide_dbsetup_sql92_retain_conf">
Specifying Connection Usage Defaults
</a></dt><dt>4.12. <a href="#ref_guide_dbsetup_sql92_retain_runtime">
Specifying Connection Usage at Runtime
</a></dt><dt>4.13. <a href="#ref_guide_dbsetup_stmtbatch_exmple1">
Enable SQL statement batching
</a></dt><dt>4.14. <a href="#ref_guide_dbsetup_stmtbatch_exmple2">
Disable SQL statement batching
</a></dt><dt>4.15. <a href="#ref_guide_dbsetup_stmtbatch_exmple3">
Plug-in custom statement batching implementation
</a></dt><dt>4.16. <a href="#ref_guide_dbsetup_lrs_def">
Specifying Result Set Defaults
</a></dt><dt>4.17. <a href="#ref_guide_dbsetup_lrs_runtime">
Specifying Result Set Behavior at Runtime
</a></dt><dt>4.18. <a href="#ref_guide_schema_schematool_create">
Schema Creation
</a></dt><dt>4.19. <a href="#ref_guide_schema_schematool_script">
SQL Scripting
</a></dt><dt>4.20. <a href="#ref_guide_schema_schematool_table_cleanup">
Table Cleanup
</a></dt><dt>4.21. <a href="#ref_guide_schema_schematool_drop">
Schema Drop
</a></dt><dt>4.22. <a href="#ref_guide_schema_schematool_reflect">
Schema Reflection
</a></dt><dt>4.23. <a href="#ref_guide_schema_xml_basic">
Basic Schema
</a></dt><dt>4.24. <a href="#ref_guide_schema_xml_full">
Full Schema
</a></dt><dt>5.1. <a href="#ref_guide_pc_enhance_enhancer">
Using the OpenJPA Enhancer
</a></dt><dt>5.2. <a href="#ref_guide_pc_enhance_runtime_ex">
Using the OpenJPA Agent for Runtime Enhancement
</a></dt><dt>5.3. <a href="#ref_guide_pc_enhance_runtime_opt_ex">
Passing Options to the OpenJPA Agent
</a></dt><dt>5.4. <a href="#ref_guide_pc_oid_datastoreentityex">
JPA Datastore Identity Metadata
</a></dt><dt>5.5. <a href="#ref_guide_pc_oid_entitypk_simplefind">
Finding an Entity with an Entity Identity Field
</a></dt><dt>5.6. <a href="#ref_guide_pc_oid_entitypk_idcls">
Id Class for Entity Identity Fields
</a></dt><dt>5.7. <a href="#ref_guide_pc_oid_entitypk_embeded_id">
Embedded Id for Entity Identity Fields
</a></dt><dt>5.8. <a href="#ref_guide_pc_appid_appidtool">
Using the Application Identity Tool
</a></dt><dt>5.9. <a href="#ref_guide_inverses_logicalex">
Specifying Logical Inverses
</a></dt><dt>5.10. <a href="#ref_guide_inversesex">
Enabling Managed Inverses
</a></dt><dt>5.11. <a href="#ref_guide_inverses_logex">
Log Inconsistencies
</a></dt><dt>5.12. <a href="#ref_guide_pc_scos_order_initialvals">
Using Initial Field Values
</a></dt><dt>5.13. <a href="#ref_guide_pc_scos_proxy_lrs_itr">
Using a Large Result Set Iterator
</a></dt><dt>5.14. <a href="#ref_guide_pc_scos_proxy_lrs_extension">
Marking a Large Result Set Field
</a></dt><dt>5.15. <a href="#ref_guide_pc_scos_proxy_custom_ex">
Configuring the Proxy Manager
</a></dt><dt>5.16. <a href="#ref_guide_pc_externex">
Using Externalization
</a></dt><dt>5.17. <a href="#ref_guide_pc_extern_queryex">
Querying Externalization Fields
</a></dt><dt>5.18. <a href="#externvalues_ex">
Using External Values
</a></dt><dt>5.19. <a href="#ref_guide_fetch_customgroups">
Custom Fetch Group Metadata
</a></dt><dt>5.20. <a href="#ref_guide_fetch_loadgroup">
Load Fetch Group Metadata
</a></dt><dt>5.21. <a href="#ref_guide_fetch_conf_query">
Using the FetchPlan
</a></dt><dt>5.22. <a href="#ref_guide_fetch-conf_per_field">
Adding an Eager Field
</a></dt><dt>5.23. <a href="#ref_guide_perfpack_eager_def">
Setting the Default Eager Fetch Mode
</a></dt><dt>5.24. <a href="#ref_guide_perfpack_eager_runtime">
Setting the Eager Fetch Mode at Runtime
</a></dt><dt>6.1. <a href="#ref_guide_meta_stdfactoryex">
Setting a Standard Metadata Factory
</a></dt><dt>6.2. <a href="#ref_guide_meta_customfactoryex">
Setting a Custom Metadata Factory
</a></dt><dt>6.3. <a href="#ref_guide_meta_repo">
Setting the Preload Property on Metadata Repository
</a></dt><dt>6.4. <a href="#ref_guide_metaex">
OpenJPA Metadata Extensions
</a></dt><dt>6.5. <a href="#ref_guide_schema_ex">
OpenJPA Schema Extensions
</a></dt><dt>7.1. <a href="#ref_guide_mapping_mappingtool_typical">
Using the Mapping Tool
</a></dt><dt>7.2. <a href="#ref_guide_mapping_mappingtool_buildschema">
Creating the Relational Schema from Mappings
</a></dt><dt>7.3. <a href="#ref_guide_mapping_mappingtool_cleanup_tables">
Refreshing entire schema and cleaning out tables
</a></dt><dt>7.4. <a href="#ref_guide_mapping_mappingtool_dropschema">
Dropping Mappings and Association Schema
</a></dt><dt>7.5. <a href="#ref_guid_mapping_ddl_full_ddl">
Create DDL for Current Mappings
</a></dt><dt>7.6. <a href="#ref_guid_mapping_ddl_part_ddl">
Create DDL to Update Database for Current Mappings
</a></dt><dt>7.7. <a href="#ref_guide_mapping_synchex">
Configuring Runtime Forward Mapping
</a></dt><dt>7.8. <a href="#ref_guide_pc_reverse_schemagen">
Reflection with the Schema Tool
</a></dt><dt>7.9. <a href="#ref_guide_pc_reverse_reversemappingtool">
Using the Reverse Mapping Tool
</a></dt><dt>7.10. <a href="#ref_guide_pc_reverse_custom_ex">
Customizing Reverse Mapping with Properties
</a></dt><dt>7.11. <a href="#ref_guide_mapping_mappingtool_validate">
Validating Mappings
</a></dt><dt>7.12. <a href="#ref_guide_mapping_defaults_conf">
Configuring Mapping Defaults
</a></dt><dt>7.13. <a href="#ref_guide_mapping_factory_jpa">
Standard JPA Configuration
</a></dt><dt>7.14. <a href="#ref_guide_mapping_jpa_datastoreidex">
Datastore Identity Mapping
</a></dt><dt>7.15. <a href="#ref_guide_mapping_jpa_embedex">
Overriding Complex Mappings
</a></dt><dt>7.16. <a href="#ref_guide_mapping_jpa_onemanyex">
One-Sided One-Many Mapping
</a></dt><dt>7.17. <a href="#ref_guide_mapping_jpa_map_stringrelmap">String Key, Entity Value Map Mapping</a></dt><dt>7.18. <a href="#ref_guide_xmlmapping_myaddress">
myaddress.xsd
</a></dt><dt>7.19. <a href="#ref_guide_xmlmapping_address">
Address.java
</a></dt><dt>7.20. <a href="#ref_guide_xmlmapping_usaaddress">
USAAddress.java
</a></dt><dt>7.21. <a href="#ref_guide_xmlmapping_canaddress">
CANAddress.java
</a></dt><dt>7.22. <a href="#ref_guide_xmlmapping_annorder">
Showing annotated Order entity with XML mapping strategy
</a></dt><dt>7.23. <a href="#ref_guide_xmlmapping_createorder">
Showing creation of Order entity having shipAddress mapped to XML column
</a></dt><dt>7.24. <a href="#ref_guide_xmlmapping_jpqlquery">
Sample JPQL queries for XML column mapping
</a></dt><dt>7.25. <a href="#ref_guide_streamsupport_example">
Annotated InputStream and Reader
</a></dt><dt>7.26. <a href="#ref_guide_orphan_logex">
Custom Logging Orphaned Keys
</a></dt><dt>8.1. <a href="#ref_guide_enterprise_transex">Configuring Transaction Manager Integration</a></dt><dt>9.1. <a href="#ref_guide_runtime_pm_evictex">
Evict from Data Cache
</a></dt><dt>9.2. <a href="#ref_guide_runtime_jpaextentex">
Using a JPA Extent
</a></dt><dt>9.3. <a href="#ref_guide_locking_default_conf">
Setting Default Lock Levels
</a></dt><dt>9.4. <a href="#ref_guide_locking_fetch">
Setting Runtime Lock Levels
</a></dt><dt>9.5. <a href="#ref_guide_locking_explicit">
Locking APIs
</a></dt><dt>9.6. <a href="#ref_guide_locking_disable">
Disabling Locking
</a></dt><dt>9.7. <a href="#ref_guide_savepoints_example">
Using Savepoints
</a></dt><dt>9.8. <a href="#ref_guide_sequence_named">
Named Seq Sequence
</a></dt><dt>9.9. <a href="#ref_guide_sequence_systemex">
System Sequence Configuration
</a></dt><dt>10.1. <a href="#ref_guide_cache_conf_sjvm">
Single-JVM Data Cache
</a></dt><dt>10.2. <a href="#ref_guide_cache_conf_lru">
Lru Cache
</a></dt><dt>10.3. <a href="#ref_guide_cache_conf_size">
Data Cache Size
</a></dt><dt>10.4. <a href="#ex_timeout_cache">
Data Cache Timeout
</a></dt><dt>10.5. <a href="#ex_exclude_types_from_cache">
Excluding entities
</a></dt><dt>10.6. <a href="#ex_include_types_in_cache">
Including entities
</a></dt><dt>10.7. <a href="#bulk_update_evict_cache">
Bulk updates and cache eviction
</a></dt><dt>10.8. <a href="#shared-cache-mode-none"></a></dt><dt>10.9. <a href="#shared-cache-mode-all"></a></dt><dt>10.10. <a href="#shared-cache-mode-enable-selective"></a></dt><dt>10.11. <a href="#ref_guide_cache_conf_partition">
Partitioned Data Cache
</a></dt><dt>10.12. <a href="#ref_guide_cache_access_jpa_standard">
Accessing the Cache
</a></dt><dt>10.13. <a href="#ref_guide_cache_use_jpa_standard">Using the javax.persistence.Cache interface</a></dt><dt>10.14. <a href="#ref_guide_cache_access_jpa">
Accessing the StoreCache
</a></dt><dt>10.15. <a href="#ref_guide_cache_use_jpa">
StoreCache Usage
</a></dt><dt>10.16. <a href="#ref_guide_cache_pmevict">
Automatic Data Cache Eviction
</a></dt><dt>10.17. <a href="#ref_guide_cache_enablestats">
Configuring CacheStatistics
</a></dt><dt>10.18. <a href="#ref_guide_cache_queryaccess">
Accessing the QueryResultCache
</a></dt><dt>10.19. <a href="#ref_guide_cache_cachesize">
Query Cache Size
</a></dt><dt>10.20. <a href="#ref_guide_cache_disablequery">
Disabling the Query Cache
</a></dt><dt>10.21. <a href="#ref_guide_cache_evictionPolicy">
Query Cache Eviction Policy
</a></dt><dt>10.22. <a href="#ref_guide_cache_query_classchange">
Evicting Queries
</a></dt><dt>10.23. <a href="#ref_guide_cache_query_pin">
Pinning, and Unpinning Query Results
</a></dt><dt>10.24. <a href="#ref_guide_cache_query_disable">
Disabling and Enabling Query Caching
</a></dt><dt>10.25. <a href="#ref_guide_cache_limits_extent">
Query Replaces Extent
</a></dt><dt>10.26. <a href="#jpa_caching_hardcode_jpql">Hardcoded Selection Value in JPQL Query</a></dt><dt>10.27. <a href="#jpa_caching_parametrize_jpql">Parameterized Selection Value in JPQL Query</a></dt><dt>12.1. <a href="#ref_guide_detach_graph_confex">
Configuring Detached State
</a></dt><dt>12.2. <a href="#ref_guide_event_conf_jmsex">
JMS Remote Commit Provider Configuration
</a></dt><dt>12.3. <a href="#ref_guide_event_conf_tcpex">
TCP Remote Commit Provider Configuration
</a></dt><dt>12.4. <a href="#ref_guide_event_conf_jms2ex">
JMS Remote Commit Provider transmitting Persisted Object Ids
</a></dt><dt>14.1. <a href="#ref_guide_integration_conf_config">
Using the &lt;config&gt; Ant Tag
</a></dt><dt>14.2. <a href="#ref_guide_integration_props">
Using the Properties Attribute of the &lt;config&gt; Tag
</a></dt><dt>14.3. <a href="#ref_guide_integration_propsfile">
Using the PropertiesFile Attribute of the &lt;config&gt; Tag
</a></dt><dt>14.4. <a href="#ref_guide_integration_conf_classpath">
Using the &lt;classpath&gt; Ant Tag
</a></dt><dt>14.5. <a href="#ref_guide_integration_conf_codeformat">
Using the &lt;codeformat&gt; Ant Tag
</a></dt><dt>14.6. <a href="#ref_guide_integration_enhance_task">
Invoking the Enhancer from Ant
</a></dt><dt>14.7. <a href="#ref_guide_integration_appidtool_task">
Invoking the Application Identity Tool from Ant
</a></dt><dt>14.8. <a href="#ref_guide_integration_mappingtool_task">
Invoking the Mapping Tool from Ant
</a></dt><dt>14.9. <a href="#ref_guide_integration_revmappingtool_task">
Invoking the Reverse Mapping Tool from Ant
</a></dt><dt>14.10. <a href="#ref_guide_integration_schematool_task">
Invoking the Schema Tool from Ant
</a></dt><dt>14.11. <a href="#ref_guide_integration_dbcp_derby">
Using Commons DBCP with Apache Derby
</a></dt><dt>2.1. <a href="#example_props_derby">
Example properties for Derby
</a></dt><dt>2.2. <a href="#example_props_interbase">
Example properties for Interbase
</a></dt><dt>2.3. <a href="#example_props_jdatastore">
Example properties for JDataStore
</a></dt><dt>2.4. <a href="#example_props_db2">
Example properties for IBM DB2
</a></dt><dt>2.5. <a href="#example_props_empress">
Example properties for Empress
</a></dt><dt>2.6. <a href="#example_props_h2">
Example properties for H2 Database Engine
</a></dt><dt>2.7. <a href="#example_props_hypersonic">
Example properties for Hypersonic
</a></dt><dt>2.8. <a href="#example_props_firebird">
Example properties for Firebird
</a></dt><dt>2.9. <a href="#example_props_informix">
Example properties for Informix Dynamic Server
</a></dt><dt>2.10. <a href="#example_props_ingres">
Example properties for Ingres
</a></dt><dt>2.11. <a href="#example_props_intersystems_cache">
Example properties for InterSystems Cache
</a></dt><dt>2.12. <a href="#example_props_access">
Example properties for Microsoft Access
</a></dt><dt>2.13. <a href="#example_props_sqlserver">
Example properties for Microsoft SQL Server
</a></dt><dt>2.14. <a href="#example_props_foxpro">
Example properties for Microsoft FoxPro
</a></dt><dt>2.15. <a href="#example_props_mysql">
Example properties for MySQL
</a></dt><dt>2.16. <a href="#dbsupport_mysql_query_hints_ex">
Using MySQL Hints
</a></dt><dt>2.17. <a href="#example_props_mariadb">
Example properties for MariaDB
</a></dt><dt>2.18. <a href="#example_props_oracle">
Example properties for Oracle
</a></dt><dt>2.19. <a href="#dbsupport_oracle_query_hints_ex">
Using Oracle Hints
</a></dt><dt>2.20. <a href="#dbsupport_oracle_disable_batch_updates">
Property to disable statement batching for Oracle
</a></dt><dt>2.21. <a href="#dbsupport_oracle_retain_connection">
Property to retain connection over the lifetime of the entity manager
</a></dt><dt>2.22. <a href="#example_props_pointbase">
Example properties for Pointbase
</a></dt><dt>2.23. <a href="#example_props_postgresql">
Example properties for PostgreSQL
</a></dt><dt>2.24. <a href="#example_props_soliddb">
Example properties for IBM solidDB
</a></dt><dt>2.25. <a href="#example_props_sybase">
Example properties for Sybase
</a></dt></dl></div>
<div class="part" id="introduction"><div class="titlepage"><div><div><h1 class="title">Part&nbsp;1.&nbsp;Introduction</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="chapter"><a href="#openjpa_intro">1.
About
</a></span></dt><dt><span class="chapter"><a href="#openjpa_legal">2.
Legal
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa_legal_license">1.
License
</a></span></dt><dt><span class="section"><a href="#openjpa_legal_notice">2.
Notice
</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright">3.
Copyrights
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa_legal_copyright_apache">3.1. Apache</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_serp">3.2. Serp</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_sun">3.3. Sun</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_other">3.4. Other</a></span></dt></dl></dd></dl></dd></dl></div>
<div class="chapter" id="openjpa_intro"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;1.&nbsp;
About
</h2></div></div></div>
<a class="indexterm" name="d5e13"></a>
<p>
OpenJPA is Apache's implementation of Java Persistence 2.0 API
(JSR-317 JPA 2.0) specification for the transparent persistence of Java objects.
This document provides an overview of the JPA standard and technical
details on the use of OpenJPA.
</p>
<p>
This document is intended for OpenJPA users. It is divided into several parts:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The <a class="link" href="#jpa_overview_intro" title="Chapter&nbsp;1.&nbsp; Introduction">JPA Overview</a> describes the
fundamentals of the JPA specification.
</p>
</li><li class="listitem">
<p>
The <a class="link" href="#ref_guide_intro" title="Chapter&nbsp;1.&nbsp; Introduction">OpenJPA Reference Guide</a> contains
detailed documentation on all aspects of OpenJPA. Browse through this guide
to familiarize yourself with the many advanced features and customization
opportunities OpenJPA provides. Later, you can use the guide when you need
details on a specific aspect of OpenJPA.
</p>
</li><li class="listitem">
<p>
Appendices
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
The appendix <a class="link" href="#jpa_resources" title="Appendix&nbsp;1.&nbsp; JPA Resources">JPA Resources
</a> provides links to other resources.
</p>
</li><li class="listitem">
<p>
The appendix <a class="link" href="#supported_databases" title="Appendix&nbsp;2.&nbsp; Supported Databases">
Supported Databases</a> provides information on
databases supported by OpenJPA.
</p>
</li><li class="listitem">
<p>
The appendix <a class="link" href="#migration_considerations" title="Appendix&nbsp;3.&nbsp; Migration Considerations">
Migration Considerations</a> provides information
related to migration to a different release.
</p>
</li></ul></div><p>
</p>
</li></ul></div>
</div>
<div class="chapter" id="openjpa_legal"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;2.&nbsp;
Legal
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#openjpa_legal_license">1.
License
</a></span></dt><dt><span class="section"><a href="#openjpa_legal_notice">2.
Notice
</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright">3.
Copyrights
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa_legal_copyright_apache">3.1. Apache</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_serp">3.2. Serp</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_sun">3.3. Sun</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_other">3.4. Other</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e38"></a>
<p>
</p>
<p>
The Apache OpenJPA website can be found at:
<a class="ulink" href="http://openjpa.apache.org/" target="_top"> http://openjpa.apache.org </a>
</p>
<p>
</p>
<div class="section" id="openjpa_legal_license"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
License
</h2></div></div></div>
<p>
Apache OpenJPA is released under the <a class="ulink" href="http://www.apache.org/licenses/LICENSE-2.0.txt" target="_top">Apache Software License Version 2.0</a>
</p>
<p>
Apache OpenJPA includes the persistence and orm schemas from the JPA specifications and elects to include this software in this distribution under the <a class="ulink" href="https://glassfish.dev.java.net/public/CDDL+GPL.html" target="_top">CDDL license.</a>
</p>
<p>
Apache OpenJPA includes software developed by the SERP project, which uses the <a class="ulink" href="http://www.opensource.org/licenses/bsd-license.php" target="_top">BSD license</a>
</p>
</div>
<div class="section" id="openjpa_legal_notice"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Notice
</h2></div></div></div>
<p>
This product includes software developed by
<a class="ulink" href="http://www.apache.org/" target="_top"> The Apache Software Foundation (http://www.apache.org/).</a>
</p>
<p>
The openjpa-all aggregate JAR includes software developed by the:
</p><div class="itemizedlist"><ul class="itemizedlist compact" style="list-style-type: disc; "><li class="listitem"><p>
Apache Commons Collections project
</p></li><li class="listitem"><p>
Apache Commons Lang project
</p></li><li class="listitem"><p>
Apache Commons Logging project
</p></li><li class="listitem"><p>
Apache Commons Pool project
</p></li><li class="listitem"><p>
Apache Geronimo project (JMS 1.1, JTA 1.1 and JPA 2.0 spec APIs)
</p></li><li class="listitem"><p>
JCP JSR-317 JPA 2.0 schemas
</p></li><li class="listitem"><p>
SERP project
</p></li></ul></div><p>
</p>
</div>
<div class="section" id="openjpa_legal_copyright"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Copyrights
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#openjpa_legal_copyright_apache">3.1. Apache</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_serp">3.2. Serp</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_sun">3.3. Sun</a></span></dt><dt><span class="section"><a href="#openjpa_legal_copyright_other">3.4. Other</a></span></dt></dl></div>
<div class="section" id="openjpa_legal_copyright_apache"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;Apache</h3></div></div></div>
<p>
Copyright (C) 2006,2011 The Apache Software Foundation.
</p>
<p>
Apache, OpenJPA and the Apache feather logo are trademarks of Apache Software Foundation.
</p>
</div>
<div class="section" id="openjpa_legal_copyright_serp"><div class="titlepage"><div><div><h3 class="title">3.2.&nbsp;Serp</h3></div></div></div>
<p>
OpenJPA includes software developed by the SERP project.
</p>
<p>
Copyright (c) 2002-2006, A. Abram White. All rights reserved.
</p>
</div>
<div class="section" id="openjpa_legal_copyright_sun"><div class="titlepage"><div><div><h3 class="title">3.3.&nbsp;Sun</h3></div></div></div>
<p>
OpenJPA includes the persistence and orm schemas from the JPA specifications.
</p>
<p>
Copyright 2005-2009 Sun Microsystems, Inc. All rights reserved.
</p>
<p>
OpenJPA elects to include this software in this distribution under the CDDL license.
</p>
<p>
You can obtain a copy of the License at:
<a class="ulink" href="https://glassfish.dev.java.net/public/CDDL+GPL.html" target="_top">https://glassfish.dev.java.net/public/CDDL+GPL.html</a>
</p>
<p>
The source code is available at:
<a class="ulink" href="http://java.net/projects/glassfish/sources/svn/show" target="_top">http://java.net/projects/glassfish/sources/svn/show</a>
or <a class="ulink" href="http://jcp.org/en/jsr/detail?id=317" target="_top"> http://jcp.org/en/jsr/detail?id=317 </a>
</p>
</div>
<div class="section" id="openjpa_legal_copyright_other"><div class="titlepage"><div><div><h3 class="title">3.4.&nbsp;Other</h3></div></div></div>
<p>
OpenJPA includes software written by Miroslav Nachev.
</p>
<p>
OpenJPA uses test code written by Charles Tillman.
</p>
<p>
Oracle and Java are registered trademarks of Oracle and/or its affiliates.
Other names may be trademarks of their respective owners.
</p>
</div>
</div>
</div>
</div>
<div class="part" id="jpa_overview"><div class="titlepage"><div><div><h1 class="title">Part&nbsp;2.&nbsp;Java Persistence API</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="chapter"><a href="#jpa_overview_intro">1.
Introduction
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_intro_audience">1.
Intended Audience
</a></span></dt><dt><span class="section"><a href="#jpa_overview_intro_transpers">2.
Lightweight Persistence
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_why">2.
Why JPA?
</a></span></dt><dt><span class="chapter"><a href="#jpa_overview_arch">3.
Java Persistence API Architecture
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_arch_exceptions">1.
JPA Exceptions
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_pc">4.
Entity
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_restrict">1.
Restrictions on Persistent Classes
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_no_arg">1.1.
Default or No-Arg Constructor
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_final">1.2.
Final
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_id">1.3.
Identity Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_version">1.4.
Version Field
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_inheritance">1.5.
Inheritance
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_fields">1.6.
Persistent Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_conclusion">1.7.
Conclusions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_identity">2.
Entity Identity
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_identitycls">2.1.
Identity Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_identity_hierarchy">2.1.1.
Identity Hierarchies
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_callbacks">3.
Lifecycle Callbacks
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_callbacks_methods">3.1.
Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_callbacks_using">3.2.
Using Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_using">3.3.
Using Entity Listeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_exclude">3.4.
Entity Listeners Hierarchy
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_conclusion">4.
Conclusions
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_meta">5.
Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_class">1.
Class Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_entity">1.1.
Entity
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_idclass">1.2.
Id Class
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddablesuper">1.3.
Mapped Superclass
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddable">1.4.
Embeddable
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_entity_listeners">1.5.
EntityListeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_classex">1.6.
Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_field">2.
Field and Property Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_explicit_access">2.1.
Explicit Access
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_transient">2.2.
Transient
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_id">2.3.
Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_gen">2.4.
Generated Value
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embedid">2.5.
Embedded Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_version">2.6.
Version
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_basic">2.7.
Basic
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_fetch">2.7.1.
Fetch Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_embedded">2.8.
Embedded
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytoone">2.9.
Many To One
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_cascade">2.9.1.
Cascade Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetomany">2.10.
One To Many
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_mappedby">2.10.1.
Bidirectional Relations
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetoone">2.11.
One To One
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytomany">2.12.
Many To Many
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_orderby">2.13.
Order By
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_mapkey">2.14.
Map Key
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_fielddefaults">2.15.
Persistent Field Defaults
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_xml">3.
XML Schema
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_complete">4.
Conclusion
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_persistence">6.
Persistence
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_persistence_xml">1.
persistence.xml
</a></span></dt><dt><span class="section"><a href="#jpa_overview_persistence_use">2.
Non-EE Use
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_emfactory">7.
EntityManagerFactory
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_emfactory_obtain">1.
Obtaining an EntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_em">2.
Obtaining EntityManagers
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext">3.
Persistence Context
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_trans">3.1.
Transaction Persistence Context
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_extend">3.2.
Extended Persistence Context
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_emf_properties">4.
Retrieving Properties Information
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_close">5.
Closing the EntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_puutil">6.
PersistenceUnitUtil
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_em">8.
EntityManager
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_em_trans">1.
Transaction Association
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_lifecycle">2.
Entity Lifecycle Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_lifeexamples">3.
Lifecycle Examples
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_identity">4.
Entity Identity Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_cache">5.
Cache Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_query">6.
Query Factory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_locking">7.
Entity Locking
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_properties">8.
Retrieving Properties Information
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_closing">9.
Closing
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_trans">9.
Transaction
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_trans_types">1.
Transaction Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_trans_local">2.
The EntityTransaction Interface
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_query">10.
JPA Query
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_query_api">1.
JPQL API
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_query_basic">1.1.
Query Basics
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_relations">1.2.
Relation Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_embeddables">1.3.
Embeddable Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_join_fetch">1.4.
Fetch Joins
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_functions">1.5.
JPQL Functions
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_inheritance">1.6.
Polymorphic Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_params">1.7.
Query Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_hints">1.8.
Query Hints
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_hints_locking">1.8.1.
Locking Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_locktimeout">1.8.2.
Lock Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_querytimeout">1.8.3.
Query Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_resultset">1.8.4.
Result Set Size Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_isolation">1.8.5.
Isolation Level Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_fetchplan">1.8.6.
Other Fetchplan Hints
</a></span></dt><dt><span class="section"><a href="#d5e3356">1.8.7.
Database-Specific Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_named">1.8.8.
Named Query Hints
</a></span></dt><dt><span class="section"><a href="#multi-hints-handling">1.8.9.
Handling of Multiple Similar Query Hints
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_query_ordering">1.9.
Ordering
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_aggregates">1.10.
Aggregates
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_named">1.11.
Named Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_delete">1.12.
Delete By Query
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_update">1.13.
Update By Query
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref">2.
JPQL Language Reference
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_stmnttypes">2.1.
JPQL Statement Types
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_select">2.1.1.
JPQL Select Statement
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk">2.1.2.
JPQL Update and Delete Statements
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_schematypes">2.2.
JPQL Abstract Schema Types and Query Domains
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_schemanaming">2.2.1.
JPQL Entity Naming
</a></span></dt><dt><span class="section"><a href="#jpa_langref_schemaexample">2.2.2.
JPQL Schema Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_fromclause">2.3.
JPQL FROM Clause and Navigational Declarations
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_from_identifiers">2.3.1.
JPQL FROM Identifiers
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_vars">2.3.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_range">2.3.3.
JPQL Range Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path">2.3.4.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_Joins">2.3.5.
JPQL Joins
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_inner_joins">2.3.5.1.
JPQL Inner Joins (Relationship Joins)
</a></span></dt><dt><span class="section"><a href="#jpa_langref_outer_joins">2.3.5.2.
JPQL Outer Joins
</a></span></dt><dt><span class="section"><a href="#jpa_langref_fetch_joins">2.3.5.3.
JPQL Fetch Joins
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_collection_dec">2.3.6.
JPQL Collection Member Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_clause_and_sql">2.3.7.
JPQL FROM Clause and SQL
</a></span></dt><dt><span class="section"><a href="#jpa_langref_polymorph">2.3.8.
JPQL Polymorphism
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_where">2.4.
JPQL WHERE Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_cond">2.5.
JPQL Conditional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_lit">2.5.1.
JPQL Literals
</a></span></dt><dt><span class="section"><a href="#jpa_langref_idvar">2.5.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path_exp">2.5.3.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_input_params">2.5.4.
JPQL Input Parameters
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_pos_params">2.5.4.1.
JPQL Positional Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_langref_named_params">2.5.4.2.
JPQL Named Parameters
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_cond_comp">2.5.5.
JPQL Conditional Expression Composition
</a></span></dt><dt><span class="section"><a href="#jpa_langref_operators">2.5.6.
JPQL Operators and Operator Precedence
</a></span></dt><dt><span class="section"><a href="#jpa_langref_comparison_expressions">2.5.7.
JPQL Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_between">2.5.8.
JPQL Between Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_in_expressions">2.5.9.
JPQL In Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_like">2.5.10.
JPQL Like Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null">2.5.11.
JPQL Null Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_empty_comp">2.5.12.
JPQL Empty Collection Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_collection_member">2.5.13.
JPQL Collection Member Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_exists">2.5.14.
JPQL Exists Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_all_any">2.5.15.
JPQL All or Any Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_subqueries">2.5.16.
JPQL Subqueries
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_scalar_expressions">2.6.
JPQL Scalar Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_math_expressions">2.6.1.
Arithmetic Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_functional_expressions">2.6.2.
String, Arithmetic, and Datetime Functional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_string_fun">2.6.2.1.
JPQL String Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_arithmetic">2.6.2.2.
JPQL Arithmetic Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_datetime">2.6.2.3.
JPQL Datetime Functions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_case_expressions">2.6.3.
Case Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_entity_type_expressions">2.6.4.
Entity Type Expressions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_group">2.7.
JPQL GROUP BY, HAVING
</a></span></dt><dt><span class="section"><a href="#jpa_langref_select_clause">2.8.
JPQL SELECT Clause
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_resulttype">2.8.1.
JPQL Result Type of the SELECT Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_constructor">2.8.2.
JPQL Constructor Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_select">2.8.3.
JPQL Null Values in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_embeddables">2.8.4.
JPQL Embeddables in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_aggregates">2.8.5.
JPQL Aggregate Functions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_agg_examples">2.8.5.1.
JPQL Aggregate Examples
</a></span></dt><dt><span class="section"><a href="#jpa_langref_numeric_expressions_in_select">2.8.5.2.
JPQL Numeric Expressions in the SELECT Clause
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_langref_orderby">2.9.
JPQL ORDER BY Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk_ops">2.10.
JPQL Bulk Update and Delete
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_values">2.11.
JPQL Null Values
</a></span></dt><dt><span class="section"><a href="#jpa_langref_equality">2.12.
JPQL Equality and Comparison Semantics
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bnf">2.13.
JPQL BNF
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#jpa_overview_criteria">11.
JPA Criteria
</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e5247">1. Constructing a CriteriaQuery</a></span></dt><dt><span class="section"><a href="#d5e5264">2. Executing a CriteriaQuery</a></span></dt><dt><span class="section"><a href="#d5e5271">3. Extension to Criteria API</a></span></dt><dt><span class="section"><a href="#d5e5275">4. Generation of Canonical MetaModel classes</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_sqlquery">12.
SQL Queries
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_sqlquery_create">1.
Creating SQL Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_sqlquery_obj">2.
Retrieving Persistent Objects with SQL
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_mapping">13.
Mapping Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_table">1.
Table
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_unq">2.
Unique Constraints
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_column">3.
Column
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_id">4.
Identity Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence">5.
Generators
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_sequence_seqgen">5.1.
Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_tablegen">5.2.
Table Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_genex">5.3.
Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher">6.
Inheritance
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_single">6.1.
Single Table
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_adv">6.1.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_disadv">6.1.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined">6.2.
Joined
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_adv">6.2.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_disadv">6.2.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc">6.3.
Table Per Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_adv">6.3.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_disadv">6.3.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_together">6.4.
Putting it All Together
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_discrim">7.
Discriminator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_field">8.
Field Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_basic">8.1.
Basic Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_lob">8.1.1.
LOBs
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_enum">8.1.2.
Enumerated
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_temporal">8.1.3.
Temporal Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_basic_example">8.1.4.
The Updated Mappings
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_secondary">8.2.
Secondary Tables
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_embed">8.3.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_rel">8.4.
Direct Relations
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_assoccoll">8.5.
Join Table
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_bidi">8.6.
Bidirectional Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_map">8.7.
Map Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_full">9.
The Complete Mappings
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#jpa_overview_conclusion">14.
Conclusion
</a></span></dt></dl></div>
<div class="chapter" id="jpa_overview_intro"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;1.&nbsp;
Introduction
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_intro_audience">1.
Intended Audience
</a></span></dt><dt><span class="section"><a href="#jpa_overview_intro_transpers">2.
Lightweight Persistence
</a></span></dt></dl></div>
<p>
<a class="indexterm" name="d5e102"></a>
<a class="indexterm" name="d5e105"></a>
The Java Persistence 2.0 API (JPA 2.0) is a specification
for the persistence of Java objects to any relational
datastore. This document provides an overview of JPA 2.0. Unless
otherwise noted, the information presented applies to all JPA implementations.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
For coverage of OpenJPA's many extensions to the JPA specification,
see the <a class="link" href="#ref_guide_intro" title="Chapter&nbsp;1.&nbsp; Introduction">Reference Guide</a>.
</p>
</div>
<div class="section" id="jpa_overview_intro_audience"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Intended Audience
</h2></div></div></div>
<p>
This document is intended for developers who want to learn about JPA
in order to use it in their applications. It assumes that you have a strong
knowledge of object-oriented concepts and Java, including annotations and
generics. It also assumes some experience with relational databases and the
Structured Query Language (SQL).
</p>
</div>
<div class="section" id="jpa_overview_intro_transpers"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Lightweight Persistence
</h2></div></div></div>
<a class="indexterm" name="d5e115"></a>
<p>
<a class="indexterm" name="d5e118"></a>
<span class="emphasis"><em>Persistent data</em></span> is information that can outlive the program
that creates it. The majority of complex programs use persistent data: GUI
applications need to store user preferences across program invocations, web
applications track user movements and orders over long periods of time, etc.
</p>
<p>
<span class="emphasis"><em>Lightweight persistence</em></span> is the storage and retrieval of
persistent data with little or no work from you, the developer. For example,
Java serialization
<a class="indexterm" name="d5e123"></a>
is a form of lightweight persistence because it can be used to persist Java
objects directly to a file with very little effort. Serialization's capabilities
as a lightweight persistence mechanism pale in comparison to those provided by
JPA, however. The next chapter compares JPA to serialization and other available
persistence mechanisms.
</p>
</div>
</div>
<div class="chapter" id="jpa_overview_why"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;2.&nbsp;
Why JPA?
</h2></div></div></div>
<a class="indexterm" name="d5e127"></a>
<p>
Java developers who need to store and retrieve persistent data already have
several options available to them: serialization, JDBC, JDO, proprietary
object-relational mapping tools, object databases, and EJB 2 entity beans. Why
introduce yet another persistence framework? The answer to this question is that
with the exception of JDO, each of the aforementioned persistence solutions has
severe limitations. JPA attempts to overcome these limitations, as illustrated
by the table below.
</p>
<div class="table" id="d5e131"><p class="title"><b>Table&nbsp;2.1.&nbsp;
Persistence Mechanisms
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Persistence Mechanisms&#xA; " border="1"><colgroup><col align="left" class="sup"><col align="left" class="ser"><col align="left" class="jdbc"><col align="left" class="or"><col align="left" class="objdb"><col align="left" class="ejb2"><col align="left" class="jdo"><col align="left" class="jpa"></colgroup><thead><tr><th align="left">
Supports:
</th><th align="left">
Serialization
</th><th align="left">
JDBC
</th><th align="left">
ORM
</th><th align="left">
ODB
</th><th align="left">
EJB 2
</th><th align="left">
JDO
</th><th align="left">
JPA
</th></tr></thead><tbody><tr><td align="left">
Java Objects
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Advanced OO Concepts
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Transactional Integrity
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Concurrency
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Large Data Sets
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Existing Schema
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Relational and Non-Relational Stores
</td><td align="left">
No
</td><td align="left">
No
</td><td align="left">
No
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
No
</td></tr><tr><td align="left">
Queries
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Strict Standards / Portability
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
No
</td><td align="left">
No
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr><tr><td align="left">
Simplicity
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
No
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td><td align="left">
<span class="bold"><strong>
Yes
</strong></span>
</td></tr></tbody></table>
</div></div><br class="table-break">
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e298"></a>
<a class="indexterm" name="d5e300"></a>
<span class="emphasis"><em>Serialization</em></span> is Java's built-in mechanism for transforming
an object graph into a series of bytes, which can then be sent over the network
or stored in a file. Serialization is very easy to use, but it is also very
limited. It must store and retrieve the entire object graph at once, making it
unsuitable for dealing with large amounts of data. It cannot undo changes that
are made to objects if an error occurs while updating information, making it
unsuitable for applications that require strict data integrity. Multiple threads
or programs cannot read and write the same serialized data concurrently without
conflicting with each other. It provides no query capabilities. All these
factors make serialization useless for all but the most trivial persistence
needs.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e306"></a>
<a class="indexterm" name="d5e309"></a>
<a class="indexterm" name="d5e311"></a>
Many developers use the <span class="emphasis"><em>Java Database Connectivity</em></span> (JDBC)
APIs to manipulate persistent data in relational databases. JDBC overcomes most
of the shortcomings of serialization: it can handle large amounts of data, has
mechanisms to ensure data integrity, supports concurrent access to information,
and has a sophisticated query language in SQL. Unfortunately, JDBC does not
duplicate serialization's ease of use. The relational paradigm used by JDBC was
not designed for storing objects, and therefore forces you to either abandon
object-oriented programming for the portions of your code that deal with
persistent data, or to find a way of mapping object-oriented concepts like
inheritance to relational databases yourself.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e317"></a>
<a class="indexterm" name="d5e320"></a>
<a class="indexterm" name="d5e322"></a>
There are many proprietary software products that can perform the mapping
between objects and relational database tables for you. These <span class="emphasis"><em>
object-relational mapping</em></span> (ORM) frameworks allow you to focus on the
object model and not concern yourself with the mismatch between the
object-oriented and relational paradigms. Unfortunately, each of these product
has its own set of APIs. Your code becomes tied to the proprietary interfaces of
a single vendor. If the vendor raises prices, fails to fix show-stopping bugs,
or falls behind in features, you cannot switch to another product without
rewriting all of your persistence code. This is referred to as vendor lock-in.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e328"></a>
<a class="indexterm" name="d5e331"></a>
<a class="indexterm" name="d5e333"></a>
<a class="indexterm" name="d5e336"></a>
Rather than map objects to relational databases, some software companies have
developed a form of database designed specifically to store objects. These
<span class="emphasis"><em>object databases</em></span> (ODBs) are often much easier to use than
object-relational mapping software. The Object Database Management Group (ODMG)
was formed to create a standard API for accessing object databases; few object
database vendors, however, comply with the ODMG's recommendations. Thus, vendor
lock-in plagues object databases as well. Many companies are also hesitant to
switch from tried-and-true relational systems to the relatively unknown object
database technology. Fewer data-analysis tools are available for object database
systems, and there are vast quantities of data already stored in older
relational databases. For all of these reasons and more, object databases have
not caught on as well as their creators hoped.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e341"></a>
<a class="indexterm" name="d5e344"></a>
<a class="indexterm" name="d5e346"></a>
The Enterprise Edition of the Java platform introduced entity Enterprise Java
Beans (EJBs). EJB 2.x entities are components that represent persistent
information in a datastore. Like object-relational mapping solutions, EJB 2.x
entities provide an object-oriented view of persistent data. Unlike
object-relational software, however, EJB 2.x entities are not limited to
relational databases; the persistent information they represent may come from an
Enterprise Information System (EIS) or other storage device. Also, EJB 2.x
entities use a strict standard, making them portable across vendors.
Unfortunately, the EJB 2.x standard is somewhat limited in the object-oriented
concepts it can represent. Advanced features like inheritance, polymorphism, and
complex relations are absent. Additionally, EBJ 2.x entities are difficult to
code, and they require heavyweight and often expensive application servers to
run.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e351"></a>
<a class="indexterm" name="d5e353"></a>
The JDO specification uses an API that is strikingly similar to JPA. JDO,
however, supports non-relational databases, a feature that some argue dilutes
the specification.
</p>
</li></ul></div>
<p>
<a class="indexterm" name="d5e357"></a>
JPA combines the best features from each of the persistence mechanisms listed
above. Creating entities under JPA is as simple as creating serializable
classes. JPA supports the large data sets, data consistency, concurrent use, and
query capabilities of JDBC. Like object-relational software and object
databases, JPA allows the use of advanced object-oriented concepts such as
inheritance. JPA avoids vendor lock-in by relying on a strict specification like
JDO and EJB 2.x entities. JPA focuses on relational databases. And like JDO, JPA
is extremely easy to use.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA typically stores data in relational databases, but can be customized for
use with non-relational datastores as well.
</p>
</div>
<p>
JPA is not ideal for every application. For many applications, though, it
provides an exciting alternative to other persistence mechanisms.
</p>
</div>
<div class="chapter" id="jpa_overview_arch"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;3.&nbsp;
Java Persistence API Architecture
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_arch_exceptions">1.
JPA Exceptions
</a></span></dt></dl></div>
<a class="indexterm" name="d5e364"></a>
<p>
The diagram below illustrates the relationships between the primary components
of the JPA architecture.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="267"><tr><td><img src="img/jpa-arch.png"></td></tr></table></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
A number of the depicted interfaces are only required outside of an
EJB3-compliant application server. In an application server, <code class="classname">
EntityManager</code> instances are typically injected, rendering the
<code class="classname">EntityManagerFactory</code> unnecessary. Also, transactions
within an application server are handled using standard application server
transaction controls. Thus, the <code class="classname">EntityTransaction</code> also
goes unused.
</p>
</div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e381"></a>
<span class="bold"><strong><a class="link" href="#jpa_overview_persistence" title="Chapter&nbsp;6.&nbsp; Persistence"><code class="classname">
Persistence</code></a></strong></span>: The <code class="classname">
javax.persistence.Persistence</code> class contains static helper methods
to obtain <code class="classname">EntityManagerFactory</code> instances in a
vendor-neutral fashion.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e390"></a>
<span class="bold"><strong><a class="link" href="#jpa_overview_emfactory" title="Chapter&nbsp;7.&nbsp; EntityManagerFactory"><code class="classname">
EntityManagerFactory</code></a></strong></span>: The <code class="classname">
javax.persistence.EntityManagerFactory</code> class is a factory for
<code class="classname"> EntityManager</code> s.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e399"></a>
<span class="bold"><strong><a class="link" href="#jpa_overview_em" title="Chapter&nbsp;8.&nbsp; EntityManager"><code class="classname">EntityManager
</code></a></strong></span>: The <code class="classname">javax.persistence.EntityManager
</code> is the primary JPA interface used by applications. Each
<code class="classname">EntityManager</code> manages a set of persistent objects, and
has APIs to insert new objects and delete existing ones. When used outside the
container, there is a one-to-one relationship between an <code class="classname">
EntityManager</code> and an <code class="classname"> EntityTransaction</code>.
<code class="classname"> EntityManager</code>s also act as factories for <code class="classname">
Query</code> instances.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e412"></a>
<span class="bold"><strong><a class="link" href="#jpa_overview_pc" title="Chapter&nbsp;4.&nbsp; Entity"><code class="classname">Entity
</code></a></strong></span>: Entities are persistent objects that represent
datastore records.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e419"></a>
<span class="bold"><strong><a class="link" href="#jpa_overview_trans" title="Chapter&nbsp;9.&nbsp; Transaction"><code class="classname">
EntityTransaction</code></a></strong></span>: Each <code class="classname">EntityManager
</code> has a one-to-one relation with a single <code class="classname">
javax.persistence.EntityTransaction</code>. <code class="classname">
EntityTransaction</code>s allow operations on persistent data to be
grouped into units of work that either completely succeed or completely fail,
leaving the datastore in its original state. These all-or-nothing operations
are important for maintaining data integrity.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e429"></a>
<a class="indexterm" name="d5e431"></a>
<a class="indexterm" name="d5e434"></a>
<a class="indexterm" name="d5e436"></a>
<a class="indexterm" name="d5e440"></a>
<a class="indexterm" name="d5e443"></a>
<span class="bold"><strong><a class="link" href="#jpa_overview_query" title="Chapter&nbsp;10.&nbsp; JPA Query"><code class="classname">Query
</code></a></strong></span>: The <code class="classname">javax.persistence.Query
</code> interface is implemented by each JPA vendor to find persistent
objects that meet certain criteria. JPA standardizes support for queries using
both the Java Persistence Query Language (JPQL) and the Structured Query
Language (SQL). You obtain <code class="classname">Query</code> instances from an
<code class="classname">EntityManager</code>.
</p>
</li></ul></div>
<p>
The example below illustrates how the JPA interfaces interact to execute a JPQL
query and update persistent objects. The example assumes execution outside a
container.
</p>
<div class="example" id="jpa_overview_arch_interact_outside"><p class="title"><b>Example&nbsp;3.1.&nbsp;
Interaction of Interfaces Outside Container
</b></p><div class="example-contents">
<pre class="programlisting">
// get an EntityManagerFactory using the Persistence class
// It is not recommended to obtain a factory often, as construction of a
// factory is a costly operation. Typically you will like to cache
// a factory and then refer it for repeated use
EntityManagerFactory factory = Persistence.createEntityManagerFactory(null);
// get an EntityManager from the factory
EntityManager em = factory.createEntityManager();
// Begin a transaction
em.getTransaction().begin();
// query for all employees who work in our research division
// and put in over 40 hours a week average
Query query = em.createQuery("SELECT e " +
" FROM Employee e " +
" WHERE e.division.name = 'Research' " +
" AND e.avgHours &gt; 40");
List results = query.getResultList();
// give all those hard-working employees a raise
for (Object res : results) {
Employee emp = (Employee) res;
emp.setSalary(emp.getSalary() * 1.1);
}
// commit will detect all updated entities and save them in database
em.getTransaction().commit();
// free the resources
em.close();
</pre>
</div></div><br class="example-break">
<p>
Within a container, the <code class="classname">EntityManager</code> will be injected
and transactions will be handled declaratively. Thus, the in-container version
of the example consists entirely of business logic:
</p>
<div class="example" id="jpa_overview_arch_interact_inside"><p class="title"><b>Example&nbsp;3.2.&nbsp;
Interaction of Interfaces Inside Container
</b></p><div class="example-contents">
<pre class="programlisting">
// query for all employees who work in our research division
// and put in over 40 hours a week average - note that the EntityManager em
// is injected using a @Resource annotation
Query query = em.createQuery("select e from Employee e where "
+ "e.division.name = 'Research' and e.avgHours &gt; 40");
List results = query.getResultList();
// give all those hard-working employees a raise
for (Object res : results) {
emp = (Employee) res;
emp.setSalary(emp.getSalary() * 1.1);
}
</pre>
</div></div><br class="example-break">
<p>
The remainder of this document explores the JPA interfaces in detail. We present
them in roughly the order that you will use them as you develop your
application.
</p>
<div class="section" id="jpa_overview_arch_exceptions"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
JPA Exceptions
</h2></div></div></div>
<a class="indexterm" name="d5e463"></a>
<a class="indexterm" name="d5e467"></a>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="285"><tr><td><img src="img/jpa-exceptions.png"></td></tr></table></div>
<p>
The diagram above depicts the JPA exception architecture. All
exceptions are unchecked. JPA uses standard exceptions where
appropriate, most notably <code class="classname">IllegalArgumentException</code>s and
<code class="classname">IllegalStateException</code>s. The specification also provides
a few JPA-specific exceptions in the <code class="literal">javax.persistence</code>
package. These exceptions should be self-explanatory. See the
<a class="ulink" href="http://download.oracle.com/javaee/6/api/" target="_top">Javadoc</a> for
additional details on JPA exceptions.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
All exceptions thrown by OpenJPA implement
<a class="ulink" href="../../apidocs/org/apache/openjpa/util/ExceptionInfo.html" target="_top"><code class="classname">
org.apache.openjpa.util.ExceptionInfo</code></a> to provide you with
additional error information.
</p>
</div>
</div>
</div>
<div class="chapter" id="jpa_overview_pc"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;4.&nbsp;
Entity
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_pc_restrict">1.
Restrictions on Persistent Classes
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_no_arg">1.1.
Default or No-Arg Constructor
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_final">1.2.
Final
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_id">1.3.
Identity Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_version">1.4.
Version Field
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_inheritance">1.5.
Inheritance
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_fields">1.6.
Persistent Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_conclusion">1.7.
Conclusions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_identity">2.
Entity Identity
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_identitycls">2.1.
Identity Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_identity_hierarchy">2.1.1.
Identity Hierarchies
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_callbacks">3.
Lifecycle Callbacks
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_callbacks_methods">3.1.
Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_callbacks_using">3.2.
Using Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_using">3.3.
Using Entity Listeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_exclude">3.4.
Entity Listeners Hierarchy
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_pc_conclusion">4.
Conclusions
</a></span></dt></dl></div>
<a class="indexterm" name="d5e486"></a>
<a class="indexterm" name="d5e488"></a>
<a class="indexterm" name="d5e491"></a>
<a class="indexterm" name="d5e495"></a>
<p>
JPA recognizes two types of persistent classes: <span class="emphasis"><em>entity</em></span>
classes and <span class="emphasis"><em>embeddable</em></span> classes. Each persistent instance of
an entity class - each <span class="emphasis"><em>entity</em></span> - represents a unique
datastore record. You can use the <code class="classname">EntityManager</code> to find
an entity by its persistent identity (covered later in this chapter), or use a
<code class="classname">Query</code> to find entities matching certain criteria.
</p>
<p>
An instance of an embeddable class, on the other hand, is only stored as part of
a separate entity. Embeddable instances have no persistent identity, and are
never returned directly from the <code class="classname">EntityManager</code> or from a
<code class="classname">Query</code> unless the query uses a projection on owning class
to the embedded instance. For example, if <code class="classname">Address</code> is
embedded in <code class="classname">Company</code>, then
a query <code class="classname">"SELECT a FROM Address a"</code> will never return the
embedded <code class="classname">Address</code> of <code class="classname">Company</code>;
but a projection query such as
<code class="classname">"SELECT c.address FROM Company c"</code> will.
</p>
<p>
Despite these differences, there are few distinctions between entity classes and
embeddable classes. In fact, writing either type of persistent class is a lot
like writing any other class. There are no special parent classes to
extend from, field types to use, or methods to write. This is one important way
in which JPA makes persistence transparent to you, the developer.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
JPA supports both fields and JavaBean properties as persistent state. For
simplicity, however, we will refer to all persistent state as persistent fields,
unless we want to note a unique aspect of persistent properties.
</p>
</div>
<div class="example" id="jpa_overview_pc_pcclass"><p class="title"><b>Example&nbsp;4.1.&nbsp;
Persistent Class
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
/**
* Example persistent class. Notice that it looks exactly like any other
* class. JPA makes writing persistent classes completely transparent.
*/
public class Magazine {
private String isbn;
private String title;
private Set articles = new HashSet();
private Article coverArticle;
private int copiesSold;
private double price;
private Company publisher;
private int version;
protected Magazine() {
}
public Magazine(String title, String isbn) {
this.title = title;
this.isbn = isbn;
}
public void publish(Company publisher, double price) {
this.publisher = publisher;
publisher.addMagazine(this);
this.price = price;
}
public void sell() {
copiesSold++;
publisher.addRevenue(price);
}
public void addArticle(Article article) {
articles.add(article);
}
// rest of methods omitted
}
</pre>
</div></div><br class="example-break">
<div class="section" id="jpa_overview_pc_restrict"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Restrictions on Persistent Classes
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_pc_no_arg">1.1.
Default or No-Arg Constructor
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_final">1.2.
Final
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_id">1.3.
Identity Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_version">1.4.
Version Field
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_inheritance">1.5.
Inheritance
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_fields">1.6.
Persistent Fields
</a></span></dt><dt><span class="section"><a href="#jpa_overview_pc_restrict_conclusion">1.7.
Conclusions
</a></span></dt></dl></div>
<a class="indexterm" name="d5e521"></a>
<p>
There are very few restrictions placed on persistent classes. Still, it never
hurts to familiarize yourself with exactly what JPA does and does not support.
</p>
<div class="section" id="jpa_overview_pc_no_arg"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Default or No-Arg Constructor
</h3></div></div></div>
<a class="indexterm" name="d5e527"></a>
<a class="indexterm" name="d5e530"></a>
<p>
The JPA specification requires that all persistent classes have a no-arg
constructor. This constructor may be public or protected. Because the compiler
automatically creates a default no-arg constructor when no other constructor is
defined, only classes that define constructors must also include a no-arg
constructor.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA's <span class="emphasis"><em>enhancer</em></span> will automatically add a protected
no-arg constructor to your class when required. Therefore, this restriction does
not apply when using the enhancer. See <a class="xref" href="#ref_guide_pc_enhance" title="2.&nbsp; Enhancement">Section&nbsp;2, &#8220;
Enhancement
&#8221;</a>
of the Reference Guide for details.
</p>
</div>
</div>
<div class="section" id="jpa_overview_pc_final"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Final
</h3></div></div></div>
<p>
Entity classes may not be final. No method of an entity class can be final.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA supports final classes and final methods.
</p>
</div>
</div>
<div class="section" id="jpa_overview_pc_id"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Identity Fields
</h3></div></div></div>
<a class="indexterm" name="d5e545"></a>
<a class="indexterm" name="d5e548"></a>
<p>
All entity classes must declare one or more fields which together form the
persistent identity of an instance. These are called <span class="emphasis"><em>identity
</em></span> or <span class="emphasis"><em>primary key</em></span> fields. In our <code class="classname">
Magazine</code> class, <code class="literal">isbn</code> and <code class="literal">title</code>
are identity fields, because no two magazine records in the datastore can have
the same <code class="literal">isbn</code> and <code class="literal">title</code> values.
<a class="xref" href="#jpa_overview_meta_id" title="2.3.&nbsp; Id">Section&nbsp;2.3, &#8220;
Id
&#8221;</a> will show you how to denote your
identity fields in JPA metadata. <a class="xref" href="#jpa_overview_pc_identity" title="2.&nbsp; Entity Identity">Section&nbsp;2, &#8220;
Entity Identity
&#8221;</a>
below examines persistent identity.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA fully supports identity fields, but does not require them. See
<a class="xref" href="#ref_guide_pc_oid" title="4.&nbsp; Object Identity">Section&nbsp;4, &#8220;
Object Identity
&#8221;</a> of the Reference Guide for details.
</p>
</div>
</div>
<div class="section" id="jpa_overview_pc_version"><div class="titlepage"><div><div><h3 class="title">1.4.&nbsp;
Version Field
</h3></div></div></div>
<a class="indexterm" name="d5e566"></a>
<a class="indexterm" name="d5e569"></a>
<p>
The <code class="literal">version</code> field in our <code class="classname">Magazine</code>
class may seem out of place. JPA uses a version field in your entities to detect
concurrent modifications to the same datastore record. When the JPA runtime
detects an attempt to concurrently modify the same record, it throws an
exception to the transaction attempting to commit last. This prevents
overwriting the previous commit with stale data.
</p>
<p>
A version field is not required, but without one concurrent threads or
processes might succeed in making conflicting changes to the same record at the
same time. This is unacceptable to most applications.
<a class="xref" href="#jpa_overview_meta_version" title="2.6.&nbsp; Version">Section&nbsp;2.6, &#8220;
Version
&#8221;</a> shows you how to designate a
version field in JPA metadata.
</p>
<p>
The version field must be an integral type (<code class="classname"> int</code>,
<code class="classname">Long</code>, etc) or a <code class="classname">
java.sql.Timestamp</code>. You should consider version fields immutable.
Changing the field value has undefined results.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA fully supports version fields, but does not require them within the actual entity for concurrency
detection. OpenJPA can maintain surrogate version values or use state
comparisons to detect concurrent modifications. See
<a class="xref" href="#ref_guide_mapping_jpa" title="7.&nbsp; Additional JPA Mappings">Section&nbsp;7, &#8220;
Additional JPA Mappings
&#8221;</a> in the Reference Guide.
</p>
</div>
</div>
<div class="section" id="jpa_overview_pc_restrict_inheritance"><div class="titlepage"><div><div><h3 class="title">1.5.&nbsp;
Inheritance
</h3></div></div></div>
<a class="indexterm" name="d5e586"></a>
<a class="indexterm" name="d5e590"></a>
<p>
JPA fully supports inheritance in persistent classes. It allows persistent
classes to inherit from non-persistent classes, persistent classes to inherit
from other persistent classes, and non-persistent classes to inherit from
persistent classes. It is even possible to form inheritance hierarchies in which
persistence skips generations. There are, however, a few important limitations:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Persistent classes cannot inherit from certain natively-implemented system
classes such as <code class="classname">java.net.Socket</code> and <code class="classname">
java.lang.Thread</code>.
</p>
</li><li class="listitem">
<p>
If a persistent class inherits from a non-persistent class, the fields of the
non-persistent superclass cannot be persisted.
</p>
</li><li class="listitem">
<p>
All classes in an inheritance tree must use the same identity type. We cover
entity identity in <a class="xref" href="#jpa_overview_pc_identity" title="2.&nbsp; Entity Identity">Section&nbsp;2, &#8220;
Entity Identity
&#8221;</a>.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_pc_restrict_fields"><div class="titlepage"><div><div><h3 class="title">1.6.&nbsp;
Persistent Fields
</h3></div></div></div>
<a class="indexterm" name="d5e606"></a>
<a class="indexterm" name="d5e610"></a>
<a class="indexterm" name="d5e614"></a>
<p>
JPA manages the state of all persistent fields. Before you access persistent
state, the JPA runtime makes sure that it has been loaded from the datastore.
When you set a field, the runtime records that it has changed so that the new
value will be persisted. This allows you to treat the field in exactly the same
way you treat any other field - another aspect of JPA's transparency.
</p>
<p>
JPA does not support static or final fields. It does, however, include built-in
support for most common field types. These types can be roughly divided into
three categories: immutable types, mutable types, and relations.
</p>
<p>
<a class="indexterm" name="d5e620"></a>
<a class="indexterm" name="d5e623"></a>
<span class="emphasis"><em>Immutable</em></span> types, once created, cannot be changed. The only
way to alter a persistent field of an immutable type is to assign a new value to
the field. JPA supports the following immutable types:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
All primitives (<code class="classname">int, float, byte</code>, etc)
</p>
</li><li class="listitem">
<p>
All primitive wrappers (<code class="classname">java.lang.Integer, java.lang.Float,
java.lang.Byte</code>, etc)
</p>
</li><li class="listitem">
<p>
<code class="classname">java.lang.String</code>
</p>
</li><li class="listitem">
<p>
<code class="classname">java.math.BigInteger</code>
</p>
</li><li class="listitem">
<p>
<code class="classname">java.math.BigDecimal</code>
</p>
</li></ul></div>
<p>
JPA also supports <code class="classname">byte[]</code>, <code class="classname">Byte[]</code>,
<code class="classname">char[]</code>, and <code class="classname">Character[]</code> as
immutable types. That is, you can persist fields of these types,
but you should not manipulate individual array indexes without resetting the
array into the persistent field.
</p>
<p>
<a class="indexterm" name="d5e649"></a>
<a class="indexterm" name="d5e653"></a>
<a class="indexterm" name="d5e658"></a>
<a class="indexterm" name="d5e661"></a>
Persistent fields of <span class="emphasis"><em>mutable</em></span> types can be altered without
assigning the field a new value. Mutable types can be modified directly through
their own methods. The JPA specification requires that implementations support
the following mutable field types:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="classname">java.util.Date</code>
</p>
</li><li class="listitem">
<p>
<code class="classname">java.util.Calendar</code>
</p>
</li><li class="listitem">
<p>
<code class="classname">java.sql.Date</code>
</p>
</li><li class="listitem">
<p>
<code class="classname">java.sql.Timestamp</code>
</p>
</li><li class="listitem">
<p>
<code class="classname">java.sql.Time</code>
</p>
</li><li class="listitem">
<p>
Enums
</p>
</li><li class="listitem">
<p>
Entity types (relations between entities)
</p>
</li><li class="listitem">
<p>
Embeddable types
</p>
</li><li class="listitem">
<p>
<code class="classname">java.util.Collection</code>s of entities
</p>
</li><li class="listitem">
<p>
<code class="classname">java.util.Set</code>s of entities
</p>
</li><li class="listitem">
<p>
<code class="classname">java.util.List</code>s of entities
</p>
</li><li class="listitem">
<p>
<code class="classname">java.util.Map</code>s in which each entry maps the value of one
of a related entity's fields to that entity.
</p>
</li></ul></div>
<p>
Collection and map types may be parameterized.
</p>
<p>
<a class="indexterm" name="d5e702"></a>
<a class="indexterm" name="d5e705"></a>
Most JPA implementations also have support for persisting serializable values as
binary data in the datastore. <a class="xref" href="#jpa_overview_meta" title="Chapter&nbsp;5.&nbsp; Metadata">Chapter&nbsp;5, <i>
Metadata
</i></a> has more
information on persisting serializable types.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA also supports arrays, <code class="classname">java.lang.Number</code>,
<code class="classname">java.util.Locale</code>, all JDK 1.2 <code class="classname">Set</code>,
<code class="classname">List</code>, and <code class="classname">Map</code> types,
and many other mutable and immutable field types. OpenJPA also allows you to
plug in support for custom types.
</p>
</div>
</div>
<div class="section" id="jpa_overview_pc_restrict_conclusion"><div class="titlepage"><div><div><h3 class="title">1.7.&nbsp;
Conclusions
</h3></div></div></div>
<p>
This section detailed all of the restrictions JPA places on persistent classes.
While it may seem like we presented a lot of information, you will seldom find
yourself hindered by these restrictions in practice. Additionally, there are
often ways of using JPA's other features to circumvent any limitations you run
into.
</p>
</div>
</div>
<div class="section" id="jpa_overview_pc_identity"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Entity Identity
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_pc_identitycls">2.1.
Identity Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_pc_identity_hierarchy">2.1.1.
Identity Hierarchies
</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e722"></a>
<a class="indexterm" name="d5e726"></a>
<a class="indexterm" name="d5e729"></a>
<p>
<a class="indexterm" name="d5e733"></a>
<a class="indexterm" name="d5e736"></a>
<a class="indexterm" name="d5e739"></a>
<a class="indexterm" name="d5e742"></a>
Java recognizes two forms of object identity: numeric identity and qualitative
identity. If two references are <span class="emphasis"><em>numerically</em></span> identical, then
they refer to the same JVM instance in memory. You can test for this using the
<code class="literal">==</code> operator. <span class="emphasis"><em>Qualitative</em></span> identity, on
the other hand, relies on some user-defined criteria to determine whether two
objects are "equal". You test for qualitative identity using the <code class="methodname">
equals</code> method. By default, this method simply relies on numeric
identity.
</p>
<p>
JPA introduces another form of object identity, called <span class="emphasis"><em>entity
identity</em></span> or <span class="emphasis"><em>persistent identity</em></span>. Entity
identity tests whether two persistent objects represent the same state in the
datastore.
</p>
<p>
<a class="indexterm" name="d5e753"></a>
<a class="indexterm" name="d5e756"></a>
The entity identity of each persistent instance is encapsulated in its
<span class="emphasis"><em>identity field(s)</em></span>. If two entities of the same type have
the same identity field values, then the two entities represent the same state
in the datastore. Each entity's identity field values must be unique among all
other entities of the same type.
</p>
<p>
Identity fields must be primitives, primitive wrappers, <code class="classname">
String</code>s, <code class="classname">Date</code>s, <code class="classname">
Timestamp</code>s, or embeddable types.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA supports entities as identity fields, as the Reference Guide discusses
in <a class="xref" href="#ref_guide_pc_oid_entitypk" title="4.2.&nbsp; Entities as Identity Fields">Section&nbsp;4.2, &#8220;
Entities as Identity Fields
&#8221;</a>. For legacy schemas with binary
primary key columns, OpenJPA also supports using identity fields of type
<code class="classname">byte[]</code>. When you use a <code class="classname">byte[]</code>
identity field, you must create an identity class. Identity classes are
covered below.
</p>
</div>
<div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Warning</h3>
<p>
Changing the fields of an embeddable instance while it is assigned to an
identity field has undefined results. Always treat embeddable identity instances
as immutable objects in your applications.
</p>
</div>
<p>
<a class="indexterm" name="d5e773"></a>
<a class="indexterm" name="d5e776"></a>
If you are dealing with a single persistence context (see
<a class="xref" href="#jpa_overview_emfactory_perscontext" title="3.&nbsp; Persistence Context">Section&nbsp;3, &#8220;
Persistence Context
&#8221;</a>), then you do not
have to compare identity fields to test whether two entity references represent
the same state in the datastore. There is a much easier way: the <code class="literal">==
</code> operator. JPA requires that each persistence context maintain only
one JVM object to represent each unique datastore record. Thus, entity identity
is equivalent to numeric identity within a persistence context. This is referred
to as the <span class="emphasis"><em>uniqueness requirement</em></span>.
</p>
<p>
The uniqueness requirement is extremely important - without it, it would be
impossible to maintain data integrity. Think of what could happen if two
different objects in the same transaction were allowed to represent the same
persistent data. If you made different modifications to each of these objects,
which set of changes should be written to the datastore? How would your
application logic handle seeing two different "versions" of the same data?
Thanks to the uniqueness requirement, these questions do not have to be
answered.
</p>
<div class="section" id="jpa_overview_pc_identitycls"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
Identity Class
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_pc_identity_hierarchy">2.1.1.
Identity Hierarchies
</a></span></dt></dl></div>
<p>
<a class="indexterm" name="d5e786"></a>
<a class="indexterm" name="d5e789"></a>
If your entity has only one identity field, you can use the value of that field
as the entity's identity object in all <a class="link" href="#jpa_overview_em" title="Chapter&nbsp;8.&nbsp; EntityManager">
<code class="classname">EntityManager</code></a> APIs. Otherwise, you must supply an
identity class to use for identity objects. Your identity class must meet the
following criteria:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The class must be public.
</p>
</li><li class="listitem">
<p>
The class must be serializable.
</p>
</li><li class="listitem">
<p>
The class must have a public no-args constructor.
</p>
</li><li class="listitem">
<p>
The names of the non-static fields or properties of the class must be the same
as the names of the identity fields or properties of the corresponding entity
class, and the types must be identical.
</p>
</li><li class="listitem">
<p>
The <code class="methodname">equals</code> and <code class="methodname">hashCode</code>
methods of the class must use the values of all fields or properties
corresponding to identity fields or properties in the entity class.
</p>
</li><li class="listitem">
<p>
If the class is an inner class, it must be <code class="literal">static</code>.
</p>
</li><li class="listitem">
<p>
All entity classes related by inheritance must use the same identity class, or
else each entity class must have its own identity class whose inheritance
hierarchy mirrors the inheritance hierarchy of the owning entity classes (see
<a class="xref" href="#jpa_overview_pc_identity_hierarchy" title="2.1.1.&nbsp; Identity Hierarchies">Section&nbsp;2.1.1, &#8220;
Identity Hierarchies
&#8221;</a>).
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Though you may still create identity classes by hand, OpenJPA provides the
<code class="classname">appidtool</code> to automatically generate proper identity
classes based on your identity fields. See
<a class="xref" href="#ref_guide_pc_oid_application" title="4.3.&nbsp; Application Identity Tool">Section&nbsp;4.3, &#8220;
Application Identity Tool
&#8221;</a> of the Reference Guide.
</p>
</div>
<div class="example" id="jpa_overview_pc_identity_appidcode"><p class="title"><b>Example&nbsp;4.2.&nbsp;
Identity Class
</b></p><div class="example-contents">
<p>
This example illustrates a proper identity class for an entity with multiple
identity fields.
</p>
<pre class="programlisting">
/**
* Persistent class using application identity.
*/
public class Magazine {
private String isbn; // identity field
private String title; // identity field
// rest of fields and methods omitted
/**
* Application identity class for Magazine.
*/
public static class MagazineId {
// each identity field in the Magazine class must have a
// corresponding field in the identity class
public String isbn;
public String title;
/**
* Equality must be implemented in terms of identity field
* equality, and must use instanceof rather than comparing
* classes directly (some JPA implementations may subclass the
* identity class).
*/
public boolean equals(Object other) {
if (other == this)
return true;
if (!(other instanceof MagazineId))
return false;
MagazineId mi = (MagazineId) other;
return (isbn == mi.isbn
|| (isbn != null &amp;&amp; isbn.equals(mi.isbn)))
&amp;&amp; (title == mi.title
|| (title != null &amp;&amp; title.equals(mi.title)));
}
/**
* Hashcode must also depend on identity values.
*/
public int hashCode() {
return ((isbn == null) ? 0 : isbn.hashCode())
^ ((title == null) ? 0 : title.hashCode());
}
public String toString() {
return isbn + ":" + title;
}
}
}
</pre>
</div></div><br class="example-break">
<div class="section" id="jpa_overview_pc_identity_hierarchy"><div class="titlepage"><div><div><h4 class="title">2.1.1.&nbsp;
Identity Hierarchies
</h4></div></div></div>
<a class="indexterm" name="d5e823"></a>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="213"><tr><td><img src="img/appid-hierarchy.png"></td></tr></table></div>
<p>
An alternative to having a single identity class for an entire inheritance
hierarchy is to have one identity class per level in the inheritance hierarchy.
The requirements for using a hierarchy of identity classes are as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The inheritance hierarchy of identity classes must exactly mirror the hierarchy
of the persistent classes that they identify. In the example pictured above,
abstract class <code class="classname">Person</code> is extended by abstract class
<code class="classname">Employee</code>, which is extended by non-abstract class
<code class="classname"> FullTimeEmployee</code>, which is extended by non-abstract
class <code class="classname">Manager</code>. The corresponding identity classes, then,
are an abstract <code class="classname">PersonId</code> class, extended by an abstract
<code class="classname">EmployeeId</code> class, extended by a non-abstract <code class="classname">
FullTimeEmployeeId</code> class, extended by a non-abstract <code class="classname">
ManagerId</code> class.
</p>
</li><li class="listitem">
<p>
Subclasses in the identity hierarchy may define additional identity fields until
the hierarchy becomes non-abstract. In the aforementioned example, <code class="classname">
Person</code> defines an identity field <code class="literal">ssn</code>, <code class="classname">
Employee</code> defines additional identity field <code class="literal">userName
</code>, and <code class="classname">FullTimeEmployee</code> adds a final identity
field, <code class="literal">empId</code>. However, <code class="classname">Manager</code> may not
define any additional identity fields, since it is a subclass of a non-abstract
class. The hierarchy of identity classes, of course, must match the identity
field definitions of the persistent class hierarchy.
</p>
</li><li class="listitem">
<p>
It is not necessary for each abstract class to declare identity fields. In the
previous example, the abstract <code class="classname">Person</code> and <code class="classname">
Employee</code> classes could declare no identity fields, and the first
concrete subclass <code class="classname">FullTimeEmployee</code> could define one or
more identity fields.
</p>
</li><li class="listitem">
<p>
All subclasses of a concrete identity class must be <code class="methodname">equals
</code> and <code class="methodname">hashCode</code>-compatible with the
concrete superclass. This means that in our example, a <code class="classname">ManagerId
</code> instance and a <code class="classname">FullTimeEmployeeId</code> instance
with the same identity field values should have the same hash code, and should
compare equal to each other using the <code class="methodname">equals</code> method of
either one. In practice, this requirement reduces to the following coding
practices:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
Use <code class="literal">instanceof</code> instead of comparing <code class="classname">Class
</code> objects in the <code class="methodname">equals</code> methods of your
identity classes.
</p>
</li><li class="listitem">
<p>
An identity class that extends another non-abstract identity class should not
override <code class="methodname">equals</code> or <code class="methodname">hashCode</code>.
</p>
</li></ol></div>
</li></ul></div>
</div>
</div>
</div>
<div class="section" id="jpa_overview_pc_callbacks"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Lifecycle Callbacks
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_pc_callbacks_methods">3.1.
Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_callbacks_using">3.2.
Using Callback Methods
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_using">3.3.
Using Entity Listeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_entity_listeners_exclude">3.4.
Entity Listeners Hierarchy
</a></span></dt></dl></div>
<a class="indexterm" name="d5e874"></a>
<a class="indexterm" name="d5e876"></a>
<p>
It is often necessary to perform various actions at different stages of a
persistent object's lifecycle. JPA includes a variety of callbacks methods for
monitoring changes in the lifecycle of your persistent objects. These callbacks
can be defined on the persistent classes themselves and on non-persistent
listener classes.
</p>
<div class="section" id="jpa_overview_pc_callbacks_methods"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;
Callback Methods
</h3></div></div></div>
<a class="indexterm" name="d5e883"></a>
<a class="indexterm" name="d5e886"></a>
<p>
Every persistence event has a corresponding callback method marker. These
markers are shared between persistent classes and their listeners. You can use
these markers to designate a method for callback either by annotating that
method or by listing the method in the XML mapping file for a given class. The
lifecycle events and their corresponding method markers are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e893"></a>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/PrePersist.html" target="_top">
<code class="classname">PrePersist</code></a>: Methods marked with this annotation
will be invoked before an object is persisted. This could be used for assigning
primary key values to persistent objects. This is equivalent to the XML element
tag <code class="literal">pre-persist</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e901"></a>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/PostPersist.html" target="_top">
<code class="classname">PostPersist</code></a>: Methods marked with this annotation
will be invoked after an object has transitioned to the persistent state. You
might want to use such methods to update a screen after a new row is added. This
is equivalent to the XML element tag <code class="literal">post-persist</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e909"></a>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/PostLoad.html" target="_top">
<code class="classname">PostLoad</code></a>: Methods marked with this annotation
will be invoked after all eagerly fetched fields of your class have been loaded
from the datastore. No other persistent fields can be accessed in this method.
This is equivalent to the XML element tag <code class="literal">post-load</code>.
</p>
<p>
<code class="classname">PostLoad</code> is often used to initialize non-persistent
fields whose values depend on the values of persistent fields, such as a complex
data structure.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e919"></a>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/PreUpdate.html" target="_top">
<code class="classname">PreUpdate</code></a>: Methods marked with this annotation
will be invoked just the persistent values in your objects are flushed to the
datastore. This is equivalent to the XML element tag <code class="literal">
pre-update</code>.
</p>
<p>
<code class="classname">PreUpdate</code> is the complement to <code class="classname">PostLoad
</code>. While methods marked with <code class="classname">PostLoad</code> are most
often used to initialize non-persistent values from persistent data, methods
annotated with <code class="classname">PreUpdate</code> is normally used to set
persistent fields with information cached in non-persistent data.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e932"></a>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/PostUpdate.html" target="_top">
<code class="classname">PostUpdate</code></a>: Methods marked with this annotation
will be invoked after changes to a given instance have been stored to the
datastore. This is useful for clearing stale data cached at the application
layer. This is equivalent to the XML element tag <code class="literal">post-update</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e940"></a>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/PreRemove.html" target="_top">
<code class="classname">PreRemove</code></a>: Methods marked with this annotation
will be invoked before an object transactions to the deleted state. Access to
persistent fields is valid within this method. You might use this method to
cascade the deletion to related objects based on complex criteria, or to perform
other cleanup. This is equivalent to the XML element tag <code class="literal">
pre-remove</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e948"></a>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/PostRemove.html" target="_top">
<code class="classname">PostRemove</code></a>: Methods marked with this annotation
will be invoked after an object has been marked as to be deleted. This is
equivalent to the XML element tag <code class="literal">post-remove</code>.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_callbacks_using"><div class="titlepage"><div><div><h3 class="title">3.2.&nbsp;
Using Callback Methods
</h3></div></div></div>
<p>
When declaring callback methods on a persistent class, any method may be used
which takes no arguments and is not shared with any property access fields.
Multiple events can be assigned to a single method as well.
</p>
<p>
Below is an example of how to declare callback methods on persistent classes:
</p>
<pre class="programlisting">
/**
* Example persistent class declaring our entity listener.
*/
@Entity
public class Magazine {
@Transient
private byte[][] data;
@ManyToMany
private List&lt;Photo&gt; photos;
@PostLoad
public void convertPhotos() {
data = new byte[photos.size()][];
for (int i = 0; i &lt; photos.size(); i++)
data[i] = photos.get(i).toByteArray();
}
@PreDelete
public void logMagazineDeletion() {
getLog().debug("deleting magazine containing" + photos.size()
+ " photos.");
}
}
</pre>
<p>
In an XML mapping file, we can define the same methods without annotations:
</p>
<pre class="programlisting">
&lt;entity class="Magazine"&gt;
&lt;pre-remove&gt;logMagazineDeletion&lt;/pre-remove&gt;
&lt;post-load&gt;convertPhotos&lt;/post-load&gt;
&lt;/entity&gt;
</pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
We fully explore persistence metadata annotations and XML in
<a class="xref" href="#jpa_overview_meta" title="Chapter&nbsp;5.&nbsp; Metadata">Chapter&nbsp;5, <i>
Metadata
</i></a>.
</p>
</div>
</div>
<div class="section" id="jpa_overview_entity_listeners_using"><div class="titlepage"><div><div><h3 class="title">3.3.&nbsp;
Using Entity Listeners
</h3></div></div></div>
<p>
Mixing lifecycle event code into your persistent classes is not always ideal. It
is often more elegant to handle cross-cutting lifecycle events in a
non-persistent listener class. JPA allows for this, requiring only that listener
classes have a public no-arg constructor. Like persistent classes, your listener
classes can consume any number of callbacks. The callback methods must take in a
single <code class="classname">java.lang.Object</code> argument which represents the
persistent object that triggered the event.
</p>
<p>
Entities can enumerate listeners using the <code class="classname">EntityListeners
</code> annotation. This annotation takes an array of listener classes as
its value.
</p>
<p>
Below is an example of how to declare an entity and its corresponding listener
classes.
</p>
<pre class="programlisting">
/**
* Example persistent class declaring our entity listener.
*/
@Entity
@EntityListeners({ MagazineLogger.class, ... })
public class Magazine {
// ... //
}
/**
* Example entity listener.
*/
public class MagazineLogger {
@PostPersist
public void logAddition(Object pc) {
getLog().debug("Added new magazine:" + ((Magazine) pc).getTitle());
}
@PreRemove
public void logDeletion(Object pc) {
getLog().debug("Removing from circulation:" +
((Magazine) pc).getTitle());
}
}
</pre>
<p>
In XML, we define both the listeners and their callback methods as so:
</p>
<pre class="programlisting">
&lt;entity class="Magazine"&gt;
&lt;entity-listeners&gt;
&lt;entity-listener class="MagazineLogger"&gt;
&lt;post-persist&gt;logAddition&lt;/post-persist&gt;
&lt;pre-remove&gt;logDeletion&lt;/pre-remove&gt;
&lt;/entity-listener&gt;
&lt;/entity-listeners&gt;
&lt;/entity&gt;
</pre>
</div>
<div class="section" id="jpa_overview_entity_listeners_exclude"><div class="titlepage"><div><div><h3 class="title">3.4.&nbsp;
Entity Listeners Hierarchy
</h3></div></div></div>
<a class="indexterm" name="d5e976"></a>
<p>
Entity listener methods are invoked in a specific order when a given event is
fired. So-called <span class="emphasis"><em>default</em></span> listeners are invoked first: these
are listeners which have been defined in a package annotation or in the root
element of XML mapping files. Next, entity listeners are invoked in the order of
the inheritance hierarchy, with superclass listeners being invoked before
subclass listeners. Finally, if an entity has multiple listeners for the same
event, the listeners are invoked in declaration order.
</p>
<p>
You can exclude default listeners and listeners defined in superclasses from the
invocation chain through the use of two class-level annotations:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="classname">ExcludeDefaultListeners</code>: This annotation indicates that
no default listeners will be invoked for this class, or any of its subclasses.
The XML equivalent is the empty <code class="literal">exclude-default-listeners</code>
element.
</p>
</li><li class="listitem">
<p>
<code class="classname">ExcludeSuperclassListeners</code>: This annotation will cause
OpenJPA to skip invoking any listeners declared in superclasses. The XML
equivalent is the empty <code class="literal">exclude-superclass-listeners</code> element.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="jpa_overview_pc_conclusion"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Conclusions
</h2></div></div></div>
<p>
This chapter covered everything you need to know to write persistent class
definitions in JPA. JPA cannot use your persistent classes, however, until you
complete one additional step: you must define the persistence metadata. The next
chapter explores metadata in detail.
</p>
</div>
</div>
<div class="chapter" id="jpa_overview_meta"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;5.&nbsp;
Metadata
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_meta_class">1.
Class Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_entity">1.1.
Entity
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_idclass">1.2.
Id Class
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddablesuper">1.3.
Mapped Superclass
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddable">1.4.
Embeddable
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_entity_listeners">1.5.
EntityListeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_classex">1.6.
Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_field">2.
Field and Property Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_explicit_access">2.1.
Explicit Access
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_transient">2.2.
Transient
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_id">2.3.
Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_gen">2.4.
Generated Value
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embedid">2.5.
Embedded Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_version">2.6.
Version
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_basic">2.7.
Basic
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_fetch">2.7.1.
Fetch Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_embedded">2.8.
Embedded
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytoone">2.9.
Many To One
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_cascade">2.9.1.
Cascade Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetomany">2.10.
One To Many
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_mappedby">2.10.1.
Bidirectional Relations
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetoone">2.11.
One To One
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytomany">2.12.
Many To Many
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_orderby">2.13.
Order By
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_mapkey">2.14.
Map Key
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_fielddefaults">2.15.
Persistent Field Defaults
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_xml">3.
XML Schema
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_complete">4.
Conclusion
</a></span></dt></dl></div>
<a class="indexterm" name="d5e996"></a>
<a class="indexterm" name="d5e998"></a>
<p>
JPA requires that you accompany each persistent class with persistence metadata.
This metadata serves three primary purposes:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
To identify persistent classes.
</p>
</li><li class="listitem">
<p>
To override default JPA behavior.
</p>
</li><li class="listitem">
<p>
To provide the JPA implementation with information that it cannot glean from
simply reflecting on the persistent class.
</p>
</li></ol></div>
<p>
<a class="indexterm" name="d5e1011"></a>
Persistence metadata is specified using either the Java annotations defined in
the <code class="literal">javax.persistence</code> package, XML mapping files, or a
mixture of both. In the latter case, XML declarations override conflicting
annotations. If you choose to use XML metadata, the XML files must be available
at development and runtime, and must be discoverable via either of two
strategies:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
In a resource named <code class="filename">orm.xml</code> placed in a <code class="filename">
META-INF</code> directory within a directory in your classpath or within a
jar archive containing your persistent classes.
</p>
</li><li class="listitem">
<p>
Declared in your <a class="link" href="#jpa_overview_persistence_xml" title="1.&nbsp; persistence.xml"><code class="filename">
persistence.xml</code></a> configuration file. In this case, each XML
metadata file must be listed in a <code class="literal">mapping-file</code> element whose
content is either a path to the given file or a resource location available to
the class' class loader.
</p>
</li></ol></div>
<p>
We describe the standard metadata annotations and XML equivalents throughout
this chapter. The full schema for XML mapping files is available in
<a class="xref" href="#jpa_overview_meta_xml" title="3.&nbsp; XML Schema">Section&nbsp;3, &#8220;
XML Schema
&#8221;</a>. JPA also standardizes relational
mapping metadata and named query metadata, which we discuss in
<a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a> and
<a class="xref" href="#jpa_overview_query_named" title="1.11.&nbsp; Named Queries">Section&nbsp;1.11, &#8220;
Named Queries
&#8221;</a> respectively.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA defines many useful annotations beyond the standard set. See
<a class="xref" href="#ref_guide_meta_jpa" title="3.&nbsp; Additional JPA Metadata">Section&nbsp;3, &#8220;
Additional JPA Metadata
&#8221;</a> and
<a class="xref" href="#ref_guide_meta_ext" title="4.&nbsp; Metadata Extensions">Section&nbsp;4, &#8220;
Metadata Extensions
&#8221;</a>
in the Reference Guide for details. There are currently no XML equivalents for
these extension annotations.
</p>
</div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Persistence metadata may be used to validate the contents of your entities prior to communicating
with the database. This differs from mapping meta data which is primarily used for schema generation.
For example if you indicate that a relationship is not optional (e.g. @Basic(optional=false)) OpenJPA
will validate that the variable in your entity is not null <span class="emphasis"><em>before</em></span> inserting a row
in the database.
</p>
</div>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="369"><tr><td><img src="img/jpa-meta-model.png"></td></tr></table></div>
<p>
Through the course of this chapter, we will create the persistent object model
above.
</p>
<div class="section" id="jpa_overview_meta_class"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Class Metadata
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_meta_entity">1.1.
Entity
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_idclass">1.2.
Id Class
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddablesuper">1.3.
Mapped Superclass
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embeddable">1.4.
Embeddable
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_entity_listeners">1.5.
EntityListeners
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_classex">1.6.
Example
</a></span></dt></dl></div>
<p>
The following metadata annotations and XML elements apply to persistent class
declarations.
</p>
<div class="section" id="jpa_overview_meta_entity"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Entity
</h3></div></div></div>
<a class="indexterm" name="d5e1044"></a>
<a class="indexterm" name="d5e1047"></a>
<a class="indexterm" name="d5e1050"></a>
<p>
The <code class="classname">Entity</code> annotation denotes an entity class. All entity
classes must have this annotation. The <code class="classname">Entity</code> annotation
takes one optional property:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: Name used to refer to the entity in queries.
Must not be a reserved literal in JPQL. Defaults to the unqualified name of the
entity class.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">entity</code>. It has the following
attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">class</code>: The entity class. This attribute is required.
</p>
</li><li class="listitem">
<p>
<code class="literal">name</code>: Named used to refer to the class in queries. See the
name property above.
</p>
</li><li class="listitem">
<p>
<code class="literal">access</code>: The access type to use for the class. Must either be
<code class="literal">FIELD</code> or <code class="literal">PROPERTY</code>. For details on access
types, see <a class="xref" href="#jpa_overview_meta_field" title="2.&nbsp; Field and Property Metadata">Section&nbsp;2, &#8220;
Field and Property Metadata
&#8221;</a>.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA uses a process called <span class="emphasis"><em>enhancement</em></span> to modify the
bytecode of entities for transparent lazy loading and immediate dirty tracking.
See <a class="xref" href="#ref_guide_pc_enhance" title="2.&nbsp; Enhancement">Section&nbsp;2, &#8220;
Enhancement
&#8221;</a> in the Reference Guide for
details on enhancement.
</p>
</div>
</div>
<div class="section" id="jpa_overview_meta_idclass"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Id Class
</h3></div></div></div>
<a class="indexterm" name="d5e1081"></a>
<a class="indexterm" name="d5e1083"></a>
<a class="indexterm" name="d5e1086"></a>
<p>
As we discussed in <a class="xref" href="#jpa_overview_pc_identitycls" title="2.1.&nbsp; Identity Class">Section&nbsp;2.1, &#8220;
Identity Class
&#8221;</a>,
entities with multiple identity fields must use an <span class="emphasis"><em> identity class
</em></span> to encapsulate their persistent identity. The <code class="classname">IdClass
</code> annotation specifies this class. It accepts a single <code class="classname">
java.lang.Class</code> value.
</p>
<p>
The equivalent XML element is <code class="literal">id-class</code>, which has a single
attribute:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">class</code>: Set this required attribute to the name of the
identity class.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_meta_embeddablesuper"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Mapped Superclass
</h3></div></div></div>
<a class="indexterm" name="d5e1102"></a>
<a class="indexterm" name="d5e1104"></a>
<a class="indexterm" name="d5e1107"></a>
<p>
A <span class="emphasis"><em>mapped superclass</em></span> is a non-entity class that can define
persistent state and mapping information for entity subclasses. Mapped
superclasses are usually abstract. Unlike true entities, you cannot query a
mapped superclass, pass a mapped superclass instance to any <code class="classname">
EntityManager</code> or <code class="classname">Query</code> methods, or declare a
persistent relation with a mapped superclass target. You denote a mapped
superclass with the <code class="classname">MappedSuperclass</code> marker annotation.
</p>
<p>
The equivalent XML element is <code class="literal">mapped-superclass</code>. It expects
the following attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">class</code>: The entity class. This attribute is required.
</p>
</li><li class="listitem">
<p>
<code class="literal">access</code>: The access type to use for the class. Must either be
<code class="literal">FIELD</code> or <code class="literal">PROPERTY</code>. For details on access
types, see <a class="xref" href="#jpa_overview_meta_field" title="2.&nbsp; Field and Property Metadata">Section&nbsp;2, &#8220;
Field and Property Metadata
&#8221;</a>.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA allows you to query on mapped superclasses. A query on a mapped
superclass will return all matching subclass instances. OpenJPA also allows you
to declare relations to mapped superclass types; however, you cannot query
across these relations.
</p>
</div>
</div>
<div class="section" id="jpa_overview_meta_embeddable"><div class="titlepage"><div><div><h3 class="title">1.4.&nbsp;
Embeddable
</h3></div></div></div>
<a class="indexterm" name="d5e1131"></a>
<a class="indexterm" name="d5e1133"></a>
<a class="indexterm" name="d5e1136"></a>
<p>
The <code class="classname">Embeddable</code> annotation designates an embeddable
persistent class. Embeddable instances are stored as part of the record of their
owning instance. All embeddable classes must have this annotation.
</p>
<p>
A persistent class can either be an entity or an embeddable class, but not both.
</p>
<p>
The equivalent XML element is <code class="literal">embeddable</code>. It understands the
following attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">class</code>: The entity class. This attribute is required.
</p>
</li><li class="listitem">
<p>
<code class="literal">access</code>: The access type to use for the class. Must either be
<code class="literal">FIELD</code> or <code class="literal">PROPERTY</code>. For details on access
types, see <a class="xref" href="#jpa_overview_meta_field" title="2.&nbsp; Field and Property Metadata">Section&nbsp;2, &#8220;
Field and Property Metadata
&#8221;</a>.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA allows a persistent class to be both an entity and an embeddable class.
Instances of the class will act as entities when persisted explicitly or assigned
to non-embedded fields of entities. Instances will act as embedded values when
assigned to embedded fields of entities.
</p>
<p>
To signal that a class is both an entity and an embeddable class in OpenJPA,
simply add both the <code class="literal">@Entity</code> and the <code class="literal">@Embeddable
</code> annotations to the class.
</p>
</div>
</div>
<div class="section" id="jpa_overview_meta_entity_listeners"><div class="titlepage"><div><div><h3 class="title">1.5.&nbsp;
EntityListeners
</h3></div></div></div>
<a class="indexterm" name="d5e1161"></a>
<a class="indexterm" name="d5e1163"></a>
<a class="indexterm" name="d5e1165"></a>
<a class="indexterm" name="d5e1168"></a>
<p>
An entity may list its lifecycle event listeners in the <code class="classname">
EntityListeners</code> annotation. This value of this annotation is an
array of the listener <code class="classname">Class</code> es for the entity. The
equivalent XML element is <code class="literal">entity-listeners</code>. For more details
on entity listeners, see <a class="xref" href="#jpa_overview_pc_callbacks" title="3.&nbsp; Lifecycle Callbacks">Section&nbsp;3, &#8220;
Lifecycle Callbacks
&#8221;</a>.
</p>
</div>
<div class="section" id="jpa_overview_meta_classex"><div class="titlepage"><div><div><h3 class="title">1.6.&nbsp;
Example
</h3></div></div></div>
<p>
Here are the class declarations for our persistent object model, annotated with
the appropriate persistence metadata. Note that <code class="classname">Magazine</code>
declares an identity class, and that <code class="classname">Document</code> and
<code class="classname">Address</code> are a mapped superclass and an embeddable class,
respectively. <code class="classname">LifetimeSubscription</code> and <code class="classname">
TrialSubscription</code> override the default entity name to supply a
shorter alias for use in queries.
</p>
<div class="example" id="jpa_overview_meta_classlisting"><p class="title"><b>Example&nbsp;5.1.&nbsp;
Class Metadata
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
public class Magazine {
...
public static class MagazineId {
...
}
}
@Entity
public class Article {
...
}
package org.mag.pub;
@Entity
public class Company {
...
}
@Entity
public class Author {
...
}
@Embeddable
public class Address {
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
...
}
@Entity
public class Contract
extends Document {
...
}
@Entity
public class Subscription {
...
@Entity
public static class LineItem
extends Contract {
...
}
}
@Entity(name="Lifetime")
public class LifetimeSubscription
extends Subscription {
...
}
@Entity(name="Trial")
public class TrialSubscription
extends Subscription {
...
}
</pre>
<p>
The equivalent declarations in XML:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"&gt;
&lt;mapped-superclass class="org.mag.subscribe.Document"&gt;
...
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.Magazine"&gt;
&lt;id-class class="org.mag.Magazine$MagazineId"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Contract"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LineItem"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription" name="Lifetime"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.TrialSubscription" name="Trial"&gt;
...
&lt;/entity&gt;
&lt;embeddable class="org.mag.pub.Address"&gt;
...
&lt;/embeddable&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="jpa_overview_meta_field"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Field and Property Metadata
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_explicit_access">2.1.
Explicit Access
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_transient">2.2.
Transient
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_id">2.3.
Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_gen">2.4.
Generated Value
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_embedid">2.5.
Embedded Id
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_version">2.6.
Version
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_basic">2.7.
Basic
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_fetch">2.7.1.
Fetch Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_embedded">2.8.
Embedded
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytoone">2.9.
Many To One
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_cascade">2.9.1.
Cascade Type
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetomany">2.10.
One To Many
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_meta_mappedby">2.10.1.
Bidirectional Relations
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_meta_onetoone">2.11.
One To One
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_manytomany">2.12.
Many To Many
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_orderby">2.13.
Order By
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_mapkey">2.14.
Map Key
</a></span></dt><dt><span class="section"><a href="#jpa_overview_meta_fielddefaults">2.15.
Persistent Field Defaults
</a></span></dt></dl></div>
<p>
The persistence implementation must be able to retrieve and set the persistent
state of your entities, mapped superclasses, and embeddable types. JPA offers
two modes of persistent state access: <span class="emphasis"><em>field access</em></span>, and
<span class="emphasis"><em>property access</em></span>. The access type of a persistent attribute
can be either set explicitly on a class or attribute level, inherited, or
determined by the provider.
</p>
<p>
Under field access, the implementation injects state directly into your
persistent fields, and retrieves changed state from your fields as well. To
declare field access on an entire entity with XML metadata, set the
<code class="literal">access</code> attribute of your <code class="literal">entity</code> XML
element to <code class="literal">FIELD</code>. To use field access for an entire entity
using annotation metadata, simply place your metadata and mapping annotations
on your field declarations:
</p>
<pre class="programlisting">
@ManyToOne
private Company publisher;
</pre>
<p>
<a class="indexterm" name="d5e1200"></a>
<a class="indexterm" name="d5e1203"></a>
<a class="indexterm" name="d5e1206"></a>
Property access, on the other hand, retrieves and loads state through JavaBean
"getter" and "setter" methods. For a property <code class="literal">p</code> of type
<code class="literal">T</code>, you must define the following getter method:
</p>
<pre class="programlisting">
T getP();
</pre>
<p>
For boolean properties, this is also acceptable:
</p>
<pre class="programlisting">
boolean isP();
</pre>
<p>
You must also define the following setter method:
</p>
<pre class="programlisting">
void setP(T value);
</pre>
<p>
To implicitly use property access for an entire class by default, set your
<code class="literal">entity</code> element's <code class="literal"> access</code> attribute to
<code class="literal">PROPERTY</code>, or place your metadata and mapping annotations on
the getter method:
</p>
<pre class="programlisting">
@ManyToOne
private Company getPublisher() { ... }
private void setPublisher(Company publisher) { ... }
</pre>
<div class="section" id="jpa_overview_explicit_access"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
Explicit Access
</h3></div></div></div>
<p>
<a class="indexterm" name="d5e1224"></a>
<a class="indexterm" name="d5e1227"></a>
<a class="indexterm" name="d5e1230"></a>
The access type of a class or individual persistent attributes can be specified
explicitly using the <code class="literal">@Access</code> annotation or <code class="literal">access
</code> attribute on the XML elements used to define persistent attributes.
When explicitly defining access, specify the explicit access type for the class
and then apply the <code class="literal">@Access</code> annotation or <code class="literal">access
</code>XML attribute to individual fields or properties. If explicit
<code class="literal">FIELD</code> or <code class="literal">PROPERTY</code> is specified at the
class level, all eligible non-transient fields or properties will be persistent.
If using class level <code class="literal">FIELD</code> access, non-persistent fields must
be <code class="literal">transient</code> or annotated with <code class="literal">@Transient</code>.
If using class level <code class="literal">PROPERTY</code> access, non-persistent
properties must be annotated <code class="literal">@Transient</code> or excluded using
the <code class="literal">transient</code> XML attribute. Refer to the JPA specification
for specific rules regarding the use of explicit access with embeddables and
within an inheritance hierarchy.
</p>
<p>
This entity definitions shows how multiple access types may be specified
on an entity:
</p>
<pre class="programlisting">
@Entity
@Access(AccessType.FIELD)
public class PaymentContract {
@Id
private String id;
@Temporal(TemporalType.DATE)
private String contractDate;
@Transient
private String terms;
@Version
private int version;
@Lob
@Access(AccessType.PROPERTY)
public String getContractTerms() {
return terms;
}
public void setContractTerms(String terms) {
// Format string before persisting
this.terms = formatTerms(terms);
}
...
}
</pre>
<p>
The equivalent declarations in XML:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"&gt;
&lt;entity class="org.xyz.PaymentContract" access="FIELD"&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
&lt;basic name="contractTerms" access="PROPERTY"&gt;
&lt;lob/&gt;
&lt;/basic&gt;
&lt;basic name="contractDate"&gt;
&lt;temporal&gt;DATE&lt;/temporal&gt;
&lt;/basic&gt;
&lt;version name="version"/&gt;
&lt;transient name="terms"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;/entity-mappings&gt;
</pre>
</div>
<div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Warning</h3>
<p>
When using property access, only the getter and setter method for a property
should ever access the underlying persistent field directly. Other methods,
including internal business methods in the persistent class, should go through
the getter and setter methods when manipulating persistent state.
</p>
<p>
Also, take care when adding business logic to your getter and setter methods.
Consider that they are invoked by the persistence implementation to load and
retrieve all persistent state; other side effects might not be desirable.
</p>
</div>
<p>
The remainder of this document uses the term "persistent field" to refer to
either a persistent field or a persistent property.
</p>
<div class="section" id="jpa_overview_meta_transient"><div class="titlepage"><div><div><h3 class="title">2.2.&nbsp;
Transient
</h3></div></div></div>
<a class="indexterm" name="d5e1256"></a>
<a class="indexterm" name="d5e1258"></a>
<a class="indexterm" name="d5e1261"></a>
<p>
The <code class="classname">Transient</code> annotation specifies that a field is
non-persistent. Use it to exclude fields from management that would otherwise be
persistent. <code class="classname">Transient</code> is a marker annotation only; it
has no properties.
</p>
<p>
The equivalent XML element is <code class="literal">transient</code>. It has a single
attribute:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The transient field or property name. This attribute
is required.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_meta_id"><div class="titlepage"><div><div><h3 class="title">2.3.&nbsp;
Id
</h3></div></div></div>
<a class="indexterm" name="d5e1275"></a>
<a class="indexterm" name="d5e1277"></a>
<a class="indexterm" name="d5e1280"></a>
<p>
Annotate your simple identity fields with <code class="classname">Id</code>. This
annotation has no properties. We explore entity identity and identity fields in
<a class="xref" href="#jpa_overview_pc_id" title="1.3.&nbsp; Identity Fields">Section&nbsp;1.3, &#8220;
Identity Fields
&#8221;</a>.
</p>
<p>
The equivalent XML element is <code class="literal">id</code>. It has one required
attribute:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the identity field or property.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_meta_gen"><div class="titlepage"><div><div><h3 class="title">2.4.&nbsp;
Generated Value
</h3></div></div></div>
<a class="indexterm" name="d5e1294"></a>
<a class="indexterm" name="d5e1296"></a>
<a class="indexterm" name="d5e1299"></a>
<p>
The previous section showed you how to declare your identity fields with the
<code class="classname">Id</code> annotation. It is often convenient to allow the
persistence implementation to assign a unique value to your identity fields
automatically. JPA includes the <code class="classname">GeneratedValue</code>
annotation for this purpose. It has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">GenerationType strategy</code>: Enum value specifying how to
auto-generate the field value. The <code class="classname">GenerationType</code> enum
has the following values:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">GeneratorType.AUTO</code>: The default. Assign the field a
generated value, leaving the details to the JPA vendor.
</p>
</li><li class="listitem">
<p>
<code class="literal">GenerationType.IDENTITY</code>: The database will assign an
identity value on insert.
</p>
</li><li class="listitem">
<p>
<code class="literal">GenerationType.SEQUENCE</code>: Use a datastore sequence to
generate a field value.
</p>
</li><li class="listitem">
<p>
<code class="literal">GenerationType.TABLE</code>: Use a sequence table to generate a
field value.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<code class="literal">String generator</code>: The name of a generator defined in mapping
metadata. We show you how to define named generators in
<a class="xref" href="#jpa_overview_mapping_sequence" title="5.&nbsp; Generators">Section&nbsp;5, &#8220;
Generators
&#8221;</a>. If the <code class="classname">
GenerationType</code> is set but this property is unset, the JPA
implementation uses appropriate defaults for the selected generation type.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">generated-value</code>, which
includes the following attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">strategy</code>: One of <code class="literal"> TABLE</code>, <code class="literal">
SEQUENCE</code>, <code class="literal"> IDENTITY</code>, or <code class="literal">AUTO</code>,
defaulting to <code class="literal">AUTO</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">generator</code>: Equivalent to the generator property listed
above.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA allows you to use the <code class="classname">GeneratedValue</code> annotation
on any field, not just identity fields. Before using the <code class="literal">IDENTITY
</code> generation strategy, however, read
<a class="xref" href="#ref_guide_pc_oid_pkgen_autoinc" title="4.4.&nbsp; Autoassign / Identity Strategy Caveats">Section&nbsp;4.4, &#8220;
Autoassign / Identity Strategy Caveats
&#8221;</a> in the Reference Guide.
</p>
<p>
OpenJPA also offers additional generator strategies for non-numeric fields,
which you can access by setting <code class="literal">strategy</code> to <code class="literal">AUTO
</code> (the default), and setting the <code class="literal">generator</code> string
to:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e1354"></a>
<a class="indexterm" name="d5e1357"></a>
<code class="literal">uuid-string</code>: OpenJPA will generate a 128-bit type 1 UUID
unique within the network, represented as a 16-character string. For more
information on UUIDs, see the IETF UUID draft specification at:
<a class="ulink" href="http://www.ics.uci.edu/~ejw/authoring/uuid-guid/" target="_top">
http://www.ics.uci.edu/~ejw/authoring/uuid-guid/</a>
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e1363"></a>
<a class="indexterm" name="d5e1366"></a>
<code class="literal">uuid-hex</code>: Same as <code class="literal"> uuid-string</code>, but
represents the type 1 UUID as a 32-character hexadecimal string.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e1372"></a>
<a class="indexterm" name="d5e1375"></a>
<code class="literal">uuid-type4-string</code>: OpenJPA will generate a 128-bit type 4
pseudo-random UUID, represented as a 16-character string. For more
information on UUIDs, see the IETF UUID draft specification at:
<a class="ulink" href="http://www.ics.uci.edu/~ejw/authoring/uuid-guid/" target="_top">
http://www.ics.uci.edu/~ejw/authoring/uuid-guid/</a>
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e1381"></a>
<a class="indexterm" name="d5e1384"></a>
<code class="literal">uuid-type4-hex</code>: Same as <code class="literal"> uuid-type4-string</code>
, but represents the type 4 UUID as a 32-character hexadecimal string.
</p>
</li></ul></div>
<p>
These string constants are defined in
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Generator.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.Generator</code></a>.
</p>
<p>
If the entities are mapped to the same table name but with different schema
name within one <code class="literal">PersistenceUnit</code> intentionally, and the
strategy of <code class="literal">GeneratedType.AUTO</code> is used to generate the ID
for each entity, a schema name for each entity must be explicitly declared
either through the annotation or the mapping.xml file. Otherwise, the mapping
tool only creates the tables for those entities with the schema names under
each schema. In addition, there will be only one
<code class="literal">OPENJPA_SEQUENCE_TABLE</code> created for all the entities within
the <code class="literal">PersistenceUnit</code> if the entities are not identified
with the schema name. Read <a class="xref" href="#ref_guide_sequence" title="6.&nbsp; Generators">Section&nbsp;6, &#8220;
Generators
&#8221;</a> and
<a class="xref" href="#ref_guide_schema_def" title="11.&nbsp; Default Schema">Section&nbsp;11, &#8220;
Default Schema
&#8221;</a> in the Reference Guide.
</p>
</div>
</div>
<div class="section" id="jpa_overview_meta_embedid"><div class="titlepage"><div><div><h3 class="title">2.5.&nbsp;
Embedded Id
</h3></div></div></div>
<a class="indexterm" name="d5e1400"></a>
<a class="indexterm" name="d5e1402"></a>
<a class="indexterm" name="d5e1405"></a>
<p>
If your entity has multiple identity values, you may declare multiple <code class="literal">
@Id</code> fields, or you may declare a single <code class="literal">@EmbeddedId</code>
field. The type of a field annotated with <code class="classname">EmbeddedId</code> must
be an embeddable entity class. The fields of this embeddable class are
considered the identity values of the owning entity. We explore entity identity
and identity fields in <a class="xref" href="#jpa_overview_pc_id" title="1.3.&nbsp; Identity Fields">Section&nbsp;1.3, &#8220;
Identity Fields
&#8221;</a>.
</p>
<p>
The <code class="classname">EmbeddedId</code> annotation has no properties.
</p>
<p>
The equivalent XML element is <code class="literal">embedded-id</code>. It has one
required attribute:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the identity field or property.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_meta_version"><div class="titlepage"><div><div><h3 class="title">2.6.&nbsp;
Version
</h3></div></div></div>
<a class="indexterm" name="d5e1423"></a>
<a class="indexterm" name="d5e1425"></a>
<a class="indexterm" name="d5e1428"></a>
<p>
Use the <code class="classname">Version</code> annotation to designate a version field.
<a class="xref" href="#jpa_overview_pc_version" title="1.4.&nbsp; Version Field">Section&nbsp;1.4, &#8220;
Version Field
&#8221;</a> explained the importance of
version fields to JPA. This is a marker annotation; it has no properties.
</p>
<p>
The equivalent XML element is <code class="literal">version</code>, which has a single
attribute:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the version field or property. This
attribute is required.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_meta_basic"><div class="titlepage"><div><div><h3 class="title">2.7.&nbsp;
Basic
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_meta_fetch">2.7.1.
Fetch Type
</a></span></dt></dl></div>
<a class="indexterm" name="d5e1442"></a>
<a class="indexterm" name="d5e1444"></a>
<a class="indexterm" name="d5e1447"></a>
<p>
<code class="classname">Basic</code> signifies a standard value persisted as-is to the
datastore. You can use the <code class="classname">Basic</code> annotation on persistent
fields of the following types: primitives, primitive wrappers, <code class="classname">
java.lang.String</code>, <code class="classname">byte[]</code>, <code class="classname">
Byte[]</code>, <code class="classname">char[]</code>, <code class="classname">
Character[]</code>, <code class="classname">java.math.BigDecimal</code>,
<code class="classname">java.math.BigInteger</code>, <code class="classname">
java.util.Date</code>, <code class="classname">java.util.Calendar</code>,
<code class="classname">java.sql.Date</code>, <code class="classname">java.sql.Timestamp</code>,
<code class="classname">Enum</code>s, and <code class="classname">Serializable</code> types.
</p>
<p>
<code class="classname">Basic</code> declares these properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the field eagerly
(<code class="literal">FetchType.EAGER</code>) or lazily (<code class="literal">
FetchType.LAZY</code>). Defaults to <code class="literal">FetchType.EAGER</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean optional</code>: Whether the datastore allows null values.
Defaults to true.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">basic</code>. It has the following
attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the field or property. This attribute is
required.
</p>
</li><li class="listitem">
<p>
<code class="literal">fetch</code>: One of <code class="literal">EAGER</code> or <code class="literal">LAZY
</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">optional</code>: Boolean indicating whether the field value may be
null.
</p>
</li></ul></div>
<div class="section" id="jpa_overview_meta_fetch"><div class="titlepage"><div><div><h4 class="title">2.7.1.&nbsp;
Fetch Type
</h4></div></div></div>
<a class="indexterm" name="d5e1494"></a>
<a class="indexterm" name="d5e1497"></a>
<a class="indexterm" name="d5e1500"></a>
<p>
Many metadata annotations in JPA have a <code class="literal">fetch</code> property. This
property can take on one of two values: <code class="literal">FetchType.EAGER</code> or
<code class="literal">FetchType.LAZY</code>. <code class="literal">FetchType.EAGER</code> means that
the field is loaded by the JPA implementation before it returns the persistent
object to you. Whenever you retrieve an entity from a query or from the
<code class="classname">EntityManager</code>, you are guaranteed that all of its eager
fields are populated with datastore data.
</p>
<p>
<code class="literal">FetchType.LAZY</code> is a hint to the JPA runtime that you want to
defer loading of the field until you access it. This is called <span class="emphasis"><em>lazy
loading</em></span>. Lazy loading is completely transparent; when you attempt to
read the field for the first time, the JPA runtime will load the value from the
datastore and populate the field automatically. Lazy loading is only a hint and
not a directive because some JPA implementations cannot lazy-load certain field
types.
</p>
<p>
With a mix of eager and lazily-loaded fields, you can ensure that commonly-used
fields load efficiently, and that other state loads transparently when accessed.
As you will see in <a class="xref" href="#jpa_overview_emfactory_perscontext" title="3.&nbsp; Persistence Context">Section&nbsp;3, &#8220;
Persistence Context
&#8221;</a>,
you can also use eager fetching to ensure that entities have all needed data
loaded before they become <span class="emphasis"><em>detached</em></span> at the end of a
persistence context.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA can lazy-load any field type. OpenJPA also allows you to dynamically
change which fields are eagerly or lazily loaded at runtime. See
<a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a> in the Reference Guide for details.
</p>
<p>
The Reference Guide details OpenJPA's eager fetching behavior in
<a class="xref" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">Section&nbsp;8, &#8220;
Eager Fetching
&#8221;</a>.
</p>
</div>
</div>
</div>
<div class="section" id="jpa_overview_meta_embedded"><div class="titlepage"><div><div><h3 class="title">2.8.&nbsp;
Embedded
</h3></div></div></div>
<a class="indexterm" name="d5e1522"></a>
<a class="indexterm" name="d5e1524"></a>
<a class="indexterm" name="d5e1527"></a>
<p>
Use the <code class="classname">Embedded</code> marker annotation on embeddable field
types. Embedded fields are mapped as part of the datastore record of the
declaring entity. In our sample model, <code class="classname">Author</code> and
<code class="classname">Company</code> each embed their <code class="classname">Address</code>,
rather than forming a relation to an <code class="classname">Address</code> as a
separate entity.
</p>
<p>
The equivalent XML element is <code class="literal">embedded</code>, which expects a
single attribute:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the field or property. This attribute is
required.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_meta_manytoone"><div class="titlepage"><div><div><h3 class="title">2.9.&nbsp;
Many To One
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_meta_cascade">2.9.1.
Cascade Type
</a></span></dt></dl></div>
<a class="indexterm" name="d5e1544"></a>
<a class="indexterm" name="d5e1546"></a>
<a class="indexterm" name="d5e1549"></a>
<p>
When an entity <code class="literal">A</code> references a single entity <code class="literal">
B</code>, and other <code class="literal">A</code>s might also reference the same
<code class="literal">B</code>, we say there is a <span class="emphasis"><em>many to one</em></span>
relation from <code class="literal">A</code> to <code class="literal">B</code>. In our sample
model, for example, each magazine has a reference to its publisher. Multiple
magazines might have the same publisher. We say, then, that the <code class="literal">
Magazine.publisher</code> field is a many to one relation from magazines to
publishers.
</p>
<p>
JPA indicates many to one relations between entities with the <code class="classname">
ManyToOne</code> annotation. This annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Class targetEntity</code>: The class of the related entity type.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] cascade</code>: Array of enum values defining cascade
behavior for this field. We explore cascades below. Defaults to an empty array.
</p>
</li><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the field eagerly
(<code class="literal">FetchType.EAGER</code>) or lazily
(<code class="literal">FetchType.LAZY</code>). Defaults to <code class="literal">
FetchType.EAGER</code>. See <a class="xref" href="#jpa_overview_meta_fetch" title="2.7.1.&nbsp; Fetch Type">Section&nbsp;2.7.1, &#8220;
Fetch Type
&#8221;</a> above
for details on fetch types.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean optional</code>: Whether the related object must exist. If
<code class="literal">false</code>, this field cannot be null. Defaults to <code class="literal">
true</code>.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">many-to-one</code>. It accepts the
following attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the field or property. This attribute is
required.
</p>
</li><li class="listitem">
<p>
<code class="literal">target-entity</code>: The class of the related type.
</p>
</li><li class="listitem">
<p>
<code class="literal">fetch</code>: One of <code class="literal">EAGER</code> or <code class="literal">
LAZY</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">optional</code>: Boolean indicating whether the field value may be
null.
</p>
</li></ul></div>
<div class="section" id="jpa_overview_meta_cascade"><div class="titlepage"><div><div><h4 class="title">2.9.1.&nbsp;
Cascade Type
</h4></div></div></div>
<a class="indexterm" name="d5e1601"></a>
<a class="indexterm" name="d5e1603"></a>
<p>
We introduce the JPA <code class="classname">EntityManager</code> in
<a class="xref" href="#jpa_overview_em" title="Chapter&nbsp;8.&nbsp; EntityManager">Chapter&nbsp;8, <i>
EntityManager
</i></a>. The <code class="classname">EntityManager
</code> has APIs to persist new entities, remove (delete) existing
entities, refresh entity state from the datastore, and merge <span class="emphasis"><em>detached
</em></span> entity state back into the persistence context. We explore all of
these APIs in detail later in the overview.
</p>
<p>
When the <code class="classname">EntityManager</code> is performing the above
operations, you can instruct it to automatically cascade the operation to the
entities held in a persistent field with the <code class="literal">cascade</code> property
of your metadata annotation. This process is recursive. The <code class="literal">cascade
</code> property accepts an array of <code class="classname">CascadeType</code> enum
values.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">CascadeType.PERSIST</code>: When persisting an entity, also persist
the entities held in this field. We suggest liberal application of this cascade
rule, because if the <code class="classname">EntityManager</code> finds a field that
references a new entity during flush, and the field does not use <code class="literal">
CascadeType.PERSIST</code>, it is an error.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType.REMOVE</code>: When deleting an entity, also delete the
entities held in this field.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType.REFRESH</code>: When refreshing an entity, also refresh
the entities held in this field.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType.MERGE</code>: When merging entity state, also merge the
entities held in this field.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA offers enhancements to JPA's CascadeType.REMOVE functionality,
including additional annotations to control how and when dependent fields will
be removed. See <a class="xref" href="#dependent" title="4.2.1.&nbsp; Dependent">Section&nbsp;4.2.1, &#8220;
Dependent
&#8221;</a> for more details.
</p>
</div>
<p>
<code class="classname">CascadeType</code> defines one additional value, <code class="literal">
CascadeType.ALL</code>, that acts as a shortcut for all of the values above.
The following annotations are equivalent:
</p>
<pre class="programlisting">
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE,
CascadeType.REFRESH,CascadeType.MERGE})
private Company publisher;
</pre>
<pre class="programlisting">
@ManyToOne(cascade=CascadeType.ALL)
private Company publisher;
</pre>
<p>
In XML, these enumeration constants are available as child elements of the
<code class="literal">cascade</code> element. The <code class="literal">cascade</code> element is
itself a child of <code class="literal">many-to-one</code>. The following examples are
equivalent:
</p>
<pre class="programlisting">
&lt;many-to-one name="publisher"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-merge/&gt;
&lt;cascade-remove/&gt;
&lt;cascade-refresh/&gt;
&lt;/cascade&gt;
&lt;/many-to-one&gt;
</pre>
<pre class="programlisting">
&lt;many-to-one name="publisher"&gt;
&lt;cascade&gt;
&lt;cascade-all/&gt;
&lt;/cascade&gt;
&lt;/many-to-one&gt;
</pre>
</div>
</div>
<div class="section" id="jpa_overview_meta_onetomany"><div class="titlepage"><div><div><h3 class="title">2.10.&nbsp;
One To Many
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_meta_mappedby">2.10.1.
Bidirectional Relations
</a></span></dt></dl></div>
<a class="indexterm" name="d5e1647"></a>
<a class="indexterm" name="d5e1649"></a>
<a class="indexterm" name="d5e1652"></a>
<p>
When an entity <code class="literal">A</code> references multiple <code class="literal">B</code>
entities, and no two <code class="literal">A</code>s reference the same <code class="literal">
B</code>, we say there is a <span class="emphasis"><em>one to many</em></span> relation from
<code class="literal">A</code> to <code class="literal">B</code>.
</p>
<p>
One to many relations are the exact inverse of the many to one relations we
detailed in the preceding section. In that section, we said that the <code class="literal">
Magazine.publisher</code> field is a many to one relation from magazines to
publishers. Now, we see that the <code class="literal">Company.mags</code> field is the
inverse - a one to many relation from publishers to magazines. Each company may
publish multiple magazines, but each magazine can have only one publisher.
</p>
<p>
JPA indicates one to many relations between entities with the <code class="classname">
OneToMany</code> annotation. This annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Class targetEntity</code>: The class of the related entity type.
This information is usually taken from the parameterized collection or map
element type. You must supply it explicitly, however, if your field isn't a
parameterized type.
</p>
</li><li class="listitem">
<p>
<code class="literal">String mappedBy</code>: Names the many to one field in the related
entity that maps this bidirectional relation. We explain bidirectional relations
below. Leaving this property unset signals that this is a standard
unidirectional relation.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] cascade</code>: Array of enum values defining cascade
behavior for the collection elements. We explore cascades above in
<a class="xref" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">Section&nbsp;2.9.1, &#8220;
Cascade Type
&#8221;</a>. Defaults to an empty array.
</p>
</li><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the field eagerly
(<code class="literal">FetchType.EAGER</code>) or lazily
(<code class="literal">FetchType.LAZY</code>). Defaults to <code class="literal">
FetchType.LAZY</code>. See <a class="xref" href="#jpa_overview_meta_fetch" title="2.7.1.&nbsp; Fetch Type">Section&nbsp;2.7.1, &#8220;
Fetch Type
&#8221;</a> above
for details on fetch types.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">one-to-many</code>, which includes
the following attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the field or property. This attribute is
required.
</p>
</li><li class="listitem">
<p>
<code class="literal">target-entity</code>: The class of the related type.
</p>
</li><li class="listitem">
<p>
<code class="literal">fetch</code>: One of <code class="literal">EAGER</code> or <code class="literal">
LAZY</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">mapped-by</code>: The name of the field or property that owns the
relation. See <a class="xref" href="#jpa_overview_meta_field" title="2.&nbsp; Field and Property Metadata">Section&nbsp;2, &#8220;
Field and Property Metadata
&#8221;</a>.
</p>
</li></ul></div>
<p>
You may also nest the <code class="literal">cascade</code> element within a <code class="literal">
one-to-many</code> element.
</p>
<div class="section" id="jpa_overview_meta_mappedby"><div class="titlepage"><div><div><h4 class="title">2.10.1.&nbsp;
Bidirectional Relations
</h4></div></div></div>
<a class="indexterm" name="d5e1709"></a>
<a class="indexterm" name="d5e1711"></a>
<a class="indexterm" name="d5e1714"></a>
<p>
When two fields are logical inverses of each other, they form a <span class="emphasis"><em>
bidirectional relation</em></span>. Our model contains two bidirectional
relations: <code class="literal">Magazine.publisher</code> and <code class="literal">Company.mags
</code> form one bidirectional relation, and <code class="literal">Article.authors
</code> and <code class="literal">Author.articles</code> form the other. In both cases,
there is a clear link between the two fields that form the relationship. A
magazine refers to its publisher while the publisher refers to all its published
magazines. An article refers to its authors while each author refers to her
written articles.
</p>
<p>
When the two fields of a bidirectional relation share the same datastore
mapping, JPA formalizes the connection with the <code class="literal">mappedBy</code>
property. Marking <code class="literal">Company.mags</code> as <code class="literal">mappedBy</code>
<code class="literal">Magazine.publisher</code> means two things:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
<code class="literal">Company.mags</code> uses the datastore mapping for <code class="literal">
Magazine.publisher</code>, but inverses it. In fact, it is illegal to
specify any additional mapping information when you use the <code class="literal">mappedBy
</code> property. All mapping information is read from the referenced field.
We explore mapping in depth in <a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">Magazine.publisher</code> is the "owner" of the relation. The field
that specifies the mapping data is always the owner. This means that changes to
the <code class="literal">Magazine.publisher</code> field are reflected in the datastore,
while changes to the <code class="literal">Company.mags</code> field alone are not.
Changes to <code class="literal">Company.mags</code> may still affect the JPA
implementation's cache, however. Thus, it is very important that you keep your
object model consistent by properly maintaining both sides of your bidirectional
relations at all times.
</p>
</li></ol></div>
<p>
You should always take advantage of the <code class="literal">mappedBy</code> property
rather than mapping each field of a bidirectional relation independently.
Failing to do so may result in the JPA implementation trying to update the
database with conflicting data. Be careful to only mark one side of the relation
as <code class="literal">mappedBy</code>, however. One side has to actually do the
mapping!
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
You can configure OpenJPA to automatically synchronize both sides of a
bidirectional relation, or to perform various actions when it detects
inconsistent relations. See <a class="xref" href="#ref_guide_inverses" title="5.&nbsp; Managed Inverses">Section&nbsp;5, &#8220;
Managed Inverses
&#8221;</a> in the
Reference Guide for details.
</p>
</div>
</div>
</div>
<div class="section" id="jpa_overview_meta_onetoone"><div class="titlepage"><div><div><h3 class="title">2.11.&nbsp;
One To One
</h3></div></div></div>
<a class="indexterm" name="d5e1749"></a>
<a class="indexterm" name="d5e1751"></a>
<a class="indexterm" name="d5e1754"></a>
<p>
When an entity <code class="literal">A</code> references a single entity <code class="literal">
B</code>, and no other <code class="literal">A</code>s can reference the same <code class="literal">
B</code>, we say there is a <span class="emphasis"><em>one to one</em></span> relation between
<code class="literal">A</code> and <code class="literal">B</code>. In our sample model, <code class="classname">
Magazine</code> has a one to one relation to <code class="classname">Article</code>
through the <code class="literal">Magazine.coverArticle</code> field. No two magazines can
have the same cover article.
</p>
<p>
JPA indicates one to one relations between entities with the <code class="classname">
OneToOne</code> annotation. This annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Class targetEntity</code>: The class of the related entity type.
This information is usually taken from the field type.
</p>
</li><li class="listitem">
<p>
<code class="literal">String mappedBy</code>: Names the field in the related entity that
maps this bidirectional relation. We explain bidirectional relations in
<a class="xref" href="#jpa_overview_meta_mappedby" title="2.10.1.&nbsp; Bidirectional Relations">Section&nbsp;2.10.1, &#8220;
Bidirectional Relations
&#8221;</a> above. Leaving this property
unset signals that this is a standard unidirectional relation.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] cascade</code>: Array of enum values defining cascade
behavior for this field. We explore cascades in
<a class="xref" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">Section&nbsp;2.9.1, &#8220;
Cascade Type
&#8221;</a> above. Defaults to an empty
array.
</p>
</li><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the field eagerly
(<code class="literal">FetchType.EAGER</code>) or lazily
(<code class="literal">FetchType.LAZY</code>). Defaults to <code class="literal">
FetchType.EAGER</code>. See <a class="xref" href="#jpa_overview_meta_fetch" title="2.7.1.&nbsp; Fetch Type">Section&nbsp;2.7.1, &#8220;
Fetch Type
&#8221;</a> above
for details on fetch types.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean optional</code>: Whether the related object must exist. If
<code class="literal">false</code>, this field cannot be null. Defaults to <code class="literal">
true</code>.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">one-to-one</code> which understands
the following attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the field or property. This attribute is
required.
</p>
</li><li class="listitem">
<p>
<code class="literal">target-entity</code>: The class of the related type.
</p>
</li><li class="listitem">
<p>
<code class="literal">fetch</code>: One of <code class="literal">EAGER</code> or <code class="literal">
LAZY</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">mapped-by</code>: The field that owns the relation. See
<a class="xref" href="#jpa_overview_meta_field" title="2.&nbsp; Field and Property Metadata">Section&nbsp;2, &#8220;
Field and Property Metadata
&#8221;</a>.
</p>
</li></ul></div>
<p>
You may also nest the <code class="literal">cascade</code> element within a <code class="literal">
one-to-one</code> element.
</p>
</div>
<div class="section" id="jpa_overview_meta_manytomany"><div class="titlepage"><div><div><h3 class="title">2.12.&nbsp;
Many To Many
</h3></div></div></div>
<a class="indexterm" name="d5e1817"></a>
<a class="indexterm" name="d5e1819"></a>
<a class="indexterm" name="d5e1822"></a>
<p>
When an entity <code class="literal">A</code> references multiple <code class="literal">B</code>
entities, and other <code class="literal">A</code>s might reference some of the same
<code class="literal">B</code>s, we say there is a <span class="emphasis"><em>many to many</em></span>
relation between <code class="literal">A</code> and <code class="literal">B</code>. In our sample
model, for example, each article has a reference to all the authors that
contributed to the article. Other articles might have some of the same authors.
We say, then, that <code class="classname">Article</code> and <code class="classname">Author
</code> have a many to many relation through the <code class="literal">Article.authors
</code> field.
</p>
<p>
JPA indicates many to many relations between entities with the <code class="classname">
ManyToMany</code> annotation. This annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Class targetEntity</code>: The class of the related entity type.
This information is usually taken from the parameterized collection or map
element type. You must supply it explicitly, however, if your field isn't a
parameterized type.
</p>
</li><li class="listitem">
<p>
<code class="literal">String mappedBy</code>: Names the many to many field in the related
entity that maps this bidirectional relation. We explain bidirectional relations
in <a class="xref" href="#jpa_overview_meta_mappedby" title="2.10.1.&nbsp; Bidirectional Relations">Section&nbsp;2.10.1, &#8220;
Bidirectional Relations
&#8221;</a> above. Leaving this
property unset signals that this is a standard unidirectional relation.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] cascade</code>: Array of enum values defining cascade
behavior for the collection elements. We explore cascades above in
<a class="xref" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">Section&nbsp;2.9.1, &#8220;
Cascade Type
&#8221;</a>. Defaults to an empty array.
</p>
</li><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the field eagerly
(<code class="literal">FetchType.EAGER</code>) or lazily
(<code class="literal">FetchType.LAZY</code>). Defaults to <code class="literal">
FetchType.LAZY</code>. See <a class="xref" href="#jpa_overview_meta_fetch" title="2.7.1.&nbsp; Fetch Type">Section&nbsp;2.7.1, &#8220;
Fetch Type
&#8221;</a> above
for details on fetch types.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">many-to-many</code>. It accepts the
following attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the field or property. This attribute is
required.
</p>
</li><li class="listitem">
<p>
<code class="literal">target-entity</code>: The class of the related type.
</p>
</li><li class="listitem">
<p>
<code class="literal">fetch</code>: One of <code class="literal">EAGER</code> or <code class="literal">
LAZY</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">mapped-by</code>: The field that owns the relation. See
<a class="xref" href="#jpa_overview_meta_field" title="2.&nbsp; Field and Property Metadata">Section&nbsp;2, &#8220;
Field and Property Metadata
&#8221;</a>.
</p>
</li></ul></div>
<p>
You may also nest the <code class="literal">cascade</code> element within a <code class="literal">
many-to-many</code> element.
</p>
</div>
<div class="section" id="jpa_overview_meta_orderby"><div class="titlepage"><div><div><h3 class="title">2.13.&nbsp;
Order By
</h3></div></div></div>
<a class="indexterm" name="d5e1880"></a>
<a class="indexterm" name="d5e1882"></a>
<a class="indexterm" name="d5e1885"></a>
<p>
Datastores such as relational databases do not preserve the order of records.
Your persistent <code class="classname">List</code> fields might be ordered one way the
first time you retrieve an object from the datastore, and a completely different
way the next. To ensure consistent ordering of collection fields, you must use
the <code class="classname">OrderBy</code> annotation. The <code class="classname">OrderBy
</code> annotation's value is a string defining the order of the collection
elements. An empty value means to sort on the identity value(s) of the elements
in ascending order. Any other value must be of the form:
</p>
<pre class="programlisting">
&lt;field name&gt;[ ASC|DESC][, ...]
</pre>
<p>
Each <code class="literal">&lt;field name&gt;</code> is the name of a persistent field in
the collection's element type. You can optionally follow each field by the
keyword <code class="literal">ASC</code> for ascending order, or <code class="literal">DESC</code>
for descending order. If the direction is omitted, it defaults to ascending.
</p>
<p>
The equivalent XML element is <code class="literal">order-by</code> which can be listed as
a sub-element of the <code class="literal">one-to-many</code> or <code class="literal">many-to-many
</code> elements. The text within this element is parsed as the order by
string.
</p>
</div>
<div class="section" id="jpa_overview_meta_mapkey"><div class="titlepage"><div><div><h3 class="title">2.14.&nbsp;
Map Key
</h3></div></div></div>
<a class="indexterm" name="d5e1903"></a>
<a class="indexterm" name="d5e1905"></a>
<a class="indexterm" name="d5e1908"></a>
<p>
JPA supports persistent <code class="classname">Map</code> fields through either a
<a class="link" href="#jpa_overview_meta_onetomany" title="2.10.&nbsp; One To Many"><code class="classname"> OneToMany</code>
</a> or <a class="link" href="#jpa_overview_meta_manytomany" title="2.12.&nbsp; Many To Many"><code class="classname">ManyToMany
</code></a> association. The related entities form the map values. JPA
derives the map keys by extracting a field from each entity value. The
<code class="classname">MapKey</code> annotation designates the field that is used as
the key. It has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of a field in the related entity class
to use as the map key. If no name is given, defaults to the identity field of
the related entity class.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">map-key</code> which can be listed as
a sub-element of the <code class="literal">one-to-many</code> or <code class="literal">many-to-many
</code> elements. The <code class="literal">map-key</code> element has the following
attributes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: The name of the field in the related entity class to
use as the map key.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_meta_fielddefaults"><div class="titlepage"><div><div><h3 class="title">2.15.&nbsp;
Persistent Field Defaults
</h3></div></div></div>
<p>
In the absence of any of the annotations above, JPA defines the following
default behavior for declared fields:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
Fields declared <code class="literal">static, transient</code>, or <code class="literal">final
</code> default to non-persistent.
</p>
</li><li class="listitem">
<p>
Fields of any primitive type, primitive wrapper type, <code class="classname">
java.lang.String</code>, <code class="classname">byte[]</code>, <code class="classname">
Byte[]</code>, <code class="classname">char[]</code>, <code class="classname">
Character[]</code>, <code class="classname">java.math.BigDecimal</code>,
<code class="classname">java.math.BigInteger</code>, <code class="classname">
java.util.Date</code>, <code class="classname"> java.util.Calendar</code>,
<code class="classname">java.sql.Date</code>, <code class="classname">java.sql.Timestamp</code>,
or any <code class="classname">Serializable</code> type default to persistent, as if
annotated with <a class="link" href="#jpa_overview_meta_basic" title="2.7.&nbsp; Basic"><code class="literal">
@Basic</code></a>.
</p>
</li><li class="listitem">
<p>
Fields of an embeddable type default to persistent, as if annotated with
<a class="link" href="#jpa_overview_meta_embedded" title="2.8.&nbsp; Embedded"><code class="literal">@Embedded</code></a>.
</p>
</li><li class="listitem">
<p>
All other fields default to non-persistent.
</p>
</li></ol></div>
<p>
Note that according to these defaults, all relations between entities must be
annotated explicitly. Without an annotation, a relation field will default to
serialized storage if the related entity type is serializable, or will default
to being non-persistent if not.
</p>
</div>
</div>
<div class="section" id="jpa_overview_meta_xml"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
XML Schema
</h2></div></div></div>
<a class="indexterm" name="d5e1964"></a>
<a class="indexterm" name="d5e1967"></a>
<p>
The latest revision of the version 2.0 orm schema is presented below. Version
2.0 of the schema must be used if JPA 2.0 elements are specified as XML
metadata. Many of the elements in the schema relate to object/relational
mapping rather than metadata; these elements are discussed in
<a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a>. Version 1.0 of the orm schema can be
found at <a class="ulink" href="http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" target="_top">http://java.sun.com/xml/ns/persistence/orm_1_0.xsd</a>.
</p>
<pre class="programlisting">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!-- Java Persistence API object/relational mapping file schema --&gt;
&lt;xsd:schema targetNamespace="http://java.sun.com/xml/ns/persistence/orm"
xmlns:orm="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified"
version="2.0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@(#)orm_2_0.xsd 2.0 October 1 2009
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2005-2009 Sun Microsystems, Inc. All rights reserved.
The contents of this file are subject to the terms of either the
GNU General Public License Version 2 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with
the License. You can obtain a copy of the License at
https://glassfish.dev.java.net/public/CDDL+GPL.html or
glassfish/bootstrap/legal/LICENSE.txt. See the License for the
specific language governing permissions and limitations under the
License.
When distributing the software, include this License Header
Notice in each file and include the License file at
glassfish/bootstrap/legal/LICENSE.txt. Sun designates this
particular file as subject to the "Classpath" exception as
provided by Sun in the GPL Version 2 section of the License file
that accompanied this code. If applicable, add the following
below the License Header, with the fields enclosed by brackets []
replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
Contributor(s):
If you wish your version of this file to be governed by only the
CDDL or only the GPL Version 2, indicate your decision by adding
"[Contributor] elects to include this software in this
distribution under the [CDDL or GPL Version 2] license." If you
don't indicate a single choice of license, a recipient has the
option to distribute your version of this file under either the
CDDL, the GPL Version 2 or to extend the choice of license to its
licensees as provided above. However, if you add GPL Version 2
code and therefore, elected the GPL Version 2 license, then the
option applies only if the new code is made subject to such
option by the copyright holder.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
&lt;![CDATA[
This is the XML Schema for the persistence object/relational
mapping file.
The file may be named "META-INF/orm.xml" in the persistence
archive or it may be named some other name which would be
used to locate the file as resource on the classpath.
Object/relational mapping files must indicate the object/relational
mapping file schema by using the persistence namespace:
http://java.sun.com/xml/ns/persistence
and indicate the version of the schema by
using the version element as shown below:
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm/orm_2_0.xsd"
version="2.0"&gt;
...
&lt;/entity-mappings&gt;
]]&gt;
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:complexType name="emptyType" /&gt;
&lt;xsd:simpleType name="versionType"&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:pattern value="[0-9]+(\.[0-9]+)*" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="entity-mappings"&gt;
&lt;xsd:complexType&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
The entity-mappings element is the root element of a mapping
file. It contains the following four types of elements:
1. The persistence-unit-metadata element contains metadata
for the entire persistence unit. It is undefined if this element
occurs in multiple mapping files within the same
persistence unit.
2. The package, schema, catalog and access elements apply to all of
the entity, mapped-superclass and embeddable
elements defined in
the same file in which they occur.
3. The sequence-generator, table-generator, named-query,
named-native-query and sql-result-set-mapping
elements are global
to the persistence unit. It is undefined to have more than one
sequence-generator or table-generator of the same
name in the same
or different mapping files in a persistence unit. It is also
undefined to have more than one named-query,
named-native-query, or
result-set-mapping of the same name in the same or different mapping
files in a persistence unit.
4. The entity, mapped-superclass and embeddable elements each define
the mapping information for a managed persistent
class. The mapping
information contained in these elements may be complete or it may
be partial.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="persistence-unit-metadata"
type="orm:persistence-unit-metadata" minOccurs="0" /&gt;
&lt;xsd:element name="package" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="schema" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="catalog" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="access" type="orm:access-type"
minOccurs="0" /&gt;
&lt;xsd:element name="sequence-generator" type="orm:sequence-generator"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="table-generator" type="orm:table-generator"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="named-query" type="orm:named-query"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="named-native-query" type="orm:named-native-query"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="sql-result-set-mapping"
type="orm:sql-result-set-mapping" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;xsd:element name="mapped-superclass" type="orm:mapped-superclass"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="entity" type="orm:entity"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="embeddable" type="orm:embeddable"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="version" type="orm:versionType"
fixed="2.0" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="persistence-unit-metadata"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Metadata that applies to the persistence unit and not just to
the mapping file in which it is contained.
If the xml-mapping-metadata-complete element is specified,
the complete set of mapping metadata for the persistence unit
is contained in the XML mapping files for the persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="xml-mapping-metadata-complete"
type="orm:emptyType" minOccurs="0" /&gt;
&lt;xsd:element name="persistence-unit-defaults"
type="orm:persistence-unit-defaults" minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="persistence-unit-defaults"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
These defaults are applied to the persistence unit as a whole
unless they are overridden by local annotation or XML
element settings.
schema - Used as the schema for all tables, secondary tables, join
tables, collection tables, sequence generators, and table
generators that apply to the persistence unit
catalog - Used as the catalog for all tables, secondary tables, join
tables, collection tables, sequence generators, and
table generators that apply to the persistence unit
delimited-identifiers - Used to treat database identifiers as
delimited identifiers.
access - Used as the access type for all managed classes in
the persistence unit
cascade-persist - Adds cascade-persist to the set of cascade options
in all entity relationships of the persistence unit
entity-listeners - List of default entity listeners to be invoked
on each entity in the persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="schema" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="catalog" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="delimited-identifiers" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;xsd:element name="access" type="orm:access-type"
minOccurs="0" /&gt;
&lt;xsd:element name="cascade-persist" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;xsd:element name="entity-listeners" type="orm:entity-listeners"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="entity"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Defines the settings and mappings for an entity. Is allowed to be
sparsely populated and used in conjunction with the annotations.
Alternatively, the metadata-complete attribute can be
used to
indicate that no annotations on the entity class (and its fields
or properties) are to be processed. If this is the case then
the defaulting rules for the entity and its subelements will
be recursively applied.
@Target(TYPE) @Retention(RUNTIME)
public @interface Entity {
String name() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="table" type="orm:table"
minOccurs="0" /&gt;
&lt;xsd:element name="secondary-table" type="orm:secondary-table"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="primary-key-join-column"
type="orm:primary-key-join-column" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;xsd:element name="id-class" type="orm:id-class"
minOccurs="0" /&gt;
&lt;xsd:element name="inheritance" type="orm:inheritance"
minOccurs="0" /&gt;
&lt;xsd:element name="discriminator-value" type="orm:discriminator-value"
minOccurs="0" /&gt;
&lt;xsd:element name="discriminator-column" type="orm:discriminator-column"
minOccurs="0" /&gt;
&lt;xsd:element name="sequence-generator" type="orm:sequence-generator"
minOccurs="0" /&gt;
&lt;xsd:element name="table-generator" type="orm:table-generator"
minOccurs="0" /&gt;
&lt;xsd:element name="named-query" type="orm:named-query"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="named-native-query" type="orm:named-native-query"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="sql-result-set-mapping" type="orm:sql-result-set-mapping"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="exclude-default-listeners"
type="orm:emptyType" minOccurs="0" /&gt;
&lt;xsd:element name="exclude-superclass-listeners"
type="orm:emptyType" minOccurs="0" /&gt;
&lt;xsd:element name="entity-listeners" type="orm:entity-listeners"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-persist" type="orm:pre-persist"
minOccurs="0" /&gt;
&lt;xsd:element name="post-persist" type="orm:post-persist"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-remove" type="orm:pre-remove"
minOccurs="0" /&gt;
&lt;xsd:element name="post-remove" type="orm:post-remove"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-update" type="orm:pre-update"
minOccurs="0" /&gt;
&lt;xsd:element name="post-update" type="orm:post-update"
minOccurs="0" /&gt;
&lt;xsd:element name="post-load" type="orm:post-load"
minOccurs="0" /&gt;
&lt;xsd:element name="attribute-override" type="orm:attribute-override"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="association-override" type="orm:association-override"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="attributes" type="orm:attributes"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="class" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;xsd:attribute name="cacheable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="metadata-complete" type="xsd:boolean" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="access-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
This element determines how the persistence provider accesses the
state of an entity or embedded object.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="PROPERTY" /&gt;
&lt;xsd:enumeration value="FIELD" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="association-override"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME)
public @interface AssociationOverride {
String name();
JoinColumn[] joinColumns() default{};
JoinTable joinTable() default @JoinTable;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string" minOccurs="0" /&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="join-column" type="orm:join-column"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="join-table" type="orm:join-table"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="attribute-override"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME)
public @interface AttributeOverride {
String name();
Column column();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="column" type="orm:column" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="attributes"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
This element contains the entity field or property mappings.
It may be sparsely populated to include only a subset of the
fields or properties. If metadata-complete for the entity is true
then the remainder of the attributes will be defaulted according
to the default rules.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="id" type="orm:id"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="embedded-id" type="orm:embedded-id"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:element name="basic" type="orm:basic"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="version" type="orm:version"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="many-to-one" type="orm:many-to-one"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="one-to-many" type="orm:one-to-many"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="one-to-one" type="orm:one-to-one"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="many-to-many" type="orm:many-to-many"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="element-collection" type="orm:element-collection"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="embedded" type="orm:embedded"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="transient" type="orm:transient"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="basic"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Basic {
FetchType fetch() default EAGER;
boolean optional() default true;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="column" type="orm:column"
minOccurs="0" /&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="lob" type="orm:lob"
minOccurs="0" /&gt;
&lt;xsd:element name="temporal" type="orm:temporal"
minOccurs="0" /&gt;
&lt;xsd:element name="enumerated" type="orm:enumerated"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="fetch" type="orm:fetch-type" /&gt;
&lt;xsd:attribute name="optional" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="cascade-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum CascadeType { ALL, PERSIST, MERGE, REMOVE, REFRESH,
DETACH};
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="cascade-all" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;xsd:element name="cascade-persist" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;xsd:element name="cascade-merge" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;xsd:element name="cascade-remove" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;xsd:element name="cascade-refresh" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;xsd:element name="cascade-detach" type="orm:emptyType"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="collection-table"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface CollectionTable {
String name() default "";
String catalog() default "";
String schema() default "";
JoinColumn[] joinColumns() default {};
UniqueConstraint[] uniqueConstraints() default {};
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="join-column" type="orm:join-column"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="unique-constraint" type="orm:unique-constraint"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="catalog" type="xsd:string" /&gt;
&lt;xsd:attribute name="schema" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="column"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Column {
String name() default "";
boolean unique() default false;
boolean nullable() default true;
boolean insertable() default true;
boolean updatable() default true;
String columnDefinition() default "";
String table() default "";
int length() default 255;
int precision() default 0; // decimal precision
int scale() default 0; // decimal scale
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="unique" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="nullable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="insertable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="updatable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="column-definition" type="xsd:string" /&gt;
&lt;xsd:attribute name="table" type="xsd:string" /&gt;
&lt;xsd:attribute name="length" type="xsd:int" /&gt;
&lt;xsd:attribute name="precision" type="xsd:int" /&gt;
&lt;xsd:attribute name="scale" type="xsd:int" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="column-result"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({}) @Retention(RUNTIME)
public @interface ColumnResult {
String name();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="discriminator-column"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface DiscriminatorColumn {
String name() default "DTYPE";
DiscriminatorType discriminatorType() default STRING;
String columnDefinition() default "";
int length() default 31;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="discriminator-type" type="orm:discriminator-type" /&gt;
&lt;xsd:attribute name="column-definition" type="xsd:string" /&gt;
&lt;xsd:attribute name="length" type="xsd:int" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="discriminator-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum DiscriminatorType { STRING, CHAR, INTEGER };
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="STRING" /&gt;
&lt;xsd:enumeration value="CHAR" /&gt;
&lt;xsd:enumeration value="INTEGER" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="discriminator-value"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface DiscriminatorValue {
String value();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:string" /&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="element-collection"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface ElementCollection {
Class targetClass() default void.class;
FetchType fetch() default LAZY;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="order-by" type="orm:order-by"
minOccurs="0" /&gt;
&lt;xsd:element name="order-column" type="orm:order-column"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key" type="orm:map-key"
minOccurs="0" /&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="map-key-class" type="orm:map-key-class"
minOccurs="0" /&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key-temporal"
type="orm:temporal" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-enumerated"
type="orm:enumerated" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-attribute-override"
type="orm:attribute-override" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key-column"
type="orm:map-key-column" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-join-column"
type="orm:map-key-join-column" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;/xsd:choice&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="column" type="orm:column"
minOccurs="0" /&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="temporal" type="orm:temporal"
minOccurs="0" /&gt;
&lt;xsd:element name="enumerated" type="orm:enumerated"
minOccurs="0" /&gt;
&lt;xsd:element name="lob" type="orm:lob"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="attribute-override"
type="orm:attribute-override" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;xsd:element name="association-override"
type="orm:association-override" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:choice&gt;
&lt;xsd:element name="collection-table" type="orm:collection-table"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="target-class" type="xsd:string" /&gt;
&lt;xsd:attribute name="fetch" type="orm:fetch-type" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="embeddable"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Defines the settings and mappings for embeddable objects. Is
allowed to be sparsely populated and used in conjunction with
the annotations. Alternatively, the metadata-complete attribute
can be used to indicate that no annotations are to be processed
in the class. If this is the case then the defaulting rules will
be recursively applied.
@Target({TYPE}) @Retention(RUNTIME)
public @interface Embeddable {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="attributes" type="orm:embeddable-attributes"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="class" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;xsd:attribute name="metadata-complete" type="xsd:boolean" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="embeddable-attributes"&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="basic" type="orm:basic"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="many-to-one" type="orm:many-to-one"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="one-to-many" type="orm:one-to-many"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="one-to-one" type="orm:one-to-one"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="many-to-many" type="orm:many-to-many"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="element-collection" type="orm:element-collection"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="embedded" type="orm:embedded"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="transient" type="orm:transient"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="embedded"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Embedded {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="attribute-override" type="orm:attribute-override"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="association-override" type="orm:association-override"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="embedded-id"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface EmbeddedId {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="attribute-override" type="orm:attribute-override"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="entity-listener"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Defines an entity listener to be invoked at lifecycle events
for the entities that list this listener.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-persist" type="orm:pre-persist"
minOccurs="0" /&gt;
&lt;xsd:element name="post-persist" type="orm:post-persist"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-remove" type="orm:pre-remove"
minOccurs="0" /&gt;
&lt;xsd:element name="post-remove" type="orm:post-remove"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-update" type="orm:pre-update"
minOccurs="0" /&gt;
&lt;xsd:element name="post-update" type="orm:post-update"
minOccurs="0" /&gt;
&lt;xsd:element name="post-load" type="orm:post-load"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="class" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="entity-listeners"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface EntityListeners {
Class[] value();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="entity-listener" type="orm:entity-listener"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="entity-result"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({}) @Retention(RUNTIME)
public @interface EntityResult {
Class entityClass();
FieldResult[] fields() default {};
String discriminatorColumn() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="field-result" type="orm:field-result"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="entity-class" type="xsd:string"
use="required" /&gt;
&lt;xsd:attribute name="discriminator-column" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="enum-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum EnumType {
ORDINAL,
STRING
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="ORDINAL" /&gt;
&lt;xsd:enumeration value="STRING" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="enumerated"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Enumerated {
EnumType value() default ORDINAL;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="orm:enum-type" /&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="fetch-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum FetchType { LAZY, EAGER };
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="LAZY" /&gt;
&lt;xsd:enumeration value="EAGER" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="field-result"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({}) @Retention(RUNTIME)
public @interface FieldResult {
String name();
String column();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="column" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="generated-value"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface GeneratedValue {
GenerationType strategy() default AUTO;
String generator() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="strategy" type="orm:generation-type" /&gt;
&lt;xsd:attribute name="generator" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="generation-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum GenerationType { TABLE, SEQUENCE, IDENTITY, AUTO };
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="TABLE" /&gt;
&lt;xsd:enumeration value="SEQUENCE" /&gt;
&lt;xsd:enumeration value="IDENTITY" /&gt;
&lt;xsd:enumeration value="AUTO" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="id"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Id {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="column" type="orm:column"
minOccurs="0" /&gt;
&lt;xsd:element name="generated-value" type="orm:generated-value"
minOccurs="0" /&gt;
&lt;xsd:element name="temporal" type="orm:temporal"
minOccurs="0" /&gt;
&lt;xsd:element name="table-generator" type="orm:table-generator"
minOccurs="0" /&gt;
&lt;xsd:element name="sequence-generator" type="orm:sequence-generator"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="id-class"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface IdClass {
Class value();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="class" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="inheritance"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface Inheritance {
InheritanceType strategy() default SINGLE_TABLE;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="strategy" type="orm:inheritance-type" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="inheritance-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum InheritanceType
{ SINGLE_TABLE, JOINED, TABLE_PER_CLASS};
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="SINGLE_TABLE" /&gt;
&lt;xsd:enumeration value="JOINED" /&gt;
&lt;xsd:enumeration value="TABLE_PER_CLASS" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="join-column"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface JoinColumn {
String name() default "";
String referencedColumnName() default "";
boolean unique() default false;
boolean nullable() default true;
boolean insertable() default true;
boolean updatable() default true;
String columnDefinition() default "";
String table() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="referenced-column-name" type="xsd:string" /&gt;
&lt;xsd:attribute name="unique" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="nullable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="insertable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="updatable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="column-definition" type="xsd:string" /&gt;
&lt;xsd:attribute name="table" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="join-table"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface JoinTable {
String name() default "";
String catalog() default "";
String schema() default "";
JoinColumn[] joinColumns() default {};
JoinColumn[] inverseJoinColumns() default {};
UniqueConstraint[] uniqueConstraints() default {};
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="join-column" type="orm:join-column"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="inverse-join-column" type="orm:join-column"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="unique-constraint" type="orm:unique-constraint"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="catalog" type="xsd:string" /&gt;
&lt;xsd:attribute name="schema" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="lob"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Lob {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="lock-mode-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum LockModeType { READ, WRITE, OPTIMISTIC,
OPTIMISTIC_FORCE_INCREMENT, PESSIMISTIC_READ,
PESSIMISTIC_WRITE,
PESSIMISTIC_FORCE_INCREMENT, NONE};
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="READ" /&gt;
&lt;xsd:enumeration value="WRITE" /&gt;
&lt;xsd:enumeration value="OPTIMISTIC" /&gt;
&lt;xsd:enumeration value="OPTIMISTIC_FORCE_INCREMENT" /&gt;
&lt;xsd:enumeration value="PESSIMISTIC_READ" /&gt;
&lt;xsd:enumeration value="PESSIMISTIC_WRITE" /&gt;
&lt;xsd:enumeration value="PESSIMISTIC_FORCE_INCREMENT" /&gt;
&lt;xsd:enumeration value="NONE" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="many-to-many"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface ManyToMany {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default LAZY;
String mappedBy() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="order-by" type="orm:order-by"
minOccurs="0" /&gt;
&lt;xsd:element name="order-column" type="orm:order-column"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key" type="orm:map-key"
minOccurs="0" /&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="map-key-class" type="orm:map-key-class"
minOccurs="0" /&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key-temporal"
type="orm:temporal" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-enumerated"
type="orm:enumerated" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-attribute-override"
type="orm:attribute-override" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key-column"
type="orm:map-key-column" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-join-column"
type="orm:map-key-join-column" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;/xsd:choice&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:choice&gt;
&lt;xsd:element name="join-table" type="orm:join-table"
minOccurs="0" /&gt;
&lt;xsd:element name="cascade" type="orm:cascade-type"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="target-entity" type="xsd:string" /&gt;
&lt;xsd:attribute name="fetch" type="orm:fetch-type" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;xsd:attribute name="mapped-by" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="many-to-one"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface ManyToOne {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default EAGER;
boolean optional() default true;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="join-column" type="orm:join-column"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="join-table" type="orm:join-table"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:element name="cascade" type="orm:cascade-type"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="target-entity" type="xsd:string" /&gt;
&lt;xsd:attribute name="fetch" type="orm:fetch-type" /&gt;
&lt;xsd:attribute name="optional" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;xsd:attribute name="maps-id" type="xsd:string" /&gt;
&lt;xsd:attribute name="id" type="xsd:boolean" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="map-key"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface MapKey {
String name() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="map-key-class"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface MapKeyClass {
Class value();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="class" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="map-key-column"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface MapKeyColumn {
String name() default "";
boolean unique() default false;
boolean nullable() default false;
boolean insertable() default true;
boolean updatable() default true;
String columnDefinition() default "";
String table() default "";
int length() default 255;
int precision() default 0; // decimal precision
int scale() default 0; // decimal scale
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="unique" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="nullable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="insertable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="updatable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="column-definition" type="xsd:string" /&gt;
&lt;xsd:attribute name="table" type="xsd:string" /&gt;
&lt;xsd:attribute name="length" type="xsd:int" /&gt;
&lt;xsd:attribute name="precision" type="xsd:int" /&gt;
&lt;xsd:attribute name="scale" type="xsd:int" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="map-key-join-column"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface MapKeyJoinColumn {
String name() default "";
String referencedColumnName() default "";
boolean unique() default false;
boolean nullable() default false;
boolean insertable() default true;
boolean updatable() default true;
String columnDefinition() default "";
String table() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="referenced-column-name" type="xsd:string" /&gt;
&lt;xsd:attribute name="unique" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="nullable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="insertable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="updatable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="column-definition" type="xsd:string" /&gt;
&lt;xsd:attribute name="table" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="mapped-superclass"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Defines the settings and mappings for a mapped superclass. Is
allowed to be sparsely populated and used in conjunction with
the annotations. Alternatively, the metadata-complete attribute
can be used to indicate that no annotations are to be processed
If this is the case then the defaulting rules will be recursively
applied.
@Target(TYPE) @Retention(RUNTIME)
public @interface MappedSuperclass{}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="id-class" type="orm:id-class"
minOccurs="0" /&gt;
&lt;xsd:element name="exclude-default-listeners"
type="orm:emptyType" minOccurs="0" /&gt;
&lt;xsd:element name="exclude-superclass-listeners"
type="orm:emptyType" minOccurs="0" /&gt;
&lt;xsd:element name="entity-listeners" type="orm:entity-listeners"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-persist" type="orm:pre-persist"
minOccurs="0" /&gt;
&lt;xsd:element name="post-persist" type="orm:post-persist"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-remove" type="orm:pre-remove"
minOccurs="0" /&gt;
&lt;xsd:element name="post-remove" type="orm:post-remove"
minOccurs="0" /&gt;
&lt;xsd:element name="pre-update" type="orm:pre-update"
minOccurs="0" /&gt;
&lt;xsd:element name="post-update" type="orm:post-update"
minOccurs="0" /&gt;
&lt;xsd:element name="post-load" type="orm:post-load"
minOccurs="0" /&gt;
&lt;xsd:element name="attributes" type="orm:attributes"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="class" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;xsd:attribute name="metadata-complete" type="xsd:boolean" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="named-native-query"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface NamedNativeQuery {
String name();
String query();
QueryHint[] hints() default {};
Class resultClass() default void.class;
String resultSetMapping() default ""; //named SqlResultSetMapping
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="query" type="xsd:string" /&gt;
&lt;xsd:element name="hint" type="orm:query-hint"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="result-class" type="xsd:string" /&gt;
&lt;xsd:attribute name="result-set-mapping" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="named-query"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface NamedQuery {
String name();
String query();
LockModeType lockMode() default NONE;
QueryHint[] hints() default {};
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="query" type="xsd:string" /&gt;
&lt;xsd:element name="lock-mode" type="orm:lock-mode-type"
minOccurs="0" /&gt;
&lt;xsd:element name="hint" type="orm:query-hint"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="one-to-many"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OneToMany {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default LAZY;
String mappedBy() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="order-by" type="orm:order-by"
minOccurs="0" /&gt;
&lt;xsd:element name="order-column" type="orm:order-column"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key" type="orm:map-key"
minOccurs="0" /&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="map-key-class" type="orm:map-key-class"
minOccurs="0" /&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key-temporal"
type="orm:temporal" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-enumerated"
type="orm:enumerated" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-attribute-override"
type="orm:attribute-override" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="map-key-column"
type="orm:map-key-column" minOccurs="0" /&gt;
&lt;xsd:element name="map-key-join-column"
type="orm:map-key-join-column" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;/xsd:choice&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:choice&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="join-table" type="orm:join-table"
minOccurs="0" /&gt;
&lt;xsd:element name="join-column" type="orm:join-column"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:element name="cascade" type="orm:cascade-type"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="target-entity" type="xsd:string" /&gt;
&lt;xsd:attribute name="fetch" type="orm:fetch-type" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;xsd:attribute name="mapped-by" type="xsd:string" /&gt;
&lt;xsd:attribute name="orphan-removal" type="xsd:boolean" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="one-to-one"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OneToOne {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default EAGER;
boolean optional() default true;
String mappedBy() default "";
boolean orphanRemoval() default false;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:choice&gt;
&lt;xsd:element name="primary-key-join-column"
type="orm:primary-key-join-column" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;xsd:element name="join-column" type="orm:join-column"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="join-table" type="orm:join-table"
minOccurs="0" /&gt;
&lt;/xsd:choice&gt;
&lt;xsd:element name="cascade" type="orm:cascade-type"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="target-entity" type="xsd:string" /&gt;
&lt;xsd:attribute name="fetch" type="orm:fetch-type" /&gt;
&lt;xsd:attribute name="optional" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;xsd:attribute name="mapped-by" type="xsd:string" /&gt;
&lt;xsd:attribute name="orphan-removal" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="maps-id" type="xsd:string" /&gt;
&lt;xsd:attribute name="id" type="xsd:boolean" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="order-by"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OrderBy {
String value() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:string" /&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="order-column"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OrderColumn {
String name() default "";
boolean nullable() default true;
boolean insertable() default true;
boolean updatable() default true;
String columnDefinition() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="nullable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="insertable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="updatable" type="xsd:boolean" /&gt;
&lt;xsd:attribute name="column-definition" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="post-load"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD}) @Retention(RUNTIME)
public @interface PostLoad {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="method-name" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="post-persist"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD}) @Retention(RUNTIME)
public @interface PostPersist {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="method-name" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="post-remove"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD}) @Retention(RUNTIME)
public @interface PostRemove {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="method-name" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="post-update"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD}) @Retention(RUNTIME)
public @interface PostUpdate {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="method-name" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="pre-persist"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD}) @Retention(RUNTIME)
public @interface PrePersist {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="method-name" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="pre-remove"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD}) @Retention(RUNTIME)
public @interface PreRemove {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="method-name" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="pre-update"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD}) @Retention(RUNTIME)
public @interface PreUpdate {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="method-name" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="primary-key-join-column"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME)
public @interface PrimaryKeyJoinColumn {
String name() default "";
String referencedColumnName() default "";
String columnDefinition() default "";
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="referenced-column-name" type="xsd:string" /&gt;
&lt;xsd:attribute name="column-definition" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="query-hint"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({}) @Retention(RUNTIME)
public @interface QueryHint {
String name();
String value();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="value" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="secondary-table"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface SecondaryTable {
String name();
String catalog() default "";
String schema() default "";
PrimaryKeyJoinColumn[] pkJoinColumns() default {};
UniqueConstraint[] uniqueConstraints() default {};
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="primary-key-join-column"
type="orm:primary-key-join-column" minOccurs="0"
maxOccurs="unbounded" /&gt;
&lt;xsd:element name="unique-constraint" type="orm:unique-constraint"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="catalog" type="xsd:string" /&gt;
&lt;xsd:attribute name="schema" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="sequence-generator"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME)
public @interface SequenceGenerator {
String name();
String sequenceName() default "";
String catalog() default "";
String schema() default "";
int initialValue() default 1;
int allocationSize() default 50;
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="sequence-name" type="xsd:string" /&gt;
&lt;xsd:attribute name="catalog" type="xsd:string" /&gt;
&lt;xsd:attribute name="schema" type="xsd:string" /&gt;
&lt;xsd:attribute name="initial-value" type="xsd:int" /&gt;
&lt;xsd:attribute name="allocation-size" type="xsd:int" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="sql-result-set-mapping"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface SqlResultSetMapping {
String name();
EntityResult[] entities() default {};
ColumnResult[] columns() default {};
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="entity-result" type="orm:entity-result"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;xsd:element name="column-result" type="orm:column-result"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="table"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE}) @Retention(RUNTIME)
public @interface Table {
String name() default "";
String catalog() default "";
String schema() default "";
UniqueConstraint[] uniqueConstraints() default {};
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="unique-constraint" type="orm:unique-constraint"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;xsd:attribute name="catalog" type="xsd:string" /&gt;
&lt;xsd:attribute name="schema" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="table-generator"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME)
public @interface TableGenerator {
String name();
String table() default "";
String catalog() default "";
String schema() default "";
String pkColumnName() default "";
String valueColumnName() default "";
String pkColumnValue() default "";
int initialValue() default 0;
int allocationSize() default 50;
UniqueConstraint[] uniqueConstraints() default {};
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="description" type="xsd:string"
minOccurs="0" /&gt;
&lt;xsd:element name="unique-constraint" type="orm:unique-constraint"
minOccurs="0" maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="table" type="xsd:string" /&gt;
&lt;xsd:attribute name="catalog" type="xsd:string" /&gt;
&lt;xsd:attribute name="schema" type="xsd:string" /&gt;
&lt;xsd:attribute name="pk-column-name" type="xsd:string" /&gt;
&lt;xsd:attribute name="value-column-name" type="xsd:string" /&gt;
&lt;xsd:attribute name="pk-column-value" type="xsd:string" /&gt;
&lt;xsd:attribute name="initial-value" type="xsd:int" /&gt;
&lt;xsd:attribute name="allocation-size" type="xsd:int" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="temporal"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Temporal {
TemporalType value();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="orm:temporal-type" /&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="temporal-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum TemporalType {
DATE, // java.sql.Date
TIME, // java.sql.Time
TIMESTAMP // java.sql.Timestamp
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="DATE" /&gt;
&lt;xsd:enumeration value="TIME" /&gt;
&lt;xsd:enumeration value="TIMESTAMP" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="transient"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Transient {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="unique-constraint"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({}) @Retention(RUNTIME)
public @interface UniqueConstraint {
String name() default "";
String[] columnNames();
}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="column-name" type="xsd:string"
maxOccurs="unbounded" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" /&gt;
&lt;/xsd:complexType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:complexType name="version"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Version {}
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="column" type="orm:column"
minOccurs="0" /&gt;
&lt;xsd:element name="temporal" type="orm:temporal"
minOccurs="0" /&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="name" type="xsd:string" use="required" /&gt;
&lt;xsd:attribute name="access" type="orm:access-type" /&gt;
&lt;/xsd:complexType&gt;
&lt;/xsd:schema&gt;
</pre>
</div>
<div class="section" id="jpa_overview_meta_complete"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Conclusion
</h2></div></div></div>
<p>
That exhausts persistence metadata annotations. We present the class definitions
for our sample model below:
</p>
<div class="example" id="jpa_overview_meta_complete_ex"><p class="title"><b>Example&nbsp;5.2.&nbsp;
Complete Metadata
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
public class Magazine {
@Id private String isbn;
@Id private String title;
@Version private int version;
private double price; // defaults to @Basic
private int copiesSold; // defaults to @Basic
@OneToOne(fetch=FetchType.LAZY,
cascade={CascadeType.PERSIST,CascadeType.REMOVE})
private Article coverArticle;
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@OrderBy
private Collection&lt;Article&gt; articles;
@ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST)
private Company publisher;
@Transient private byte[] data;
...
public static class MagazineId {
...
}
}
@Entity
public class Article {
@Id private long id;
@Version private int version;
private String title; // defaults to @Basic
private byte[] content; // defaults to @Basic
@ManyToMany(cascade=CascadeType.PERSIST)
@OrderBy("lastName, firstName")
private Collection&lt;Author&gt; authors;
...
}
package org.mag.pub;
@Entity
public class Company {
@Id private long id;
@Version private int version;
private String name; // defaults to @Basic
private double revenue; // defaults to @Basic
private Address address; // defaults to @Embedded
@OneToMany(mappedBy="publisher", cascade=CascadeType.PERSIST)
private Collection&lt;Magazine&gt; mags;
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
private Collection&lt;Subscription&gt; subscriptions;
...
}
@Entity
public class Author {
@Id private long id;
@Version private int version;
private String firstName; // defaults to @Basic
private double lastName; // defaults to @Basic
private Address address; // defaults to @Embedded
@ManyToMany(mappedBy="authors", cascade=CascadeType.PERSIST)
private Collection&lt;Article&gt; arts;
...
}
@Embeddable
public class Address {
private String street; // defaults to @Basic
private String city; // defaults to @Basic
private String state; // defaults to @Basic
private String zip; // defaults to @Basic
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
@Id private long id;
@Version private int version;
...
}
@Entity
public class Contract
extends Document {
private String terms; // defaults to @Basic
...
}
@Entity
public class Subscription {
@Id private long id;
@Version private int version;
private Date startDate; // defaults to @Basic
private double payment; // defaults to @Basic
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@MapKey(name="num")
private Map&lt;Long,LineItem&gt; lineItems;
...
@Entity
public static class LineItem
extends Contract {
private String comments; // defaults to @Basic
private double price; // defaults to @Basic
private long num; // defaults to @Basic
@ManyToOne
private Magazine magazine;
...
}
}
@Entity(name="Lifetime")
public class LifetimeSubscription
extends Subscription {
@Basic(fetch=FetchType.LAZY)
private boolean getEliteClub() { ... }
public void setEliteClub(boolean elite) { ... }
...
}
@Entity(name="Trial")
public class TrialSubscription
extends Subscription {
public Date getEndDate() { ... }
public void setEndDate(Date end) { ... }
...
}
</pre>
<p>
The same metadata declarations in XML:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"&gt;
&lt;!-- declares a default access type for all entities --&gt;
&lt;access-type&gt;FIELD&lt;/access-type&gt;
&lt;mapped-superclass class="org.mag.subscribe.Document"&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
&lt;version name="version"/&gt;
&lt;/attributes&gt;
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.Magazine"&gt;
&lt;id-class="org.mag.Magazine$MagazineId"/&gt;
&lt;attributes&gt;
&lt;id name="isbn"/&gt;
&lt;id name="title"/&gt;
&lt;basic name="name"/&gt;
&lt;basic name="price"/&gt;
&lt;basic name="copiesSold"/&gt;
&lt;version name="version"/&gt;
&lt;many-to-one name="publisher" fetch="LAZY"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;/cascade&gt;
&lt;/many-to-one&gt;
&lt;one-to-many name="articles"&gt;
&lt;order-by/&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;one-to-one name="coverArticle" fetch="LAZY"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-one&gt;
&lt;transient name="data"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
&lt;basic name="title"/&gt;
&lt;basic name="content"/&gt;
&lt;version name="version"/&gt;
&lt;many-to-many name="articles"&gt;
&lt;order-by&gt;lastName, firstName&lt;/order-by&gt;
&lt;/many-to-many&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
&lt;basic name="name"/&gt;
&lt;basic name="revenue"/&gt;
&lt;version name="version"/&gt;
&lt;one-to-many name="mags" mapped-by="publisher"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;one-to-many name="subscriptions"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
&lt;basic name="firstName"/&gt;
&lt;basic name="lastName"/&gt;
&lt;version name="version"/&gt;
&lt;many-to-many name="arts" mapped-by="authors"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;/cascade&gt;
&lt;/many-to-many&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;attributes&gt;
&lt;basic name="terms"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Subscription"&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
&lt;basic name="payment"/&gt;
&lt;basic name="startDate"/&gt;
&lt;version name="version"/&gt;
&lt;one-to-many name="items"&gt;
&lt;map-key name="num"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;attributes&gt;
&lt;basic name="comments"/&gt;
&lt;basic name="price"/&gt;
&lt;basic name="num"/&gt;
&lt;many-to-one name="magazine"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription" name="Lifetime"
access="PROPERTY"&gt;
&lt;attributes&gt;
&lt;basic name="eliteClub" fetch="LAZY"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.TrialSubscription" name="Trial"&gt;
&lt;attributes&gt;
&lt;basic name="endDate"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;embeddable class="org.mag.pub.Address"&gt;
&lt;attributes&gt;
&lt;basic name="street"/&gt;
&lt;basic name="city"/&gt;
&lt;basic name="state"/&gt;
&lt;basic name="zip"/&gt;
&lt;/attributes&gt;
&lt;/embeddable&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
<p>
<a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a> will show you how to map your
persistent classes to the datastore using additional annotations and XML markup.
First, however, we turn to the JPA runtime APIs.
</p>
</div>
</div>
<div class="chapter" id="jpa_overview_persistence"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;6.&nbsp;
Persistence
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_persistence_xml">1.
persistence.xml
</a></span></dt><dt><span class="section"><a href="#jpa_overview_persistence_use">2.
Non-EE Use
</a></span></dt></dl></div>
<a class="indexterm" name="d5e1988"></a>
<a class="indexterm" name="d5e1990"></a>
<a class="indexterm" name="d5e1993"></a>
<a class="indexterm" name="d5e1996"></a>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="285"><tr><td><img src="img/persistence.png"></td></tr></table></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA also includes the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAPersistence.html" target="_top">
<code class="classname">OpenJPAPersistence</code></a> helper class to provide
additional utility methods.
</p>
</div>
<p>
Within a container, you will typically use <span class="emphasis"><em>injection</em></span> to
access an <code class="classname">EntityManagerFactory</code>. Applications operating
outside of a container, however, can use the
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/Persistence.html" target="_top">
<code class="classname">Persistence</code></a> class to obtain <code class="classname">
EntityManagerFactory</code> objects in a vendor-neutral fashion.
</p>
<pre class="programlisting">
public static EntityManagerFactory createEntityManagerFactory(String name);
public static EntityManagerFactory createEntityManagerFactory(String name, Map props);
public static PersistenceUtil getPersistenceUtil();
</pre>
<p>
Each <code class="methodname">createEntityManagerFactory</code> method searches the
system for an <code class="classname">EntityManagerFactory</code> definition with the
given name. Use <code class="literal">null</code> for an unnamed factory. The optional map
contains vendor-specific property settings used to further configure the
factory.
</p>
<p>
<code class="filename">persistence.xml</code> files define <code class="classname">
EntityManagerFactories</code>. The <code class="methodname">createEntityManagerFactory
</code> methods search for <code class="filename">persistence.xml</code> files
within the <code class="filename">META-INF</code> directory of any <code class="literal">CLASSPATH
</code> element. For example, if your <code class="literal">CLASSPATH</code> contains
the <code class="filename">conf</code> directory, you could place an <code class="classname">
EntityManagerFactory</code> definition in <code class="filename">
conf/META-INF/persistence.xml</code>.
</p>
<p>
The <code class="methodname">getPersistenceUtil</code> method returns a PersistenceUtil
interface that can be used to determine whether an entity or attribute of an
entity is loaded.
</p>
<pre class="programlisting">
PersistenceUtil pUtil = Persistence.getPersistenceUtil();
if (!pUtil.isLoaded(myEntity)) {
loadEntity(myEntity);
}
</pre>
<div class="section" id="jpa_overview_persistence_xml"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
persistence.xml
</h2></div></div></div>
<p>
With the introduction of JPA 2.0, there are two versions of the
<code class="filename">persistence.xml</code>. The most current revision of the
2.0 persistence schema is presented below. Version 1.0 of the persistence
schema can be found at
<a class="ulink" href="http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" target="_top">http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd</a>.
</p>
<pre class="programlisting">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!-- persistence.xml schema --&gt;
&lt;xsd:schema targetNamespace="http://java.sun.com/xml/ns/persistence"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:persistence="http://java.sun.com/xml/ns/persistence"
elementFormDefault="qualified" attributeFormDefault="unqualified"
version="2.0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
@(#)persistence_2_0.xsd 1.0 October 1 2009
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2005-2009 Sun Microsystems, Inc. All rights reserved.
The contents of this file are subject to the terms of either the
GNU General Public License Version 2 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with
the License. You can obtain a copy of the License at
https://glassfish.dev.java.net/public/CDDL+GPL.html or
glassfish/bootstrap/legal/LICENSE.txt. See the License for the
specific language governing permissions and limitations under the
License.
When distributing the software, include this License Header
Notice in each file and include the License file at
glassfish/bootstrap/legal/LICENSE.txt. Sun designates this
particular file as subject to the "Classpath" exception as
provided by Sun in the GPL Version 2 section of the License file
that accompanied this code. If applicable, add the following
below the License Header, with the fields enclosed by brackets []
replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
Contributor(s):
If you wish your version of this file to be governed by only the
CDDL or only the GPL Version 2, indicate your decision by adding
"[Contributor] elects to include this software in this
distribution under the [CDDL or GPL Version 2] license." If you
don't indicate a single choice of license, a recipient has the
option to distribute your version of this file under either the
CDDL, the GPL Version 2 or to extend the choice of license to its
licensees as provided above. However, if you add GPL Version 2
code and therefore, elected the GPL Version 2 license, then the
option applies only if the new code is made subject to such
option by the copyright holder.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
&lt;![CDATA[
This is the XML Schema for the persistence configuration file.
The file must be named "META-INF/persistence.xml" in the
persistence archive.
Persistence configuration files must indicate
the persistence schema by using the persistence namespace:
http://java.sun.com/xml/ns/persistence
and indicate the version of the schema by
using the version element as shown below:
&lt;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
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0"&gt;
...
&lt;/persistence&gt;
]]&gt;
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:simpleType name="versionType"&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:pattern value="[0-9]+(\.[0-9]+)*" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="persistence"&gt;
&lt;xsd:complexType&gt;
&lt;xsd:sequence&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="persistence-unit"
minOccurs="1" maxOccurs="unbounded"&gt;
&lt;xsd:complexType&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Configuration of a persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:sequence&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="description"
type="xsd:string" minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Description of this persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="provider"
type="xsd:string" minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Provider class that supplies EntityManagers for this
persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="jta-data-source"
type="xsd:string" minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
The container-specific name of the JTA datasource to use.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="non-jta-data-source"
type="xsd:string" minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
The container-specific name of a non-JTA datasource to use.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="mapping-file"
type="xsd:string" minOccurs="0"
maxOccurs="unbounded"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
File containing mapping information. Loaded as a resource
by the persistence provider.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="jar-file"
type="xsd:string" minOccurs="0"
maxOccurs="unbounded"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Jar file that is to be scanned for managed classes.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="class" type="xsd:string"
minOccurs="0" maxOccurs="unbounded"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Managed class to be included in the persistence unit and
to scan for annotations. It should be annotated
with either @Entity, @Embeddable or @MappedSuperclass.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="exclude-unlisted-classes"
type="xsd:boolean" default="true"
minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
When set to true then only listed classes and jars will
be scanned for persistent classes, otherwise the
enclosing jar or directory will also be scanned.
Not applicable to Java SE persistence units.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="shared-cache-mode"
type="persistence:persistence-unit-caching-type"
minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Defines whether caching is enabled for the
persistence unit if caching is supported by the
persistence provider. When set to ALL, all entities
will be cached. When set to NONE, no entities will
be cached. When set to ENABLE_SELECTIVE, only entities
specified as cacheable will be cached. When set to
DISABLE_SELECTIVE, entities specified as not cacheable
will not be cached. When not specified or when set to
UNSPECIFIED, provider defaults may apply.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="validation-mode"
type="persistence:persistence-unit-validation-mode-type"
minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
The validation mode to be used for the persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:element name="properties"
minOccurs="0"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
A list of standard and vendor-specific properties
and hints.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:complexType&gt;
&lt;xsd:sequence&gt;
&lt;xsd:element name="property"
minOccurs="0" maxOccurs="unbounded"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
A name-value pair.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:complexType&gt;
&lt;xsd:attribute
name="name" type="xsd:string"
use="required" /&gt;
&lt;xsd:attribute
name="value" type="xsd:string"
use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;/xsd:element&gt;
&lt;/xsd:sequence&gt;
&lt;/xsd:complexType&gt;
&lt;/xsd:element&gt;
&lt;/xsd:sequence&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:attribute name="name" type="xsd:string"
use="required"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Name used in code to reference this persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:attribute&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:attribute name="transaction-type"
type="persistence:persistence-unit-transaction-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
Type of transactions used by EntityManagers from this
persistence unit.
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;/xsd:attribute&gt;
&lt;/xsd:complexType&gt;
&lt;/xsd:element&gt;
&lt;/xsd:sequence&gt;
&lt;xsd:attribute name="version" type="persistence:versionType"
fixed="2.0" use="required" /&gt;
&lt;/xsd:complexType&gt;
&lt;/xsd:element&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="persistence-unit-transaction-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="JTA" /&gt;
&lt;xsd:enumeration value="RESOURCE_LOCAL" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="persistence-unit-caching-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE,
DISABLE_SELECTIVE, UNSPECIFIED};
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="ALL" /&gt;
&lt;xsd:enumeration value="NONE" /&gt;
&lt;xsd:enumeration value="ENABLE_SELECTIVE" /&gt;
&lt;xsd:enumeration value="DISABLE_SELECTIVE" /&gt;
&lt;xsd:enumeration value="UNSPECIFIED" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;!-- **************************************************** --&gt;
&lt;xsd:simpleType name="persistence-unit-validation-mode-type"&gt;
&lt;xsd:annotation&gt;
&lt;xsd:documentation&gt;
public enum ValidationMode { AUTO, CALLBACK, NONE};
&lt;/xsd:documentation&gt;
&lt;/xsd:annotation&gt;
&lt;xsd:restriction base="xsd:token"&gt;
&lt;xsd:enumeration value="AUTO" /&gt;
&lt;xsd:enumeration value="CALLBACK" /&gt;
&lt;xsd:enumeration value="NONE" /&gt;
&lt;/xsd:restriction&gt;
&lt;/xsd:simpleType&gt;
&lt;/xsd:schema&gt;
</pre>
<p>
The root element of a <code class="filename">persistence.xml</code> file is <code class="literal">
persistence</code>, which then contains one or more <code class="literal">
persistence-unit</code> definitions. The root element should include the
version attribute with the appropriate version, <code class="literal">1.0</code> for a
version 1.0 file and <code class="literal">2.0</code> for a version 2.0 file. Each
persistence unit describes the configuration for the entity managers created by
the persistence unit's entity manager factory. The persistence unit can specify
these elements and attributes.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>: This is the name you pass to the <code class="methodname">
Persistence.createEntityManagerFactory</code> methods described above. The
name attribute is required.
</p>
</li><li class="listitem">
<p>
<code class="literal">transaction-type</code>: Whether to use managed
(<code class="literal">JTA</code>) or local (<code class="literal">RESOURCE_LOCAL</code>)
transaction management.
</p>
</li><li class="listitem">
<p>
<code class="literal">provider</code>: If you are using a third-party JPA vendor, this
element names its implementation of the
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/spi/PersistenceProvider.html" target="_top">
<code class="classname">PersistenceProvider</code></a> bootstrapping interface.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Set the <code class="literal">provider</code> to <code class="classname">
org.apache.openjpa.persistence.PersistenceProviderImpl</code> to use
OpenJPA.
</p>
</div>
</li><li class="listitem">
<p>
<code class="literal">jta-data-source</code>: The JNDI name of a JDBC <code class="classname">
DataSource</code> that is automatically enlisted in JTA transactions. This
may be an XA <code class="classname">DataSource</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">non-jta-data-source</code>: The JNDI name of a JDBC <code class="classname">
DataSource</code> that is not enlisted in JTA transactions.
</p>
</li><li class="listitem">
<p>
<code class="literal">mapping-file</code>*: The resource names of XML mapping files for
entities and embeddable classes. You can also specify mapping information in an
<code class="filename">orm.xml</code> file in your <code class="filename">META-INF</code>
directory. If present, the <code class="filename">orm.xml</code> mapping file will be
read automatically.
</p>
</li><li class="listitem">
<p>
<code class="literal">jar-file</code>*: The names of jar files containing entities and
embeddable classes. The implementation will scan the jar for annotated classes.
</p>
</li><li class="listitem">
<p>
<code class="literal">class</code>*: The class names of entities and embeddable classes.
</p>
</li><li class="listitem">
<p>
<code class="literal">properties</code>: This element contains nested <code class="literal">property
</code> elements used to specify vendor-specific settings. Each <code class="literal">
property</code> has a name attribute and a value attribute.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
The Reference Guide's <a class="xref" href="#ref_guide_conf" title="Chapter&nbsp;2.&nbsp; Configuration">Chapter&nbsp;2, <i>
Configuration
</i></a> describes OpenJPA's
configuration properties.
</p>
</div>
</li></ul></div>
<p>
Here is a typical <code class="filename">persistence.xml</code> file for a non-EE
environment:
</p>
<div class="example" id="jpa_overview_persistence_xmlex"><p class="title"><b>Example&nbsp;6.1.&nbsp;
persistence.xml
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;?xml version="1.0"?&gt;
&lt;persistence version="1.0"&gt;
&lt;persistence-unit name="openjpa"&gt;
&lt;provider&gt;org.apache.openjpa.persistence.PersistenceProviderImpl&lt;/provider&gt;
&lt;class&gt;tutorial.Animal&lt;/class&gt;
&lt;class&gt;tutorial.Dog&lt;/class&gt;
&lt;class&gt;tutorial.Rabbit&lt;/class&gt;
&lt;class&gt;tutorial.Snake&lt;/class&gt;
&lt;properties&gt;
&lt;property name="openjpa.ConnectionURL" value="jdbc:hsqldb:tutorial_database"/&gt;
&lt;property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver"/&gt;
&lt;property name="openjpa.ConnectionUserName" value="sa"/&gt;
&lt;property name="openjpa.ConnectionPassword" value=""/&gt;
&lt;property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/&gt;
&lt;/properties&gt;
&lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_persistence_use"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Non-EE Use
</h2></div></div></div>
<p>
The example below demonstrates the <code class="classname">Persistence</code> class in
action. You will typically execute code like this on application startup, then
cache the resulting factory for future use. This bootstrapping code is only
necessary in non-EE environments; in an EE environment <code class="classname">
EntityManagerFactories</code> are typically injected.
</p>
<div class="example" id="jpa_overview_persistence_getemfactory"><p class="title"><b>Example&nbsp;6.2.&nbsp;
Obtaining an EntityManagerFactory
</b></p><div class="example-contents">
<pre class="programlisting">
// if your persistence.xml file does not contain all settings already, you
// can add vendor settings to a map
Properties props = new Properties();
...
// create the factory defined by the "openjpa" entity-manager entry
EntityManagerFactory emf = Persistence.createEntityManagerFactory("openjpa", props);
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="chapter" id="jpa_overview_emfactory"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;7.&nbsp;
EntityManagerFactory
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_emfactory_obtain">1.
Obtaining an EntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_em">2.
Obtaining EntityManagers
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext">3.
Persistence Context
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_trans">3.1.
Transaction Persistence Context
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_extend">3.2.
Extended Persistence Context
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_emf_properties">4.
Retrieving Properties Information
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_close">5.
Closing the EntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_puutil">6.
PersistenceUnitUtil
</a></span></dt></dl></div>
<a class="indexterm" name="d5e2106"></a>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="279"><tr><td><img src="img/entitymanagerfactory.png"></td></tr></table></div>
<p>
The <code class="classname">EntityManagerFactory</code> creates <code class="classname">
EntityManager</code> instances for application use.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA extends the standard <code class="classname">EntityManagerFactory</code>
interface with the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManagerFactory.html" target="_top">
<code class="classname">OpenJPAEntityManagerFactory</code></a> to provide additional
functionality.
</p>
</div>
<div class="section" id="jpa_overview_emfactory_obtain"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Obtaining an EntityManagerFactory
</h2></div></div></div>
<a class="indexterm" name="d5e2121"></a>
<a class="indexterm" name="d5e2124"></a>
<a class="indexterm" name="d5e2127"></a>
<p>
Within a container, you will typically use <span class="emphasis"><em>injection</em></span> to
access an <code class="classname">EntityManagerFactory</code>. There are, however,
alternative mechanisms for <code class="classname">EntityManagerFactory</code>
construction.
</p>
<p>
Some vendors may supply public constructors for their <code class="classname">
EntityManagerFactory</code> implementations, but we recommend using the
Java Connector Architecture (JCA) in a managed environment, or the <code class="classname">
Persistence</code> class' <code class="methodname">createEntityManagerFactory
</code> methods in an unmanaged environment, as described in
<a class="xref" href="#jpa_overview_persistence" title="Chapter&nbsp;6.&nbsp; Persistence">Chapter&nbsp;6, <i>
Persistence
</i></a>. These strategies allow
vendors to pool factories, cutting down on resource utilization.
</p>
<p>
<a class="indexterm" name="d5e2139"></a>
JPA allows you to create and configure an <code class="classname">
EntityManagerFactory</code>, then store it in a Java Naming and Directory
Interface (JNDI) tree for later retrieval and use.
</p>
</div>
<div class="section" id="jpa_overview_emfactory_em"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Obtaining EntityManagers
</h2></div></div></div>
<a class="indexterm" name="d5e2144"></a>
<a class="indexterm" name="d5e2148"></a>
<pre class="programlisting">
public EntityManager createEntityManager();
public EntityManager createEntityManager(Map map);
</pre>
<p>
The two <code class="methodname">createEntityManager</code> methods above create a new
<code class="classname">EntityManager</code> each time they are invoked. The optional
<code class="classname">Map</code> is used to supply vendor-specific settings. If you
have configured your implementation for JTA transactions and a JTA transaction
is active, the returned <code class="classname">EntityManager</code> will be
synchronized with that transaction.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA recognizes the following string keys in the map supplied to <code class="methodname">
createEntityManager</code>:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">openjpa.ConnectionUserName</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">openjpa.ConnectionPassword</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">openjpa.ConnectionRetainMode</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">openjpa.TransactionMode</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">openjpa.&lt;property&gt;</code>, where <span class="emphasis"><em>&lt;property&gt;
</em></span> is any JavaBean property of the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">
org.apache.openjpa.persistence.OpenJPAEntityManager</code></a>.
</p>
</li></ul></div>
<p>
The last option uses reflection to configure any property of OpenJPA's
<code class="classname">EntityManager</code> implementation with the value supplied in
your map. The first options correspond exactly to the same-named OpenJPA
configuration keys described in <a class="xref" href="#ref_guide_conf" title="Chapter&nbsp;2.&nbsp; Configuration">Chapter&nbsp;2, <i>
Configuration
</i></a> of the
Reference Guide.
</p>
</div>
</div>
<div class="section" id="jpa_overview_emfactory_perscontext"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Persistence Context
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_trans">3.1.
Transaction Persistence Context
</a></span></dt><dt><span class="section"><a href="#jpa_overview_emfactory_perscontext_extend">3.2.
Extended Persistence Context
</a></span></dt></dl></div>
<a class="indexterm" name="d5e2184"></a>
<a class="indexterm" name="d5e2186"></a>
<p>
A persistence context is a set of entities such that for any persistent identity
there is a unique entity instance. Within a persistence context, entities are
<span class="emphasis"><em>managed</em></span>. The <code class="classname"> EntityManager</code> controls
their lifecycle, and they can access datastore resources.
</p>
<p>
When a persistence context ends, previously-managed entities become <span class="emphasis"><em>
detached</em></span>. A detached entity is no longer under the control of the
<code class="classname">EntityManager</code>, and no longer has access to datastore
resources. We discuss detachment in detail in
<a class="xref" href="#jpa_overview_em_lifecycle" title="2.&nbsp; Entity Lifecycle Management">Section&nbsp;2, &#8220;
Entity Lifecycle Management
&#8221;</a>. For now, it is sufficient to
know that detachment has two obvious consequences:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
The detached entity cannot load any additional persistent state.
</p>
</li><li class="listitem">
<p>
The <code class="classname">EntityManager</code> will not return the detached entity
from <code class="methodname">find</code>, nor will queries include the detached
entity in their results. Instead, <code class="methodname">find</code> method
invocations and query executions that would normally incorporate the detached
entity will create a new managed entity with the same identity.
</p>
</li></ol></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA offers several features related to detaching entities. See
<a class="xref" href="#ref_guide_detach" title="1.&nbsp; Detach and Attach">Section&nbsp;1, &#8220;
Detach and Attach
&#8221;</a> in the Reference Guide.
<a class="xref" href="#ref_guide_detach_graph" title="1.3.&nbsp; Defining the Detached Object Graph">Section&nbsp;1.3, &#8220;
Defining the Detached Object Graph
&#8221;</a> in particular describes how to
use the <code class="literal">DetachState</code> setting to boost the performance of
merging detached entities.
</p>
</div>
<p>
Injected <code class="classname">EntityManager</code>s have a <span class="emphasis"><em>transaction
</em></span> persistence context,
while <code class="classname"> EntityManager</code>s obtained through the
<code class="classname">EntityManagerFactory</code> have an <span class="emphasis"><em>extended
</em></span> persistence context. We describe these persistence context types
below.
</p>
<div class="section" id="jpa_overview_emfactory_perscontext_trans"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;
Transaction Persistence Context
</h3></div></div></div>
<p>
Under the transaction persistence context model, an <code class="classname"> EntityManager
</code> begins a new persistence context with each transaction, and ends
the context when the transaction commits or rolls back. Within the transaction,
entities you retrieve through the <code class="classname">EntityManager</code> or via
<code class="classname">Queries</code> are managed entities. They can access datastore
resources to lazy-load additional persistent state as needed, and only one
entity may exist for any persistent identity.
</p>
<p>
When the transaction completes, all entities lose their association with the
<code class="classname">EntityManager</code> and become detached. Traversing a
persistent field that wasn't already loaded now has undefined results. And using
the <code class="classname"> EntityManager</code> or a <code class="classname">Query</code> to
retrieve additional objects may now create new instances with the same
persistent identities as detached instances.
</p>
<p>
If you use an <code class="classname">EntityManager</code> with a transaction
persistence context model outside of an active transaction, each method
invocation creates a new persistence context, performs the method action, and
ends the persistence context. For example, consider using the <code class="methodname">
EntityManager.find</code> method outside of a transaction. The <code class="classname">
EntityManager</code> will create a temporary persistence context, perform
the find operation, end the persistence context, and return the detached result
object to you. A second call with the same id will return a second detached
object.
</p>
<p>
When the next transaction begins, the <code class="classname">EntityManager</code> will
begin a new persistence context, and will again start returning managed
entities. As you'll see in <a class="xref" href="#jpa_overview_em" title="Chapter&nbsp;8.&nbsp; EntityManager">Chapter&nbsp;8, <i>
EntityManager
</i></a>, you can
also merge the previously-detached entities back into the new persistence
context.
</p>
<div class="example" id="jpa_overview_emfactory_perscontext_transex"><p class="title"><b>Example&nbsp;7.1.&nbsp;
Behavior of Transaction Persistence Context
</b></p><div class="example-contents">
<p>
The following code illustrates the behavior of entities under an <code class="classname">
EntityManager</code> using a transaction persistence context.
</p>
<pre class="programlisting">
EntityManager em; // injected
...
// outside a transaction:
// each operation occurs in a separate persistence context, and returns
// a new detached instance
Magazine mag1 = em.find(Magazine.class, magId);
Magazine mag2 = em.find(Magazine.class, magId);
assertTrue(mag2 != mag1);
...
// transaction begins:
// within a transaction, a subsequent lookup doesn't return any of the
// detached objects. however, two lookups within the same transaction
// return the same instance, because the persistence context spans the
// transaction
Magazine mag3 = em.find(Magazine.class, magId);
assertTrue(mag3 != mag1 &amp;&amp; mag3 != mag2);
Magazine mag4 = em.find(Magazine.class, magId);
assertTrue(mag4 == mag3);
...
// transaction commits:
// once again, each operation returns a new instance
Magazine mag5 = em.find(Magazine.class, magId);
assertTrue(mag5 != mag3);
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_emfactory_perscontext_extend"><div class="titlepage"><div><div><h3 class="title">3.2.&nbsp;
Extended Persistence Context
</h3></div></div></div>
<p>
An <code class="classname">EntityManager</code> using an extended persistence context
maintains the same persistence context for its entire lifecycle. Whether inside
a transaction or not, all entities returned from the <code class="classname">EntityManager
</code> are managed, and the <code class="classname">EntityManager</code> never
creates two entity instances to represent the same persistent identity. Entities
only become detached when you finally close the <code class="classname">EntityManager
</code> (or when they are serialized).
</p>
<div class="example" id="jpa_overview_emfactory_perscontext_extendex"><p class="title"><b>Example&nbsp;7.2.&nbsp;
Behavior of Extended Persistence Context
</b></p><div class="example-contents">
<p>
The following code illustrates the behavior of entities under an <code class="classname">
EntityManager</code> using an extended persistence context.
</p>
<pre class="programlisting">
EntityManagerFactory emf = ...
EntityManager em = emf.createEntityManager();
// persistence context active for entire life of EM, so only one entity
// for a given persistent identity
Magazine mag1 = em.find(Magazine.class, magId);
Magazine mag2 = em.find(Magazine.class, magId);
assertTrue(mag2 == mag1);
em.getTransaction().begin();
// same persistence context active within the transaction
Magazine mag3 = em.find(Magazine.class, magId);
assertTrue(mag3 == mag1);
Magazine mag4 = em.find(Magazine.class, magId);
assertTrue(mag4 == mag1);
em.getTransaction.commit();
// when the transaction commits, instance still managed
Magazine mag5 = em.find(Magazine.class, magId);
assertTrue(mag5 == mag1);
// instance finally becomes detached when EM closes
em.close();
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="jpa_overview_emf_properties"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Retrieving Properties Information
</h2></div></div></div>
<a class="indexterm" name="d5e2251"></a>
<p>
There are two sets of properties that may be specified: those that
are specific to OpenJPA and those that have been defined by the JPA
specification. In some cases, two properties may be equivalent, but
have different keys. For example, <span class="emphasis"><em>openjpa.LockTimeout
</em></span> and <span class="emphasis"><em>javax.persistence.lock.timeout</em></span>
are two different keys for the same property.
</p>
<p>
There are two methods that can be used to retrieve information related to
properties:
</p><pre class="programlisting">
public Map&lt;String,Object&gt; getProperties();
public Set&lt;String&gt; getSupportedProperties();
</pre><p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="methodname">getProperties</code> - Provides a list of current
properties. If a property has more than one key, the key
that will be returned is the one that was used when the
property was set. If the property was not explicitly
set, the key defined by the JPA specification will be returned
with the default value.
</p>
</li><li class="listitem">
<p>
<code class="methodname">getSupportedProperties</code> - Returns a set of
supported property keys. This includes keys defined by the JPA
specification as well as keys specific to OpenJPA.
If a property
has more than one key, all possible keys will be returned.
</p>
</li></ul></div><p>
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
The <code class="methodname">getSupportedProperties</code> method is an OpenJPA
extension to the JPA specification.
</p>
</div>
</div>
<div class="section" id="jpa_overview_emfactory_close"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Closing the EntityManagerFactory
</h2></div></div></div>
<a class="indexterm" name="d5e2271"></a>
<pre class="programlisting">
public boolean isOpen();
public void close();
</pre>
<p>
<code class="classname">EntityManagerFactory</code> instances are heavyweight objects.
Each factory might maintain a metadata cache, object state cache, <code class="classname">
EntityManager</code> pool, connection pool, and more. If your application
no longer needs an <code class="classname">EntityManagerFactory</code>, you should
close it to free these resources. When an <code class="classname">EntityManagerFactory
</code> closes, all <code class="classname">EntityManager</code>s from that
factory, and by extension all entities managed by those <code class="classname">
EntityManager</code>s, become invalid. Attempting to close an <code class="classname">
EntityManagerFactory</code> while one or more of its <code class="classname">
EntityManager</code>s has an active transaction may result in an
<code class="classname">IllegalStateException</code>.
</p>
<p>
Closing an <code class="classname">EntityManagerFactory</code> should not be taken
lightly. It is much better to keep a factory open for a long period of time than
to repeatedly create and close new factories. Thus, most applications will never
close the factory, or only close it when the application is exiting. Only
applications that require multiple factories with different configurations have
an obvious reason to create and close multiple <code class="classname">EntityManagerFactory
</code> instances. Once a factory is closed, all methods except
<code class="methodname">isOpen</code> throw an <code class="classname">
IllegalStateException</code>.
</p>
</div>
<div class="section" id="jpa_overview_emfactory_puutil"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
PersistenceUnitUtil
</h2></div></div></div>
<a class="indexterm" name="d5e2292"></a>
<pre class="programlisting">
public PersistenceUnitUtil getPersistenceUnitUtil();
</pre>
<p>
The <code class="classname">EntityManagerFactory</code> method
<code class="methodname">getPersistenceUnitUtil</code> provides access to a
<code class="classname">PersistenceUnitUtil</code> utility. <code class="classname">PersistenceUnitUtil</code>
can be used to obtain the identity of a managed object and determine the load
state of the entity or one of its attributes. If the object is not
managed by one of the entity managers created from the entity manager factory
from which the utility was obtained, the <code class="methodname">getIdentifier</code> method will
return null and the <code class="methodname">isLoaded</code> methods will return false.
</p><pre class="programlisting">
EntityManagerFactory emf = Persistence.createEntityManagerFactory();
PersistenceUnitUtil puUtil = emf.getPersistenceUnitUtil();
if (puUtil.getIdentifier(deptEntity) == null) {
throw new Exception("Identity is not valid.");
}
if (!puUtil.isLoaded(deptEntity, "employees")) {
throw new Exception("Employees not loaded.");
}
</pre><p>
</p>
</div>
</div>
<div class="chapter" id="jpa_overview_em"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;8.&nbsp;
EntityManager
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_em_trans">1.
Transaction Association
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_lifecycle">2.
Entity Lifecycle Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_lifeexamples">3.
Lifecycle Examples
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_identity">4.
Entity Identity Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_cache">5.
Cache Management
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_query">6.
Query Factory
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_locking">7.
Entity Locking
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_properties">8.
Retrieving Properties Information
</a></span></dt><dt><span class="section"><a href="#jpa_overview_em_closing">9.
Closing
</a></span></dt></dl></div>
<a class="indexterm" name="d5e2306"></a>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="189"><tr><td><img src="img/entitymanager.png"></td></tr></table></div>
<p>
The diagram above presents an overview of the <code class="classname">EntityManager
</code> interface. For a complete treatment of the <code class="classname">
EntityManager</code> API, see the
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/EntityManager.html" target="_top">
Javadoc</a> documentation. Methods whose parameter signatures consist of
an ellipsis (...) are overloaded to take multiple parameter types.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA extends the standard <code class="classname">EntityManager</code> interface with
the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.OpenJPAEntityManager</code>
</a> interface to provide additional functionality.
</p>
</div>
<p>
The <code class="classname">EntityManager</code> is the primary interface used by
application developers to interact with the JPA runtime. The methods
of the <code class="classname">EntityManager</code> can be divided into the following
functional categories:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="classname">Transaction</code> association.
</p>
</li><li class="listitem">
<p>
Entity lifecycle management.
</p>
</li><li class="listitem">
<p>
Entity identity management.
</p>
</li><li class="listitem">
<p>
Cache management.
</p>
</li><li class="listitem">
<p>
<code class="classname">Query</code> factory.
</p>
</li><li class="listitem">
<p>
Entity locking.
</p>
</li><li class="listitem">
<p>
Closing.
</p>
</li></ul></div>
<div class="section" id="jpa_overview_em_trans"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Transaction Association
</h2></div></div></div>
<a class="indexterm" name="d5e2342"></a>
<a class="indexterm" name="d5e2346"></a>
<pre class="programlisting">
public EntityTransaction getTransaction();
</pre>
<p>
Every <code class="classname">EntityManager</code> has a one-to-one relation with an
<a class="link" href="#jpa_overview_trans" title="Chapter&nbsp;9.&nbsp; Transaction"><code class="classname">EntityTransaction</code>
</a> instance. In fact, many vendors use a single class to implement both the
<code class="classname">EntityManager</code> and <code class="classname">EntityTransaction
</code> interfaces. If your application requires multiple concurrent
transactions, you will use multiple <code class="classname">EntityManager</code>s.
</p>
<p>
You can retrieve the <code class="classname">EntityTransaction</code> associated with an
<code class="classname">EntityManager</code> through the <code class="methodname">getTransaction
</code> method. Note that most JPA implementations can
integrate with an application server's managed transactions. If you take
advantage of this feature, you will control transactions by declarative
demarcation or through the Java Transaction API (JTA) rather than through the
<code class="classname">EntityTransaction</code>.
</p>
</div>
<div class="section" id="jpa_overview_em_lifecycle"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Entity Lifecycle Management
</h2></div></div></div>
<a class="indexterm" name="d5e2364"></a>
<p>
<code class="classname">EntityManager</code>s perform several actions that affect the
lifecycle state of entity instances.
</p>
<pre class="programlisting">
public void persist(Object entity);
</pre>
<p>
<a class="indexterm" name="d5e2371"></a>
<a class="indexterm" name="d5e2374"></a>
<a class="indexterm" name="d5e2377"></a>
Transitions new instances to managed. On the next flush or commit, the newly
persisted instances will be inserted into the datastore.
</p>
<p>
For a given entity <code class="literal">A</code>, the <code class="methodname">persist</code>
method behaves as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
If <code class="literal">A</code> is a new entity, it becomes managed.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is an existing managed entity, it is ignored. However,
the persist operation cascades as defined below.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a removed entity, it becomes managed.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a detached entity, an <code class="classname">
IllegalArgumentException</code> is thrown.
</p>
</li><li class="listitem">
<p>
The persist operation recurses on all relation fields of <code class="literal">A</code>
whose <a class="link" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">cascades</a> include
<code class="literal">CascadeType.PERSIST</code>.
</p>
</li></ul></div>
<p>
This action can only be used in the context of an active transaction.
</p>
<pre class="programlisting">
public void remove(Object entity);
</pre>
<p>
<a class="indexterm" name="d5e2405"></a>
<a class="indexterm" name="d5e2408"></a>
<a class="indexterm" name="d5e2411"></a>
Transitions managed instances to removed. The instances will be deleted from the
datastore on the next flush or commit. Accessing a removed entity has undefined
results.
</p>
<p>
For a given entity <code class="literal">A</code>, the <code class="methodname">remove</code>
method behaves as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
If <code class="literal">A</code> is a new entity, it is ignored. However, the remove
operation cascades as defined below.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is an existing managed entity, it becomes removed.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a removed entity, it is ignored.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a detached entity, an <code class="classname">
IllegalArgumentException</code> is thrown.
</p>
</li><li class="listitem">
<p>
The remove operation recurses on all relation fields of <code class="literal">A</code>
whose <a class="link" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">cascades</a> include
<code class="literal">CascadeType.REMOVE</code>.
</p>
</li></ul></div>
<p>
This action can only be used in the context of an active transaction.
</p>
<pre class="programlisting">
public void refresh(Object entity);
</pre>
<p>
<a class="indexterm" name="d5e2439"></a>
<a class="indexterm" name="d5e2442"></a>
<a class="indexterm" name="d5e2445"></a>
<a class="indexterm" name="d5e2448"></a>
Use the <code class="methodname">refresh</code> action to make sure the persistent
state of an instance is synchronized with the values in the datastore.
<code class="methodname">refresh</code> is intended for long-running optimistic
transactions in which there is a danger of seeing stale data.
</p>
<p>
For a given entity <code class="literal">A</code>, the <code class="methodname">refresh</code>
method behaves as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
If <code class="literal">A</code> is a new entity, it is ignored. However, the refresh
operation cascades as defined below.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is an existing managed entity, its state is refreshed
from the datastore.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a removed entity, it is ignored.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a detached entity, an <code class="classname">
IllegalArgumentException</code> is thrown.
</p>
</li><li class="listitem">
<p>
The refresh operation recurses on all relation fields of <code class="literal">A</code>
whose <a class="link" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">cascades</a> include
<code class="literal">CascadeType.REFRESH</code>.
</p>
</li></ul></div>
<pre class="programlisting">
public Object merge(Object entity);
</pre>
<p>
<a class="indexterm" name="d5e2477"></a>
<a class="indexterm" name="d5e2481"></a>
<a class="indexterm" name="d5e2484"></a>
<a class="indexterm" name="d5e2487"></a>
<a class="indexterm" name="d5e2489"></a>
A common use case for an application running in a servlet or application server
is to "detach" objects from all server resources, modify them, and then "attach"
them again. For example, a servlet might store persistent data in a user session
between a modification based on a series of web forms. Between each form
request, the web container might decide to serialize the session, requiring that
the stored persistent state be disassociated from any other resources.
Similarly, a client/server application might transfer persistent objects to a
client via serialization, allow the client to modify their state, and then have
the client return the modified data in order to be saved. This is sometimes
referred to as the <span class="emphasis"><em>data transfer object</em></span> or <span class="emphasis"><em>value
object</em></span> pattern, and it allows fine-grained manipulation of data
objects without incurring the overhead of multiple remote method invocations.
</p>
<p>
JPA provides support for this pattern by automatically detaching
entities when they are serialized or when a persistence context ends (see
<a class="xref" href="#jpa_overview_emfactory_perscontext" title="3.&nbsp; Persistence Context">Section&nbsp;3, &#8220;
Persistence Context
&#8221;</a> for an exploration of
persistence contexts). The JPA <span class="emphasis"><em>merge</em></span> API
re-attaches detached entities. This allows you to detach a persistent instance,
modify the detached instance offline, and merge the instance back into an
<code class="classname">EntityManager</code> (either the same one that detached the
instance, or a new one). The changes will then be applied to the existing
instance from the datastore.
</p>
<p>
A detached entity maintains its persistent identity, but cannot load additional
state from the datastore. Accessing any persistent field or property that was
not loaded at the time of detachment has undefined results. Also, be sure not to
alter the version or identity fields of detached instances if you plan on
merging them later.
</p>
<p>
The <code class="methodname">merge</code> method returns a managed copy of the given
detached entity. Changes made to the persistent state of the detached entity are
applied to this managed instance. Because merging involves changing persistent
state, you can only merge within a transaction.
</p>
<p>
If you attempt to merge an instance whose representation has changed in the
datastore since detachment, the merge operation will throw an exception, or the
transaction in which you perform the merge will fail on commit, just as if a
normal optimistic conflict were detected.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA offers enhancements to JPA detachment functionality,
including additional options to control which fields are detached. See
<a class="xref" href="#ref_guide_detach" title="1.&nbsp; Detach and Attach">Section&nbsp;1, &#8220;
Detach and Attach
&#8221;</a> in the Reference Guide for details.
</p>
</div>
<p>
For a given entity <code class="literal">A</code>, the <code class="methodname">merge</code>
method behaves as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
If <code class="literal">A</code> is a detached entity, its state is copied into existing
managed instance <code class="literal">A'</code> of the same entity identity, or a new
managed copy of <code class="literal">A</code> is created.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a new entity, a new managed entity <code class="literal">A'
</code> is created and the state of <code class="literal">A</code> is copied into
<code class="literal">A'</code>.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is an existing managed entity, it is ignored. However,
the merge operation still cascades as defined below.
</p>
</li><li class="listitem">
<p>
If <code class="literal">A</code> is a removed entity, an <code class="classname">
IllegalArgumentException</code> is thrown.
</p>
</li><li class="listitem">
<p>
The merge operation recurses on all relation fields of <code class="literal">A</code>
whose <a class="link" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">cascades</a> include
<code class="literal">CascadeType.MERGE</code>.
</p>
</li></ul></div>
<p>
The following diagram illustrates the lifecycle of an entity with respect to the
APIs presented in this section.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="297"><tr><td><img src="img/jpa-state-transitions.png"></td></tr></table></div>
</div>
<div class="section" id="jpa_overview_em_lifeexamples"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Lifecycle Examples
</h2></div></div></div>
<p>
The examples below demonstrate how to use the lifecycle methods presented in the
previous section. The examples are appropriate for out-of-container use. Within
a container, <code class="classname"> EntityManager</code>s are usually injected, and
transactions are usually managed. You would therefore omit the <code class="methodname">
createEntityManager</code> and <code class="methodname">close</code> calls, as
well as all transaction demarcation code.
</p>
<div class="example" id="jpa_overview_em_lifecycle_persist"><p class="title"><b>Example&nbsp;8.1.&nbsp;
Persisting Objects
</b></p><div class="example-contents">
<a class="indexterm" name="d5e2543"></a>
<pre class="programlisting">
// create some objects
Magazine mag = new Magazine("1B78-YU9L", "JavaWorld");
Company pub = new Company("Weston House");
pub.setRevenue(1750000D);
mag.setPublisher(pub);
pub.addMagazine(mag);
Article art = new Article("JPA Rules!", "Transparent Object Persistence");
art.addAuthor(new Author("Fred", "Hoyle"));
mag.addArticle(art);
// persist
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(mag);
em.persist(pub);
em.persist(art);
em.getTransaction().commit();
// or we could continue using the EntityManager...
em.close();
</pre>
</div></div><br class="example-break">
<div class="example" id="jpa_overview_em_lifecycle_update"><p class="title"><b>Example&nbsp;8.2.&nbsp;
Updating Objects
</b></p><div class="example-contents">
<a class="indexterm" name="d5e2550"></a>
<pre class="programlisting">
Magazine.MagazineId mi = new Magazine.MagazineId();
mi.isbn = "1B78-YU9L";
mi.title = "JavaWorld";
// updates should always be made within transactions; note that
// there is no code explicitly linking the magazine or company
// with the transaction; JPA automatically tracks all changes
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Magazine mag = em.find(Magazine.class, mi);
mag.setPrice(5.99);
Company pub = mag.getPublisher();
pub.setRevenue(1750000D);
em.getTransaction().commit();
// or we could continue using the EntityManager...
em.close();
</pre>
</div></div><br class="example-break">
<div class="example" id="jpa_overview_em_lifecycle_delete"><p class="title"><b>Example&nbsp;8.3.&nbsp;
Removing Objects
</b></p><div class="example-contents">
<a class="indexterm" name="d5e2557"></a>
<pre class="programlisting">
// assume we have an object id for the company whose subscriptions
// we want to delete
Object oid = ...;
// deletes should always be made within transactions
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Company pub = (Company) em.find(Company.class, oid);
for (Subscription sub : pub.getSubscriptions())
em.remove(sub);
pub.getSubscriptions().clear();
em.getTransaction().commit();
// or we could continue using the EntityManager...
em.close();
</pre>
</div></div><br class="example-break">
<div class="example" id="jpa_overview_em_detachex"><p class="title"><b>Example&nbsp;8.4.&nbsp;
Detaching and Merging
</b></p><div class="example-contents">
<p>
This example demonstrates a common client/server scenario. The client requests
objects and makes changes to them, while the server handles the object lookups
and transactions.
</p>
<pre class="programlisting">
// CLIENT:
// requests an object with a given oid
Record detached = (Record) getFromServer(oid);
...
// SERVER:
// send object to client; object detaches on EM close
Object oid = processClientRequest();
EntityManager em = emf.createEntityManager();
Record record = em.find(Record.class, oid);
em.close();
sendToClient(record);
...
// CLIENT:
// makes some modifications and sends back to server
detached.setSomeField("bar");
sendToServer(detached);
...
// SERVER:
// merges the instance and commit the changes
Record modified = (Record) processClientRequest();
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Record merged = (Record) em.merge(modified);
merged.setLastModified(System.currentTimeMillis());
merged.setModifier(getClientIdentityCode());
em.getTransaction().commit();
em.close();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_em_identity"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Entity Identity Management
</h2></div></div></div>
<p>
Each <code class="classname">EntityManager</code> is responsible for managing the
persistent identities of the managed objects in the persistence context. The
following methods allow you to interact with the management of persistent
identities. The behavior of these methods is deeply affected by the persistence
context type of the <code class="classname">EntityManager</code>; see
<a class="xref" href="#jpa_overview_emfactory_perscontext" title="3.&nbsp; Persistence Context">Section&nbsp;3, &#8220;
Persistence Context
&#8221;</a> for an explanation of
persistence contexts.
</p>
<pre class="programlisting">
public &lt;T&gt; T find(Class&lt;T&gt; cls, Object oid);
</pre>
<p>
<a class="indexterm" name="d5e2574"></a>
<a class="indexterm" name="d5e2578"></a>
<a class="indexterm" name="d5e2581"></a>
This method returns the persistent instance of the given type with the given
persistent identity. If the instance is already present in the current
persistence context, the cached version will be returned. Otherwise, a new
instance will be constructed and loaded with state from the datastore. If no
entity with the given type and identity exists in the datastore, this method
returns null.
</p>
<pre class="programlisting">
public &lt;T&gt; T getReference(Class&lt;T&gt; cls, Object oid);
</pre>
<p>
<a class="indexterm" name="d5e2586"></a>
<a class="indexterm" name="d5e2590"></a>
<a class="indexterm" name="d5e2593"></a>
<a class="indexterm" name="d5e2596"></a>
This method is similar to <code class="methodname">find</code>, but does not
necessarily go to the database when the entity is not found in cache. The
implementation may construct a <span class="emphasis"><em>hollow</em></span> entity and return it
to you instead. Hollow entities do not have any state loaded. The state only
gets loaded when you attempt to access a persistent field. At that time, the
implementation may throw an <code class="classname">EntityNotFoundException</code> if it
discovers that the entity does not exist in the datastore. The implementation
may also throw an <code class="classname">EntityNotFoundException</code> from the
<code class="methodname">getReference</code> method itself. Unlike <code class="methodname">
find</code>, <code class="methodname">getReference</code> does not return null.
</p>
<pre class="programlisting">
public boolean contains(Object entity);
</pre>
<p>
<a class="indexterm" name="d5e2607"></a>
<a class="indexterm" name="d5e2610"></a>
Returns true if the given entity is part of the current persistence context, and
false otherwise. Removed entities are not considered part of the current
persistence context.
</p>
</div>
<div class="section" id="jpa_overview_em_cache"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Cache Management
</h2></div></div></div>
<a class="indexterm" name="d5e2615"></a>
<pre class="programlisting">
public void flush();
</pre>
<p>
<a class="indexterm" name="d5e2620"></a>
<a class="indexterm" name="d5e2623"></a>
<a class="indexterm" name="d5e2626"></a>
The <code class="methodname">flush</code> method writes any changes that have been made
in the current transaction to the datastore. If the <code class="classname">EntityManager
</code> does not already have a connection to the datastore, it obtains one
for the flush and retains it for the duration of the transaction. Any exceptions
during flush cause the transaction to be marked for rollback. See
<a class="xref" href="#jpa_overview_trans" title="Chapter&nbsp;9.&nbsp; Transaction">Chapter&nbsp;9, <i>
Transaction
</i></a>.
</p>
<p>
Flushing requires an active transaction. If there isn't a transaction in
progress, the <code class="methodname">flush</code> method throws a <code class="classname">
TransactionRequiredException</code>.
</p>
<pre class="programlisting">
public FlushModeType getFlushMode();
public void setFlushMode(FlushModeType flushMode);
</pre>
<p>
<a class="indexterm" name="d5e2637"></a>
<a class="indexterm" name="d5e2640"></a>
The <code class="classname">EntityManager</code>'s <code class="literal">FlushMode</code> property
controls whether to flush transactional changes before executing queries. This
allows the query results to take into account changes you have made during the
current transaction. Available
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/FlushModeType.html" target="_top">
<code class="classname">javax.persistence.FlushModeType</code></a> constants are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">COMMIT</code>: Only flush when committing, or when told to do so
through the <code class="methodname">flush</code> method. Query results may not take
into account changes made in the current transaction.
</p>
</li><li class="listitem">
<p>
<code class="literal">AUTO</code>: The implementation is permitted to flush before
queries to ensure that the results reflect the most recent object state.
</p>
</li></ul></div>
<p>
You can also set the flush mode on individual
<a class="link" href="#jpa_overview_query" title="Chapter&nbsp;10.&nbsp; JPA Query"><code class="classname">Query</code></a>
instances.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA only flushes before a query if the query might be affected by data
changed in the current transaction. Additionally, OpenJPA allows fine-grained
control over flushing behavior. See the Reference Guide's
<a class="xref" href="#ref_guide_dbsetup_retain" title="8.&nbsp; Configuring the Use of JDBC Connections">Section&nbsp;8, &#8220;
Configuring the Use of JDBC Connections
&#8221;</a>.
</p>
</div>
<pre class="programlisting">
public void clear();
</pre>
<p>
<a class="indexterm" name="d5e2662"></a>
<a class="indexterm" name="d5e2665"></a>
Clearing the <code class="classname">EntityManager</code> effectively ends the
persistence context. All entities managed by the <code class="classname">EntityManager
</code> become detached.
</p>
</div>
<div class="section" id="jpa_overview_em_query"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
Query Factory
</h2></div></div></div>
<a class="indexterm" name="d5e2672"></a>
<a class="indexterm" name="d5e2676"></a>
<pre class="programlisting">
public Query createQuery(String query);
</pre>
<p>
<code class="classname">Query</code> objects are used to find entities matching certain
criteria. The <code class="methodname">createQuery</code> method creates a query using
the given Java Persistence Query Language (JPQL) string. See
<a class="xref" href="#jpa_overview_query" title="Chapter&nbsp;10.&nbsp; JPA Query">Chapter&nbsp;10, <i>
JPA Query
</i></a> for details.
</p>
<pre class="programlisting">
public Query createNamedQuery(String name);
</pre>
<p>
This method retrieves a query defined in metadata by name. The returned
<code class="classname">Query</code> instance is initialized with the information
declared in metadata. For more information on named queries, read
<a class="xref" href="#jpa_overview_query_named" title="1.11.&nbsp; Named Queries">Section&nbsp;1.11, &#8220;
Named Queries
&#8221;</a>.
</p>
<pre class="programlisting">
public Query createNativeQuery(String sql);
public Query createNativeQuery(String sql, Class resultCls);
public Query createNativeQuery(String sql, String resultMapping);
</pre>
<p>
<span class="emphasis"><em>Native</em></span> queries are queries in the datastore's native
language. For relational databases, this is the Structured Query Language (SQL).
<a class="xref" href="#jpa_overview_sqlquery" title="Chapter&nbsp;12.&nbsp; SQL Queries">Chapter&nbsp;12, <i>
SQL Queries
</i></a> elaborates on JPA's
native query support.
</p>
</div>
<div class="section" id="jpa_overview_em_locking"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
Entity Locking
</h2></div></div></div>
<a class="indexterm" name="d5e2694"></a>
<p>
In the area of concurrency control, the JPA specification supports
optimistic and pessimistic locking.
</p>
<pre class="programlisting">
public void lock(Object entity, LockModeType mode);
</pre>
<p>
<a class="indexterm" name="d5e2700"></a>
<a class="indexterm" name="d5e2703"></a>
This method locks the given entity using the named mode. The
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/LockModeType.html" target="_top">
<code class="classname">javax.persistence.LockModeType</code></a> enum defines eight
modes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">OPTIMISTIC</code>: Optimistic locking.
</p>
</li><li class="listitem">
<p>
<code class="literal">OPTIMISTIC_FORCE_INCREMENT</code>: Optimistic locking.
When a transaction is committed, the entity's version column
will be incremented even if the entity's state did not change in the transaction.
</p>
</li><li class="listitem">
<p>
<code class="literal">PESSIMISTIC_READ</code>: Pessimistic locking. Other transactions
may concurrently read the entity, but cannot concurrently update it.
</p>
</li><li class="listitem">
<p>
<code class="literal">PESSIMISTIC_WRITE</code>: Pessimistic locking. Other transactions
cannot concurrently read or write the entity.
</p>
</li><li class="listitem">
<p>
<code class="literal">PESSIMISTIC_FORCE_INCREMENT</code>: Pessimistic locking. Other transactions
cannot concurrently read or write the entity.
When a transaction is committed, the entity's version column
will be incremented even if the entity's state did not change in the transaction.
</p>
</li><li class="listitem">
<p>
<code class="literal">READ</code>: A synonym for <code class="literal">OPTIMISTIC</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">WRITE</code>: A synonym for <code class="literal">OPTIMISTIC_FORCE_INCREMENT</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">NONE</code>: No locking is performed.
</p>
</li></ul></div>
<p>
Entities can also be locked at the time when entity state gets loaded from the datastore.
This is achieved by supplying a lock mode to the respective versions of
<code class="methodname">find</code> and <code class="methodname">refresh</code> methods.
If an entity state is to be loaded by a query, a lock mode can be passed to the
<code class="methodname">Query.setLockMode</code> and <code class="methodname">TypedQuery.setLockMode</code>
methods.
</p>
<pre class="programlisting">
public LockModeType getLockMode(Object entity);
</pre>
<p>
Returns the lock mode currently held by the given entity.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
OpenJPA differentiates between <code class="literal">PESSIMISTIC_READ</code> and
<code class="literal">PESSIMISTIC_WRITE</code> lock modes only with DB2 databases.
While running with other databases, there is no distinction between these
two modes because
<code class="literal">PESSIMISTIC_READ</code> lock mode
is upgraded to <code class="literal">PESSIMISTIC_WRITE</code>.
</p>
</li><li class="listitem">
<p>
OpenJPA has additional APIs for controlling entity locking. See
<a class="xref" href="#ref_guide_locking" title="3.&nbsp; Object Locking">Section&nbsp;3, &#8220;
Object Locking
&#8221;</a> in the Reference Guide for details.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="jpa_overview_em_properties"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;
Retrieving Properties Information
</h2></div></div></div>
<a class="indexterm" name="d5e2755"></a>
<p>
There are two sets of properties that may be specified: those that
are specific to OpenJPA and those that have been defined by the JPA
specification. In some cases, two properties may be equivalent, but
have different keys. For example, <span class="emphasis"><em>openjpa.LockTimeout
</em></span> and <span class="emphasis"><em>javax.persistence.lock.timeout</em></span>
are two different keys for the same property.
</p>
<p>
There are two methods that can be used to retrieve information related to
properties:
</p><pre class="programlisting">
public Map&lt;String,Object&gt; getProperties();
public Set&lt;String&gt; getSupportedProperties();
</pre><p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="methodname">getProperties</code> - Provides a list of current
properties. If a property has more than one key, the key
that will be returned is the one that was used when the
property was set. If the property was not explicitly
set, the key defined by the JPA specification will be returned
with the default value.
</p>
</li><li class="listitem">
<p>
<code class="methodname">getSupportedProperties</code> - Returns a set of
supported property keys. This includes keys defined by the JPA
specification as well as keys specific to OpenJPA.
If a property
has more than one key, all possible keys will be returned.
</p>
</li></ul></div><p>
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
The <code class="methodname">getSupportedProperties</code> method is an OpenJPA
extension to the JPA specification.
</p>
</div>
</div>
<div class="section" id="jpa_overview_em_closing"><div class="titlepage"><div><div><h2 class="title" style="clear: both">9.&nbsp;
Closing
</h2></div></div></div>
<a class="indexterm" name="d5e2775"></a>
<pre class="programlisting">
public boolean isOpen();
public void close();
</pre>
<p>
When an <code class="classname">EntityManager</code> is no longer needed, you should
call its <code class="methodname">close</code> method. Closing an <code class="classname">
EntityManager</code> releases any resources it is using. The persistence
context ends, and the entities managed by the <code class="classname">EntityManager
</code> become detached. Any <code class="classname">Query</code> instances the
<code class="classname">EntityManager</code> created become invalid. Calling any method
other than <code class="methodname">isOpen</code> on a closed <code class="classname">EntityManager
</code> results in an <code class="classname">IllegalStateException</code>. You
cannot close a <code class="classname">EntityManager</code> that is in the middle of a
transaction.
</p>
<p>
If you are in a managed environment using injected entity managers, you should
not close them.
</p>
</div>
</div>
<div class="chapter" id="jpa_overview_trans"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;9.&nbsp;
Transaction
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_trans_types">1.
Transaction Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_trans_local">2.
The EntityTransaction Interface
</a></span></dt></dl></div>
<a class="indexterm" name="d5e2793"></a>
<p>
Transactions are critical to maintaining data integrity. They are used to group
operations into units of work that act in an all-or-nothing fashion.
Transactions have the following qualities:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e2800"></a>
<a class="indexterm" name="d5e2803"></a>
<span class="emphasis"><em>Atomicity</em></span>. Atomicity refers to the all-or-nothing property
of transactions. Either every data update in the transaction completes
successfully, or they all fail, leaving the datastore in its original state. A
transaction cannot be only partially successful.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e2809"></a>
<a class="indexterm" name="d5e2812"></a>
<span class="emphasis"><em>Consistency</em></span>. Each transaction takes the datastore from one
consistent state to another consistent state.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e2818"></a>
<a class="indexterm" name="d5e2821"></a>
<span class="emphasis"><em>Isolation</em></span>. Transactions are isolated from each other. When
you are reading persistent data in one transaction, you cannot "see" the changes
that are being made to that data in other transactions. Similarly, the updates
you make in one transaction cannot conflict with updates made in concurrent
transactions. The form of conflict resolution employed depends on whether you
are using pessimistic or optimistic transactions. Both types are described later
in this chapter.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e2827"></a>
<a class="indexterm" name="d5e2830"></a>
<span class="emphasis"><em>Durability</em></span>. The effects of successful transactions are
durable; the updates made to persistent data last for the lifetime of the
datastore.
</p>
</li></ul></div>
<p>
<a class="indexterm" name="d5e2835"></a>
<a class="indexterm" name="d5e2838"></a>
Together, these qualities are called the ACID properties of transactions. To
understand why these properties are so important to maintaining data integrity,
consider the following example:
</p>
<p>
Suppose you create an application to manage bank accounts. The application
includes a method to transfer funds from one user to another, and it looks
something like this:
</p>
<pre class="programlisting">
public void transferFunds(User from, User to, double amnt) {
from.decrementAccount(amnt);
to.incrementAccount(amnt);
}
</pre>
<p>
Now suppose that user Alice wants to transfer 100 dollars to user Bob. No
problem; you simply invoke your <code class="methodname">transferFunds</code> method,
supplying Alice in the <code class="literal">from</code> parameter, Bob in the <code class="literal">
to</code> parameter, and <code class="literal">100.00</code> as the <code class="literal">amnt
</code>. The first line of the method is executed, and 100 dollars is
subtracted from Alice's account. But then, something goes wrong. An unexpected
exception occurs, or the hardware fails, and your method never completes.
</p>
<p>
You are left with a situation in which the 100 dollars has simply disappeared.
Thanks to the first line of your method, it is no longer in Alice's account, and
yet it was never transferred to Bob's account either. The datastore is in an
inconsistent state.
</p>
<p>
The importance of transactions should now be clear. If the two lines of the
<code class="methodname">transferFunds</code> method had been placed together in a
transaction, it would be impossible for only the first line to succeed. Either
the funds would be transferred properly or they would not be transferred at all,
and an exception would be thrown. Money could never vanish into thin air, and
the data store could never get into an inconsistent state.
</p>
<div class="section" id="jpa_overview_trans_types"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Transaction Types
</h2></div></div></div>
<a class="indexterm" name="d5e2854"></a>
<p>
There are two major types of transactions: pessimistic transactions and
optimistic transactions. Each type has both advantages and disadvantages.
</p>
<p>
<a class="indexterm" name="d5e2859"></a>
<a class="indexterm" name="d5e2862"></a>
<a class="indexterm" name="d5e2865"></a>
Pessimistic transactions generally lock the datastore records they act on,
preventing other concurrent transactions from using the same data. This avoids
conflicts between transactions, but consumes database resources. Additionally,
locking records can result in <span class="emphasis"><em>deadlock</em></span>, a situation in
which two transactions are both waiting for the other to release its locks
before completing. The results of a deadlock are datastore-dependent; usually
one transaction is forcefully rolled back after some specified timeout interval,
and an exception is thrown.
</p>
<p>
<a class="indexterm" name="d5e2870"></a>
<a class="indexterm" name="d5e2873"></a>
This document will often use the term <span class="emphasis"><em>datastore</em></span> transaction
in place of <span class="emphasis"><em>pessimistic</em></span> transaction. This is to acknowledge
that some datastores do not support pessimistic semantics, and that the exact
meaning of a non-optimistic JPA transaction is dependent on the datastore. Most
of the time, a datastore transaction is equivalent to a pessimistic transaction.
</p>
<p>
<a class="indexterm" name="d5e2879"></a>
<a class="indexterm" name="d5e2882"></a>
Optimistic transactions consume less resources than pessimistic/datastore
transactions, but only at the expense of reliability. Because optimistic
transactions do not lock datastore records, two transactions might change the
same persistent information at the same time, and the conflict will not be
detected until the second transaction attempts to flush or commit. At this time,
the second transaction will realize that another transaction has concurrently
modified the same records (usually through a timestamp or versioning system),
and will throw an appropriate exception. Note that optimistic transactions still
maintain data integrity; they are simply more likely to fail in heavily
concurrent situations.
</p>
<p>
Despite their drawbacks, optimistic transactions are the best choice for most
applications. They offer better performance, better scalability, and lower risk
of hanging due to deadlock.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA uses optimistic semantics by default, but supports both optimistic and
datastore transactions. OpenJPA also offers advanced locking and versioning APIs
for fine-grained control over database resource allocation and object
versioning. See <a class="xref" href="#ref_guide_locking" title="3.&nbsp; Object Locking">Section&nbsp;3, &#8220;
Object Locking
&#8221;</a> of the Reference Guide for
details on locking. <a class="xref" href="#jpa_overview_meta_version" title="2.6.&nbsp; Version">Section&nbsp;2.6, &#8220;
Version
&#8221;</a>
of this document covers standard object versioning, while
<a class="xref" href="#ref_guide_mapping_jpa" title="7.&nbsp; Additional JPA Mappings">Section&nbsp;7, &#8220;
Additional JPA Mappings
&#8221;</a> of the Reference Guide discusses
additional versioning strategies available in OpenJPA.
</p>
</div>
</div>
<div class="section" id="jpa_overview_trans_local"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
The EntityTransaction Interface
</h2></div></div></div>
<a class="indexterm" name="d5e2893"></a>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="129"><tr><td><img src="img/jpa-transaction.png"></td></tr></table></div>
<p>
JPA integrates with your container's <span class="emphasis"><em>managed</em></span> transactions,
allowing you to use the container's declarative transaction demarcation and its
Java Transaction API (JTA) implementation for transaction management. Outside of
a container, though, you must demarcate transactions manually through JPA. The
<code class="classname">EntityTransaction</code> interface controls unmanaged
transactions in JPA.
</p>
<pre class="programlisting">
public void begin();
public void commit();
public void rollback();
</pre>
<p>
<a class="indexterm" name="d5e2904"></a>
<a class="indexterm" name="d5e2907"></a>
<a class="indexterm" name="d5e2910"></a>
<a class="indexterm" name="d5e2913"></a>
<a class="indexterm" name="d5e2916"></a>
The <code class="methodname">begin</code>, <code class="methodname">commit</code>, and
<code class="methodname">rollback</code> methods demarcate transaction boundaries. The
methods should be self-explanatory: <code class="methodname">begin</code> starts a
transaction, <code class="methodname">commit</code> attempts to commit the
transaction's changes to the datastore, and <code class="methodname">rollback</code>
aborts the transaction, in which case the datastore is "rolled back" to its
previous state. JPA implementations will automatically roll back transactions if
any exception is thrown during the commit process.
</p>
<p>
Unless you are using an extended persistence context, committing or rolling back
also ends the persistence context. All managed entities will be detached from the
<code class="classname">EntityManager</code>.
</p>
<pre class="programlisting">
public boolean isActive();
</pre>
<p>
<a class="indexterm" name="d5e2929"></a>
Finally, the <code class="methodname">isActive</code> method returns <code class="literal">true
</code> if the transaction is in progress (<code class="methodname">begin</code>
has been called more recently than <code class="methodname">commit</code> or
<code class="methodname">rollback</code>), and <code class="literal">false</code> otherwise.
</p>
<div class="example" id="jpa_overview_trans_group"><p class="title"><b>Example&nbsp;9.1.&nbsp;
Grouping Operations with Transactions
</b></p><div class="example-contents">
<pre class="programlisting">
public void transferFunds(EntityManager em, User from, User to, double amnt) {
// note: it would be better practice to move the transaction demarcation
// code out of this method, but for the purposes of example...
Transaction trans = em.getTransaction();
trans.begin();
try
{
from.decrementAccount(amnt);
to.incrementAccount(amnt);
trans.commit();
}
catch (RuntimeException re)
{
if (trans.isActive())
trans.rollback(); // or could attempt to fix error and retry
throw re;
}
}
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="chapter" id="jpa_overview_query"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;10.&nbsp;
JPA Query
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_query_api">1.
JPQL API
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_query_basic">1.1.
Query Basics
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_relations">1.2.
Relation Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_embeddables">1.3.
Embeddable Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_join_fetch">1.4.
Fetch Joins
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_functions">1.5.
JPQL Functions
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_inheritance">1.6.
Polymorphic Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_params">1.7.
Query Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_hints">1.8.
Query Hints
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_hints_locking">1.8.1.
Locking Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_locktimeout">1.8.2.
Lock Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_querytimeout">1.8.3.
Query Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_resultset">1.8.4.
Result Set Size Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_isolation">1.8.5.
Isolation Level Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_fetchplan">1.8.6.
Other Fetchplan Hints
</a></span></dt><dt><span class="section"><a href="#d5e3356">1.8.7.
Database-Specific Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_named">1.8.8.
Named Query Hints
</a></span></dt><dt><span class="section"><a href="#multi-hints-handling">1.8.9.
Handling of Multiple Similar Query Hints
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_query_ordering">1.9.
Ordering
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_aggregates">1.10.
Aggregates
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_named">1.11.
Named Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_delete">1.12.
Delete By Query
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_update">1.13.
Update By Query
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref">2.
JPQL Language Reference
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_stmnttypes">2.1.
JPQL Statement Types
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_select">2.1.1.
JPQL Select Statement
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk">2.1.2.
JPQL Update and Delete Statements
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_schematypes">2.2.
JPQL Abstract Schema Types and Query Domains
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_schemanaming">2.2.1.
JPQL Entity Naming
</a></span></dt><dt><span class="section"><a href="#jpa_langref_schemaexample">2.2.2.
JPQL Schema Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_fromclause">2.3.
JPQL FROM Clause and Navigational Declarations
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_from_identifiers">2.3.1.
JPQL FROM Identifiers
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_vars">2.3.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_range">2.3.3.
JPQL Range Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path">2.3.4.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_Joins">2.3.5.
JPQL Joins
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_inner_joins">2.3.5.1.
JPQL Inner Joins (Relationship Joins)
</a></span></dt><dt><span class="section"><a href="#jpa_langref_outer_joins">2.3.5.2.
JPQL Outer Joins
</a></span></dt><dt><span class="section"><a href="#jpa_langref_fetch_joins">2.3.5.3.
JPQL Fetch Joins
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_collection_dec">2.3.6.
JPQL Collection Member Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_clause_and_sql">2.3.7.
JPQL FROM Clause and SQL
</a></span></dt><dt><span class="section"><a href="#jpa_langref_polymorph">2.3.8.
JPQL Polymorphism
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_where">2.4.
JPQL WHERE Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_cond">2.5.
JPQL Conditional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_lit">2.5.1.
JPQL Literals
</a></span></dt><dt><span class="section"><a href="#jpa_langref_idvar">2.5.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path_exp">2.5.3.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_input_params">2.5.4.
JPQL Input Parameters
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_pos_params">2.5.4.1.
JPQL Positional Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_langref_named_params">2.5.4.2.
JPQL Named Parameters
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_cond_comp">2.5.5.
JPQL Conditional Expression Composition
</a></span></dt><dt><span class="section"><a href="#jpa_langref_operators">2.5.6.
JPQL Operators and Operator Precedence
</a></span></dt><dt><span class="section"><a href="#jpa_langref_comparison_expressions">2.5.7.
JPQL Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_between">2.5.8.
JPQL Between Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_in_expressions">2.5.9.
JPQL In Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_like">2.5.10.
JPQL Like Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null">2.5.11.
JPQL Null Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_empty_comp">2.5.12.
JPQL Empty Collection Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_collection_member">2.5.13.
JPQL Collection Member Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_exists">2.5.14.
JPQL Exists Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_all_any">2.5.15.
JPQL All or Any Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_subqueries">2.5.16.
JPQL Subqueries
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_scalar_expressions">2.6.
JPQL Scalar Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_math_expressions">2.6.1.
Arithmetic Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_functional_expressions">2.6.2.
String, Arithmetic, and Datetime Functional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_string_fun">2.6.2.1.
JPQL String Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_arithmetic">2.6.2.2.
JPQL Arithmetic Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_datetime">2.6.2.3.
JPQL Datetime Functions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_case_expressions">2.6.3.
Case Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_entity_type_expressions">2.6.4.
Entity Type Expressions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_group">2.7.
JPQL GROUP BY, HAVING
</a></span></dt><dt><span class="section"><a href="#jpa_langref_select_clause">2.8.
JPQL SELECT Clause
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_resulttype">2.8.1.
JPQL Result Type of the SELECT Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_constructor">2.8.2.
JPQL Constructor Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_select">2.8.3.
JPQL Null Values in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_embeddables">2.8.4.
JPQL Embeddables in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_aggregates">2.8.5.
JPQL Aggregate Functions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_agg_examples">2.8.5.1.
JPQL Aggregate Examples
</a></span></dt><dt><span class="section"><a href="#jpa_langref_numeric_expressions_in_select">2.8.5.2.
JPQL Numeric Expressions in the SELECT Clause
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_langref_orderby">2.9.
JPQL ORDER BY Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk_ops">2.10.
JPQL Bulk Update and Delete
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_values">2.11.
JPQL Null Values
</a></span></dt><dt><span class="section"><a href="#jpa_langref_equality">2.12.
JPQL Equality and Comparison Semantics
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bnf">2.13.
JPQL BNF
</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e2943"></a>
<a class="indexterm" name="d5e2946"></a>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="195"><tr><td><img src="img/jpa-query.png"></td></tr></table></div>
<p>
The <code class="classname">javax.persistence.Query</code> interface is the mechanism
for issuing queries in JPA. The primary query language used is the Java
Persistence Query Language, or <code class="literal">JPQL</code>. JPQL is syntactically
very similar to SQL, but is object-oriented rather than table-oriented.
</p>
<p>
The API for executing JPQL queries will be discussed in
<a class="xref" href="#jpa_query_api" title="1.&nbsp; JPQL API">Section&nbsp;1, &#8220;
JPQL API
&#8221;</a>, and a full language reference will be
covered in <a class="xref" href="#jpa_langref" title="2.&nbsp; JPQL Language Reference">Section&nbsp;2, &#8220;
JPQL Language Reference
&#8221;</a>.
</p>
<div class="section" id="jpa_query_api"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
JPQL API
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_query_basic">1.1.
Query Basics
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_relations">1.2.
Relation Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_embeddables">1.3.
Embeddable Traversal
</a></span></dt><dt><span class="section"><a href="#jpa_overview_join_fetch">1.4.
Fetch Joins
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_functions">1.5.
JPQL Functions
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_inheritance">1.6.
Polymorphic Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_params">1.7.
Query Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_hints">1.8.
Query Hints
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_hints_locking">1.8.1.
Locking Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_locktimeout">1.8.2.
Lock Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_querytimeout">1.8.3.
Query Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_resultset">1.8.4.
Result Set Size Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_isolation">1.8.5.
Isolation Level Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_fetchplan">1.8.6.
Other Fetchplan Hints
</a></span></dt><dt><span class="section"><a href="#d5e3356">1.8.7.
Database-Specific Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_named">1.8.8.
Named Query Hints
</a></span></dt><dt><span class="section"><a href="#multi-hints-handling">1.8.9.
Handling of Multiple Similar Query Hints
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_query_ordering">1.9.
Ordering
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_aggregates">1.10.
Aggregates
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_named">1.11.
Named Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_delete">1.12.
Delete By Query
</a></span></dt><dt><span class="section"><a href="#jpa_overview_query_update">1.13.
Update By Query
</a></span></dt></dl></div>
<div class="section" id="jpa_overview_query_basic"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Query Basics
</h3></div></div></div>
<pre class="programlisting">SELECT x FROM Magazine x
</pre>
<p>
The preceding is a simple JPQL query for all <code class="classname">Magazine</code>
entities.
</p>
<pre class="programlisting">
public Query createQuery(String jpql);
</pre>
<p>
The
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/EntityManager.html" target="_top">
<code class="methodname">EntityManager.createQuery</code></a> method creates a
<code class="classname">Query</code> instance from a given JPQL string.
</p>
<pre class="programlisting">
public List getResultList();
</pre>
<p>
Invoking
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/Query.html#getResultList()" target="_top">
<code class="methodname">Query.getResultList</code></a> executes the query and
returns a <code class="classname">List</code> containing the matching objects. The
following example executes our <code class="classname">Magazine</code> query above:
</p>
<pre class="programlisting">
EntityManager em = ...
Query q = em.createQuery("SELECT x FROM Magazine x");
List&lt;Magazine&gt; results = (List&lt;Magazine&gt;) q.getResultList();
</pre>
<p>
A JPQL query has an internal namespace declared in the <code class="literal">from</code>
clause of the query. Arbitrary identifiers are assigned to entities so that they
can be referenced elsewhere in the query. In the query example above, the
identifier <code class="literal">x</code> is assigned to the entity <code class="classname"> Magazine
</code>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
The <code class="literal">as</code> keyword can optionally be used when declaring
identifiers in the <code class="literal">from</code> clause. <code class="literal">SELECT x FROM
Magazine x</code> and <code class="literal">SELECT x FROM Magazine AS x</code> are
synonymous.
</p>
</div>
<p>
Following the <code class="literal">select</code> clause of the query is the object or
objects that the query returns. In the case of the query above, the query's
result list will contain instances of the <code class="classname">Magazine</code> class.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
When selecting entities, you can optionally use the keyword <code class="literal">object
</code>. The clauses <code class="literal">select x</code> and <code class="literal">SELECT
OBJECT(x)</code> are synonymous.
</p>
</div>
<p>
The optional <code class="literal">where</code> clause places criteria on matching
results. For example:
</p>
<pre class="programlisting">SELECT x FROM Magazine x WHERE x.title = 'JDJ'</pre>
<p>
Keywords in JPQL expressions are case-insensitive, but entity, identifier, and
member names are not. For example, the expression above could also be expressed
as:
</p>
<pre class="programlisting">select x from Magazine x where x.title = 'JDJ'</pre>
<p>
But it could not be expressed as:
</p>
<pre class="programlisting">SELECT x FROM Magazine x WHERE x.TITLE = 'JDJ'</pre>
<p>
As with the <code class="literal">select</code> clause, alias names in the <code class="literal">where
</code> clause are resolved to the entity declared in the <code class="literal">from
</code> clause. The query above could be described in English as "for all
<code class="classname">Magazine</code> instances <code class="literal">x</code>, return a list
of every <code class="literal">x</code> such that <code class="literal">x</code>'s <code class="literal">title
</code> field is equal to 'JDJ'".
</p>
<p>
JPQL uses SQL-like syntax for query criteria. The <code class="literal">and</code> and
<code class="literal">or</code> logical operators chain multiple criteria together:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.title = 'JDJ' OR x.title = 'JavaPro'
</pre>
<p>
The <code class="literal">=</code> operator tests for equality. <code class="literal">&lt;&gt;
</code> tests for inequality. JPQL also supports the following arithmetic
operators for numeric comparisons: <code class="literal">&gt;, &gt;=, &lt;, &lt;=</code>.
For example:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.price &gt; 3.00 AND x.price &lt;= 5.00
</pre>
<p>
This query returns all magazines whose price is greater than 3.00 and less than
or equal to 5.00.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.price &lt;&gt; 3.00
</pre>
<p>
This query returns all Magazines whose price is not equal to 3.00.
</p>
<p>
You can group expressions together using parentheses in order to specify how
they are evaluated. This is similar to how parentheses are used in Java. For
example:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE (x.price &gt; 3.00 AND x.price &lt;= 5.00) OR x.price &lt; 7.00
</pre>
<p>
This expression would match magazines whose price is less than 7.00.
Alternately:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.price &gt; 3.00 AND (x.price &lt;= 5.00 OR x.price &lt; 7.00)
</pre>
<p>
This expression would match magazines whose price is 4.00, 5.00 or 6.00, but not
1.00, 2.00 or 3.00.
</p>
<p>
JPQL also includes the following conditionals:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e3032"></a>
<code class="literal">[NOT] BETWEEN</code>: Shorthand for expressing that a value falls
between two other values. The following two statements are synonymous:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.price &gt;= 3.00 AND x.price &lt;= 5.00
</pre>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.price BETWEEN 3.00 AND 5.00
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3039"></a>
<code class="literal">[NOT] LIKE</code>: Performs a string comparison with wildcard
support. The special character '_' in the parameter means to match any single
character, and the special character '%' means to match any sequence of
characters. The following statement matches title fields "JDJ" and "JavaPro",
but not "IT Insider":
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.title LIKE 'J%'
</pre>
<p>
The following statement matches the title field "JDJ" but not "JavaPro":
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.title LIKE 'J__'
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3047"></a>
<code class="literal">[NOT] IN</code>: Specifies that the member must be equal to one
element of the provided list. The following two statements are synonymous:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.title IN ('JDJ', 'JavaPro', 'IT Insider')
</pre>
<pre class="programlisting">SELECT x FROM Magazine x WHERE x.title = 'JDJ' OR x.title = 'JavaPro' OR x.title = 'IT Insider'
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3054"></a>
<code class="literal">IS [NOT] EMPTY</code>: Specifies that the collection field holds no
elements. For example:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.articles is empty
</pre>
<p>
This statement will return all magazines whose <code class="literal"> articles</code>
member contains no elements.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3062"></a>
<code class="literal">IS [NOT] NULL</code>: Specifies that the field is equal to null.
For example:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.publisher is null
</pre>
<p>
This statement will return all Magazine instances whose "publisher" field is set
to <code class="literal">null</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3070"></a>
<code class="literal">NOT</code>: Negates the contained expression. For example, the
following two statements are synonymous:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE NOT(x.price = 10.0)
</pre>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.price &lt;&gt; 10.0
</pre>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_query_relations"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Relation Traversal
</h3></div></div></div>
<p>
Relations between objects can be traversed using Java-like syntax. For example,
if the Magazine class has a field named "publisher" of type Company, that
relation can be queried as follows:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.publisher.name = 'Random House'
</pre>
<p>
This query returns all <code class="classname">Magazine</code> instances whose <code class="literal">
publisher</code> field is set to a <code class="classname">Company</code> instance
whose name is "Random House".
</p>
<p>
Single-valued relation traversal implies that the relation is not null. In SQL
terms, this is known as an <span class="emphasis"><em>inner join</em></span>. If you want to also
include relations that are null, you can specify:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE x.publisher.name = 'Random House' or x.publisher is null
</pre>
<p>
You can also traverse collection fields in queries, but you must declare each
traversal in the <code class="literal">from</code> clause. Consider:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x, IN(x.articles) y WHERE y.authorName = 'John Doe'
</pre>
<p>
This query says that for each <code class="classname">Magazine</code><code class="literal"> x
</code>, traverse the <code class="literal">articles</code> relation and check each
<code class="classname">Article</code> <code class="literal">y</code>, and pass the filter if
<code class="literal">y</code>'s <code class="literal">authorName</code> field is equal to "John
Doe". In short, this query will return all magazines that have any articles
written by John Doe.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
The <code class="literal">IN()</code> syntax can also be expressed with the keywords
<code class="literal">inner join</code>. The statements <code class="literal">SELECT x FROM Magazine
x, IN(x.articles) y WHERE y.authorName = 'John Doe'</code> and <code class="literal">
SELECT x FROM Magazine x inner join x.articles y WHERE y.authorName = 'John Doe'
</code> are synonymous.
</p>
</div>
</div>
<div class="section" id="jpa_overview_query_embeddables"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Embeddable Traversal
</h3></div></div></div>
<p>
Similar to relation traversal, nested embeddable objects can be traversed using Java-like syntax.
For example, if the <code class="classname">Company</code> class has a field named "address" of
an embeddable type <code class="classname">Address</code>,
and the <code class="classname">Address</code> has a field named "geocode" of
an embeddable type <code class="classname">Geocode</code>,
the <code class="literal">geocode</code> of a company's address can be queried as follows:
</p>
<pre class="programlisting">
SELECT c.address.geocode FROM Company c WHERE c.name = 'Random House'
</pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
The <code class="literal">geocode</code> returned by the above query will not be part of the state of any managed
entity. Modifications to these embeddable instances are not allowed.
</p>
</div>
<p>
Traversal into embeddable's state field is also allowed as shown in the following query:
</p>
<pre class="programlisting">
SELECT c.address.geocode.latitude FROM Company c WHERE c.name = 'Random House'
</pre>
<p>
Embeddable objects may contain single-valued or collection-valued relations.
These relations can also be traversed using Java-like syntax.
For example, if the Address has a relation field named "phoneLists" of
an entity type <code class="classname">PhoneNumber</code>,
the following query returns the <code class="classname">PhoneNumber</code> entities of the <code class="classname">Company</code>
named 'Random House':
</p>
<pre class="programlisting">
SELECT p FROM Company c, IN(c.address.phoneLists) p WHERE c.name = 'Random House'
</pre>
</div>
<div class="section" id="jpa_overview_join_fetch"><div class="titlepage"><div><div><h3 class="title">1.4.&nbsp;
Fetch Joins
</h3></div></div></div>
<p>
JPQL queries may specify one or more <code class="literal">join fetch</code> declarations,
which allow the query to specify which fields in the returned instances will be
pre-fetched.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x join fetch x.articles WHERE x.title = 'JDJ'
</pre>
<p>
The query above returns <code class="classname">Magazine</code> instances and guarantees
that the <code class="literal">articles</code> field will already be fetched in the
returned instances.
</p>
<p>
Multiple fields may be specified in separate <code class="literal">join fetch</code>
declarations: </p><pre class="programlisting">
SELECT x FROM Magazine x join fetch x.articles join fetch x.authors WHERE x.title = 'JDJ'
</pre><p>
</p>
<p>
Notice that in the above query, both <code class="literal">articles</code> and <code class="literal">authors</code>
are relation property in <code class="classname">Magazine</code>.
JPQL syntax does not allow range variable declared for paths on the right-hand side of
<code class="literal">join fetch</code>.
Therefore, if <code class="classname">Article</code> entity has a relation property of
<code class="literal">publishers</code>,
it is not possible to specify a query
that returns <code class="classname">Magazine</code> instances and pre-fetch
the <code class="literal">articles</code> and the <code class="literal">publishers</code>.
The following query will result in syntax error:
</p><pre class="programlisting">
SELECT x FROM Magazine x join fetch x.articles a join fetch a.publishers p WHERE x.title = 'JDJ'
</pre><p>
</p>
<p>
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3><p> Specifying the <code class="literal">join fetch</code> declaration is
functionally equivalent to adding the fields to the Query's <code class="classname">
FetchConfiguration</code>. See <a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a>.
</p>
</div><p>
</p>
</div>
<div class="section" id="jpa_overview_query_functions"><div class="titlepage"><div><div><h3 class="title">1.5.&nbsp;
JPQL Functions
</h3></div></div></div>
<p>
As well as supporting direct field and relation comparisons, JPQL supports a
pre-defined set of functions that you can apply.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e3156"></a>
<code class="literal">CONCAT(string1, string2)</code>: Concatenates two string fields or
literals. For example:
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE CONCAT(x.title, 's') = 'JDJs'
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3162"></a>
<code class="literal">SUBSTRING(string, startIndex, [length])</code>: Returns the part of
the <code class="literal">string</code> argument starting at <code class="literal">startIndex</code>
(1-based) and optionally ending at <code class="literal">length</code> characters past <code class="literal">
startIndex</code>. If the <code class="literal">length</code> argument is not specified,
the substring from the <code class="literal">startIndex</code> to the end of the <code class="literal">string</code>
is returned.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE SUBSTRING(x.title, 1, 1) = 'J'
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3175"></a>
<code class="literal">TRIM([LEADING | TRAILING | BOTH] [character FROM] string</code>:
Trims the specified character from either the beginning ( <code class="literal">LEADING
</code>) end ( <code class="literal">TRAILING</code>) or both ( <code class="literal"> BOTH
</code>) of the string argument. If no trim character is specified, the
space character will be trimmed.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE TRIM(BOTH 'J' FROM x.title) = 'D'
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3184"></a>
<code class="literal">LOWER(string)</code>: Returns the lower-case of the specified
string argument.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE LOWER(x.title) = 'jdj'
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3190"></a>
<code class="literal">UPPER(string)</code>: Returns the upper-case of the specified
string argument.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE UPPER(x.title) = 'JAVAPRO'
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3196"></a>
<code class="literal">LENGTH(string)</code>: Returns the number of characters in the
specified string argument.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE LENGTH(x.title) = 3
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3202"></a>
<code class="literal">LOCATE(searchString, candidateString [, startIndex])</code>:
Returns the first index of <code class="literal">searchString</code> in <code class="literal">
candidateString</code>. Positions are 1-based. If the string is not found,
returns 0.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE LOCATE('D', x.title) = 2
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3210"></a>
<code class="literal">ABS(number)</code>: Returns the absolute value of the argument.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE ABS(x.price) &gt;= 5.00
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3216"></a>
<code class="literal">SQRT(number)</code>: Returns the square root of the argument.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE SQRT(x.price) &gt;= 1.00
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3222"></a>
<code class="literal">MOD(number, divisor)</code>: Returns the modulo of <code class="literal">number
</code> and <code class="literal">divisor</code>.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x WHERE MOD(x.price, 10) = 0
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3230"></a>
<code class="literal">INDEX(identification_variable)</code>: Returns an integer value corresponding
to the position of its argument in an ordered list.
The INDEX function can only be applied to identification variables denoting types for
which an order column has been specified.
</p>
<p>
In the following example, <code class="literal">studentWaitlist</code> is a list of
students for which an order column has
been specified, the query returns the name of the first student on the waiting list of
the course named 'Calculus':
</p>
<pre class="programlisting">
SELECT w.name FROM Course c JOIN c.studentWaitlist w WHERE c.name = &#8216;Calculus&#8217; AND INDEX(w) = 0
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3238"></a>
<code class="literal">CURRENT_DATE</code>: Returns the current date.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3243"></a>
<code class="literal">CURRENT_TIME</code>: Returns the current time.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e3248"></a>
<code class="literal">CURRENT_TIMESTAMP</code>: Returns the current timestamp.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_query_inheritance"><div class="titlepage"><div><div><h3 class="title">1.6.&nbsp;
Polymorphic Queries
</h3></div></div></div>
<p>
All JPQL queries are polymorphic, which means the <code class="literal">from</code> clause
of a query includes not only instances of the specific entity class to which it
refers, but all subclasses of that class as well. The instances returned by a
query include instances of the subclasses that satisfy the query conditions. For
example, the following query may return instances of <code class="classname"> Magazine
</code>, as well as <code class="classname">Tabloid</code> and <code class="classname">Digest
</code> instances, where <code class="classname">Tabloid</code> and <code class="classname">
Digest</code> are <code class="classname">Magazine</code> subclasses.
</p>
<pre class="programlisting">SELECT x FROM Magazine x WHERE x.price &lt; 5</pre>
<p>
Non-polymorphic queries or queries whose polymorphism is restricted can be specified using entity
type expressions (see <a class="xref" href="#jpa_langref_entity_type_expressions" title="2.6.4.&nbsp; Entity Type Expressions">Section&nbsp;2.6.4, &#8220;
Entity Type Expressions
&#8221;</a> )
in the <code class="literal">WHERE</code> clause to restrict the domain of the query.
For example, the following query returns instances of <code class="classname">Digest</code>:
</p><pre class="programlisting">
SELECT x FROM Magazine WHERE TYPE(x) = Digest
</pre><p>
</p>
</div>
<div class="section" id="jpa_overview_query_params"><div class="titlepage"><div><div><h3 class="title">1.7.&nbsp;
Query Parameters
</h3></div></div></div>
<p>
JPQL provides support for parameterized queries. Either named parameters or
positional parameters may be specified in the query string. Parameters allow you
to re-use query templates where only the input parameters vary. A single query
can declare either named parameters or positional parameters, but is not allowed
to declare both named and positional parameters.
</p>
<pre class="programlisting">
public Query setParameter (int pos, Object value);
</pre>
<p>
Specify positional parameters in your JPQL string using an integer prefixed by a
question mark. You can then populate the <code class="classname">Query</code> object
with positional parameter values via calls to the <code class="methodname">setParameter
</code> method above. The method returns the <code class="classname">Query</code>
instance for optional method chaining.
</p>
<pre class="programlisting">
EntityManager em = ...
Query q = em.createQuery("SELECT x FROM Magazine x WHERE x.title = ?1 and x.price &gt; ?2");
q.setParameter(1, "JDJ").setParameter(2, 5.0);
List&lt;Magazine&gt; results = (List&lt;Magazine&gt;) q.getResultList();
</pre>
<p>
This code will substitute <code class="literal">JDJ</code> for the <code class="literal">?1</code>
parameter and <code class="literal">5.0</code> for the <code class="literal">?2</code> parameter,
then execute the query with those values.
</p>
<pre class="programlisting">
public Query setParameter(String name, Object value);
</pre>
<p>
Named parameters are denoted by prefixing an arbitrary name with a colon in your
JPQL string. You can then populate the <code class="classname"> Query</code> object with
parameter values using the method above. Like the positional parameter method,
this method returns the <code class="classname">Query</code> instance for optional
method chaining.
</p>
<pre class="programlisting">
EntityManager em = ...
Query q = em.createQuery("SELECT x FROM Magazine x WHERE x.title = :titleParam and x.price &gt; :priceParam");
q.setParameter("titleParam", "JDJ").setParameter("priceParam", 5.0);
List&lt;Magazine&gt; results = (List&lt;Magazine&gt;) q.getResultList();
</pre>
<p>
This code substitutes <code class="literal">JDJ</code> for the <code class="literal"> :titleParam
</code> parameter and <code class="literal">5.0</code> for the <code class="literal">:priceParam
</code> parameter, then executes the query with those values.
</p>
<p>
All input parameters must be single-valued, except in IN expressions
(see <a class="xref" href="#jpa_langref_in_expressions" title="2.5.9.&nbsp; JPQL In Expressions">Section&nbsp;2.5.9, &#8220;
JPQL In Expressions
&#8221;</a>), which support the use of collection-valued
input parameters.
</p>
</div>
<div class="section" id="jpa_overview_query_hints"><div class="titlepage"><div><div><h3 class="title">1.8.&nbsp;
Query Hints
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_hints_locking">1.8.1.
Locking Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_locktimeout">1.8.2.
Lock Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_querytimeout">1.8.3.
Query Timeout Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_resultset">1.8.4.
Result Set Size Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_isolation">1.8.5.
Isolation Level Hint
</a></span></dt><dt><span class="section"><a href="#jpa_hints_fetchplan">1.8.6.
Other Fetchplan Hints
</a></span></dt><dt><span class="section"><a href="#d5e3356">1.8.7.
Database-Specific Hints
</a></span></dt><dt><span class="section"><a href="#jpa_hints_named">1.8.8.
Named Query Hints
</a></span></dt><dt><span class="section"><a href="#multi-hints-handling">1.8.9.
Handling of Multiple Similar Query Hints
</a></span></dt></dl></div>
<p>
JPQL provides support for hints which are name/value pairs used to control locking and optimization keywords in SQL.
The following example shows how to use the JPA hint API to set the <code class="classname">ReadLockMode</code>
and <code class="classname">ResultCount</code> in the OpenJPA fetch plan. This will result in
a database-specific SQL keyword (usually FOR UPDATE) to be emitted into the SQL provided that a
pessimistic LockManager is being used. Additionally, if a DB2 database is being used,
the OPTIMIZE FOR 2 ROWS clause will also be emitted.
</p>
<div class="example" id="jpa_query_hint1"><p class="title"><b>Example&nbsp;10.1.&nbsp;
Query Hints
</b></p><div class="example-contents">
<pre class="programlisting">
...
Query q = em.createQuery("select m from Magazine m where ... ");
q.setHint("openjpa.hint.OptimizeResultCount", new Integer(2));
q.setHint("openjpa.FetchPlan.ReadLockMode","WRITE");
List r = q.getResultList();
...
</pre>
</div></div><br class="example-break">
<p>
Hints which can not be processed by a particular database or are unknown to OpenJPA are ignored.
Hints known to OpenJPA but supplied with an incompatible value will result in an
<code class="classname">IllegalArgumentException</code> being thrown.
</p>
<div class="section" id="jpa_hints_locking"><div class="titlepage"><div><div><h4 class="title">1.8.1.&nbsp;
Locking Hints
</h4></div></div></div>
<p>
To avoid deadlock and optimistic update exceptions among multiple updaters, use a pessimistic LockManager, specified in the persistence unit definition,
and use a hint name of "openjpa.FetchPlan.ReadLockMode" on queries for entities that must be locked for serialization.
The value of <code class="classname">ReadLockMode</code> can be either "READ" or "WRITE".
This results in a database-specific locking keyword (usually FOR UPDATE) to be emitted into the SQL.
</p>
<p>
Using a <code class="classname">ReadLockMode</code> hint with JPA optimistic locking (i.e. specifying LockManager = "version") will result in the entity version field either being reread at end of transaction in the case of a value of "READ" or the version field updated at end of transaction in the case of "WRITE". You must define a version field in the entity mapping when using a version LockManager and using ReadLockMode.
</p>
<div class="table" id="d5e3309"><p class="title"><b>Table&nbsp;10.1.&nbsp;
Interaction of ReadLockMode hint and LockManager
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Interaction of ReadLockMode hint and LockManager&#xA; " border="1"><colgroup><col align="left" class="interaction"><col align="left" class="pessimistic"><col align="left" class="version"></colgroup><thead><tr><th align="left">
ReadLockMode
</th><th align="left">
LockManager=pessimistic
</th><th align="left">
LockManager=version
</th></tr></thead><tbody><tr><td align="left">
READ
</td><td align="left">
SQL with FOR UPDATE
</td><td align="left">SQL without FOR UPDATE;
<p>
reread version field at the end of transaction and check for no change.
</p>
</td></tr><tr><td align="left">
WRITE
</td><td align="left">
SQL with FOR UPDATE
</td><td align="left">
SQL without FOR UPDATE;
<p>
force update version field at the end of transaction
</p>
</td></tr><tr><td align="left">
not specified
</td><td align="left">
SQL without FOR UPDATE
</td><td align="left">
SQL without FOR UPDATE
</td></tr></tbody></table>
</div></div><br class="table-break">
</div>
<div class="section" id="jpa_hints_locktimeout"><div class="titlepage"><div><div><h4 class="title">1.8.2.&nbsp;
Lock Timeout Hint
</h4></div></div></div>
<p>
To specify a lock timeout hint in milliseconds to those databases that support
it, specify a hint name of "openjpa.LockTimeout" or
"javax.persistence.lock.timeout" with an integer value greater than
zero, or zero for no timeout which is the default behavior.
</p>
</div>
<div class="section" id="jpa_hints_querytimeout"><div class="titlepage"><div><div><h4 class="title">1.8.3.&nbsp;
Query Timeout Hint
</h4></div></div></div>
<p>
To specify a query timeout hint in milliseconds to those database drivers that
support it, specify a hint name of "javax.persistence.query.timeout"
with an integer value greater than zero, or zero for no timeout which is the
default behavior.
</p>
</div>
<div class="section" id="jpa_hints_resultset"><div class="titlepage"><div><div><h4 class="title">1.8.4.&nbsp;
Result Set Size Hint
</h4></div></div></div>
<p>
To specify a result set size hint to those databases that support it, specify a hint name of "openjpa.hint.OptimizeResultCount" with an integer value greater than zero. This causes the SQL keyword OPTIMIZE FOR to be generated.
</p>
</div>
<div class="section" id="jpa_hints_isolation"><div class="titlepage"><div><div><h4 class="title">1.8.5.&nbsp;
Isolation Level Hint
</h4></div></div></div>
<p>
To specify an isolation level, specify a hint name of "openjpa.FetchPlan.Isolation". The value will be used to specify isolation level using the SQL WITH &lt;isolation&gt; clause for those databases that support it. This hint only works in conjunction with the ReadLockMode hint.
</p>
</div>
<div class="section" id="jpa_hints_fetchplan"><div class="titlepage"><div><div><h4 class="title">1.8.6.&nbsp;
Other Fetchplan Hints
</h4></div></div></div>
<p>
Any property of an OpenJPA FetchPlan can be changed using a hint by using a name of the form "openjpa.FetchPlan."&lt;property name&gt;. Valid property names include:
<code class="classname">MaxFetchDepth</code>, <code class="classname">FetchBatchSize</code>, <code class="classname">LockTimeOut</code>, <code class="classname">EagerFetchMode</code>, <code class="classname">SubclassFetchMode</code> and <code class="classname">Isolation</code>.
</p>
</div>
<div class="section" id="d5e3356"><div class="titlepage"><div><div><h4 class="title">1.8.7.&nbsp;
Database-Specific Hints
</h4></div></div></div>
<p>
The hint names "openjpa.hint.MySQLSelectHint" and
"openjpa.hint.OracleSelectHint" can be used to specify a string value
of a query hint that will be inserted into SQL for MySQL and Oracle databases.
See <a class="xref" href="#dbsupport_mysql_query_hints" title="19.1.&nbsp; Using Query Hints with MySQL">Section&nbsp;19.1, &#8220;
Using Query Hints with MySQL
&#8221;</a> and
<a class="xref" href="#dbsupport_oracle_query_hints" title="21.1.&nbsp; Using Query Hints with Oracle">Section&nbsp;21.1, &#8220;
Using Query Hints with Oracle
&#8221;</a> for examples.
</p>
</div>
<div class="section" id="jpa_hints_named"><div class="titlepage"><div><div><h4 class="title">1.8.8.&nbsp;
Named Query Hints
</h4></div></div></div>
<p>
Hints can also be included as part of a NamedQuery definition.
</p>
<div class="example" id="jpa_query_hint2"><p class="title"><b>Example&nbsp;10.2.&nbsp;
Named Query using Hints
</b></p><div class="example-contents">
<pre class="programlisting">
...
@NamedQuery(name="magsOverPrice",
query="SELECT x FROM Magazine x WHERE x.price &gt; ?1",
hints={
@QueryHint(name="openjpa.hint.OptimizeResultCount", value="2"),
@QueryHint(name="openjpa.FetchPlan.ReadLockMode", value="WRITE")
}
)
...
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="multi-hints-handling"><div class="titlepage"><div><div><h4 class="title">1.8.9.&nbsp;
Handling of Multiple Similar Query Hints
</h4></div></div></div>
<p>
When similar hints in different prefix scopes are specified in a query,
the following prefix precedence order is used to select the effective hint:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
javax.persistence.*
</li><li class="listitem">
openjpa.FetchPlan.*
</li><li class="listitem">
openjpa.jdbc.*
</li><li class="listitem">
openjpa.*
</li></ul></div><p>
</p><div class="example" id="multi-hints-example"><p class="title"><b>Example&nbsp;10.3.&nbsp;
Setting Multiple Similar Query Hints
</b></p><div class="example-contents">
<pre class="programlisting">
...
Query q = em.createQuery(.....);
q.setHint("openjpa.FetchPlan.LockTimeout", 1000);
q.setHint("javax.persistence.lock.timeout", 2000);
q.setHint("openjpa.LockTimeout", 3000);
// Lock time out of 2000 ms is in effect for query q
...
</pre>
</div></div><p><br class="example-break">
</p>
</div>
</div>
<div class="section" id="jpa_overview_query_ordering"><div class="titlepage"><div><div><h3 class="title">1.9.&nbsp;
Ordering
</h3></div></div></div>
<p>
JPQL queries may optionally contain an <code class="literal">order by</code> clause which
specifies one or more fields to order by when returning query results. You may
follow the <code class="literal">order by field</code> clause with the <code class="literal">asc
</code> or <code class="literal">desc</code> keywords, which indicate that ordering
should be ascending or descending, respectively. If the direction is omitted,
ordering is ascending by default.
</p>
<pre class="programlisting">
SELECT x FROM Magazine x order by x.title asc, x.price desc
</pre>
<p>
The query above returns <code class="classname">Magazine</code> instances sorted by
their title in ascending order. In cases where the titles of two or more
magazines are the same, those instances will be sorted by price in descending
order.
</p>
</div>
<div class="section" id="jpa_overview_query_aggregates"><div class="titlepage"><div><div><h3 class="title">1.10.&nbsp;
Aggregates
</h3></div></div></div>
<p>
JPQL queries can select aggregate data as well as objects. JPQL includes the
<code class="literal">min</code>, <code class="literal">max</code>, <code class="literal">avg</code>, and
<code class="literal">count</code> aggregates. These functions can be used for reporting
and summary queries.
</p>
<p>
The following query will return the average of all the prices of all the
magazines:
</p>
<pre class="programlisting">
EntityManager em = ...
Query q = em.createQuery("SELECT AVG(x.price) FROM Magazine x");
Number result = (Number) q.getSingleResult();
</pre>
<p>
The following query will return the highest price of all the magazines titled
"JDJ":
</p>
<pre class="programlisting">
EntityManager em = ...
Query q = em.createQuery("SELECT MAX(x.price) FROM Magazine x WHERE x.title = 'JDJ'");
Number result = (Number) q.getSingleResult();
</pre>
</div>
<div class="section" id="jpa_overview_query_named"><div class="titlepage"><div><div><h3 class="title">1.11.&nbsp;
Named Queries
</h3></div></div></div>
<p>
Query templates can be statically declared using the <code class="literal"> NamedQuery
</code> and <code class="literal">NamedQueries</code> annotations. For example:
</p>
<pre class="programlisting">
@Entity
@NamedQueries({
@NamedQuery(name="magsOverPrice",
query="SELECT x FROM Magazine x WHERE x.price &gt; ?1"),
@NamedQuery(name="magsByTitle",
query="SELECT x FROM Magazine x WHERE x.title = :titleParam")
})
public class Magazine {
...
}
</pre>
<p>
These declarations will define two named queries called <code class="literal">magsOverPrice
</code> and <code class="literal">magsByTitle</code>.
</p>
<pre class="programlisting">
public Query createNamedQuery(String name);
</pre>
<p>
You retrieve named queries with the above <code class="classname">EntityManager</code>
method. For example:
</p>
<pre class="programlisting">
EntityManager em = ...
Query q = em.createNamedQuery("magsOverPrice");
q.setParameter(1, 5.0f);
List&lt;Magazine&gt; results = (List&lt;Magazine&gt;) q.getResultList();
</pre>
<pre class="programlisting">
EntityManager em = ...
Query q = em.createNamedQuery("magsByTitle");
q.setParameter("titleParam", "JDJ");
List&lt;Magazine&gt; results = (List&lt;Magazine&gt;) q.getResultList();
</pre>
</div>
<div class="section" id="jpa_overview_query_delete"><div class="titlepage"><div><div><h3 class="title">1.12.&nbsp;
Delete By Query
</h3></div></div></div>
<p>
Queries are useful not only for finding objects, but for efficiently deleting
them as well. For example, you might delete all records created before a certain
date. Rather than bring these objects into memory and delete them individually,
JPA allows you to perform a single bulk delete based on JPQL criteria.
</p>
<p>
Delete by query uses the same JPQL syntax as normal queries, with one exception:
begin your query string with the <code class="literal">delete</code> keyword instead of
the <code class="literal">select</code> keyword. To then execute the delete, you call the
following <code class="classname">Query</code> method:
</p>
<pre class="programlisting">
public int executeUpdate();
</pre>
<p>
This method returns the number of objects deleted. The following example deletes
all subscriptions whose expiration date has passed.
</p>
<div class="example" id="jpa_overview_query_deleteex"><p class="title"><b>Example&nbsp;10.4.&nbsp;
Delete by Query
</b></p><div class="example-contents">
<pre class="programlisting">
Query q = em.createQuery("DELETE FROM Subscription s WHERE s.subscriptionDate &lt; :today");
q.setParameter("today", new Date());
int deleted = q.executeUpdate();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_query_update"><div class="titlepage"><div><div><h3 class="title">1.13.&nbsp;
Update By Query
</h3></div></div></div>
<p>
Similar to bulk deletes, it is sometimes necessary to perform updates against a
large number of queries in a single operation, without having to bring all the
instances down to the client. Rather than bring these objects into memory and
modifying them individually, JPA allows you to perform a single bulk update
based on JPQL criteria.
</p>
<p>
Update by query uses the same JPQL syntax as normal queries, except that the
query string begins with the <code class="literal">update</code> keyword instead of
<code class="literal">select</code>. To execute the update, you call the following
<code class="classname">Query</code> method:
</p>
<pre class="programlisting">
public int executeUpdate();
</pre>
<p>
This method returns the number of objects updated. The following example updates
all subscriptions whose expiration date has passed to have the "paid" field set
to true..
</p>
<div class="example" id="jpa_overview_query_updateex"><p class="title"><b>Example&nbsp;10.5.&nbsp;
Update by Query
</b></p><div class="example-contents">
<pre class="programlisting">
Query q = em.createQuery("UPDATE Subscription s SET s.paid = :paid WHERE s.subscriptionDate &lt; :today");
q.setParameter("today", new Date());
q.setParameter("paid", true);
int updated = q.executeUpdate();
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="jpa_langref"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
JPQL Language Reference
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_stmnttypes">2.1.
JPQL Statement Types
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_select">2.1.1.
JPQL Select Statement
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk">2.1.2.
JPQL Update and Delete Statements
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_schematypes">2.2.
JPQL Abstract Schema Types and Query Domains
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_schemanaming">2.2.1.
JPQL Entity Naming
</a></span></dt><dt><span class="section"><a href="#jpa_langref_schemaexample">2.2.2.
JPQL Schema Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_fromclause">2.3.
JPQL FROM Clause and Navigational Declarations
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_from_identifiers">2.3.1.
JPQL FROM Identifiers
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_vars">2.3.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_range">2.3.3.
JPQL Range Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path">2.3.4.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_Joins">2.3.5.
JPQL Joins
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_inner_joins">2.3.5.1.
JPQL Inner Joins (Relationship Joins)
</a></span></dt><dt><span class="section"><a href="#jpa_langref_outer_joins">2.3.5.2.
JPQL Outer Joins
</a></span></dt><dt><span class="section"><a href="#jpa_langref_fetch_joins">2.3.5.3.
JPQL Fetch Joins
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_collection_dec">2.3.6.
JPQL Collection Member Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_clause_and_sql">2.3.7.
JPQL FROM Clause and SQL
</a></span></dt><dt><span class="section"><a href="#jpa_langref_polymorph">2.3.8.
JPQL Polymorphism
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_where">2.4.
JPQL WHERE Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_cond">2.5.
JPQL Conditional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_lit">2.5.1.
JPQL Literals
</a></span></dt><dt><span class="section"><a href="#jpa_langref_idvar">2.5.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path_exp">2.5.3.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_input_params">2.5.4.
JPQL Input Parameters
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_pos_params">2.5.4.1.
JPQL Positional Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_langref_named_params">2.5.4.2.
JPQL Named Parameters
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_cond_comp">2.5.5.
JPQL Conditional Expression Composition
</a></span></dt><dt><span class="section"><a href="#jpa_langref_operators">2.5.6.
JPQL Operators and Operator Precedence
</a></span></dt><dt><span class="section"><a href="#jpa_langref_comparison_expressions">2.5.7.
JPQL Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_between">2.5.8.
JPQL Between Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_in_expressions">2.5.9.
JPQL In Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_like">2.5.10.
JPQL Like Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null">2.5.11.
JPQL Null Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_empty_comp">2.5.12.
JPQL Empty Collection Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_collection_member">2.5.13.
JPQL Collection Member Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_exists">2.5.14.
JPQL Exists Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_all_any">2.5.15.
JPQL All or Any Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_subqueries">2.5.16.
JPQL Subqueries
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_scalar_expressions">2.6.
JPQL Scalar Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_math_expressions">2.6.1.
Arithmetic Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_functional_expressions">2.6.2.
String, Arithmetic, and Datetime Functional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_string_fun">2.6.2.1.
JPQL String Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_arithmetic">2.6.2.2.
JPQL Arithmetic Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_datetime">2.6.2.3.
JPQL Datetime Functions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_case_expressions">2.6.3.
Case Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_entity_type_expressions">2.6.4.
Entity Type Expressions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_group">2.7.
JPQL GROUP BY, HAVING
</a></span></dt><dt><span class="section"><a href="#jpa_langref_select_clause">2.8.
JPQL SELECT Clause
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_resulttype">2.8.1.
JPQL Result Type of the SELECT Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_constructor">2.8.2.
JPQL Constructor Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_select">2.8.3.
JPQL Null Values in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_embeddables">2.8.4.
JPQL Embeddables in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_aggregates">2.8.5.
JPQL Aggregate Functions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_agg_examples">2.8.5.1.
JPQL Aggregate Examples
</a></span></dt><dt><span class="section"><a href="#jpa_langref_numeric_expressions_in_select">2.8.5.2.
JPQL Numeric Expressions in the SELECT Clause
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_langref_orderby">2.9.
JPQL ORDER BY Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk_ops">2.10.
JPQL Bulk Update and Delete
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_values">2.11.
JPQL Null Values
</a></span></dt><dt><span class="section"><a href="#jpa_langref_equality">2.12.
JPQL Equality and Comparison Semantics
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bnf">2.13.
JPQL BNF
</a></span></dt></dl></div>
<p>
The Java Persistence Query Language (JPQL) is used to define searches against
persistent entities independent of the mechanism used to store those entities.
As such, JPQL is "portable", and not constrained to any particular data store.
The Java Persistence query language is an extension of the Enterprise JavaBeans
query language, <code class="literal">EJB QL</code>, adding operations such as bulk
deletes and updates, join operations, aggregates, projections, and subqueries.
Furthermore, JPQL queries can be declared statically in metadata, or can be
dynamically built in code. This chapter provides the full definition of the
language.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Much of this section is paraphrased or taken directly from Chapter 4 of the
JSR 317 Java Persistence API Specification.
</p>
</div>
<div class="section" id="jpa_langref_stmnttypes"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
JPQL Statement Types
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_select">2.1.1.
JPQL Select Statement
</a></span></dt><dt><span class="section"><a href="#jpa_langref_bulk">2.1.2.
JPQL Update and Delete Statements
</a></span></dt></dl></div>
<p>
A JPQL statement may be either a <code class="literal">SELECT</code> statement, an
<code class="literal">UPDATE</code> statement, or a <code class="literal">DELETE</code> statement.
This chapter refers to all such statements as "queries". Where it is important
to distinguish among statement types, the specific statement type is referenced.
In BNF syntax, a query language statement is defined as:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
QL_statement ::= select_statement | update_statement | delete_statement
</p>
</li></ul></div>
<p>
The complete BNF for JPQL is defined in <a class="xref" href="#jpa_langref_bnf" title="2.13.&nbsp; JPQL BNF">Section&nbsp;2.13, &#8220;
JPQL BNF
&#8221;</a>.
Any JPQL statement may be constructed dynamically or may be statically defined
in a metadata annotation or XML descriptor element. All statement types may
have parameters, as discussed in <a class="xref" href="#jpa_langref_input_params" title="2.5.4.&nbsp; JPQL Input Parameters">Section&nbsp;2.5.4, &#8220;
JPQL Input Parameters
&#8221;</a>.
</p>
<div class="section" id="jpa_langref_select"><div class="titlepage"><div><div><h4 class="title">2.1.1.&nbsp;
JPQL Select Statement
</h4></div></div></div>
<p>
A select statement is a string which consists of the following clauses:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
a <code class="literal">SELECT</code> clause, which determines the type of the objects
or values to be selected.
</p>
</li><li class="listitem">
<p>
a <code class="literal">FROM</code> clause, which provides declarations that designate the
domain to which the expressions specified in the other clauses of the query
apply.
</p>
</li><li class="listitem">
<p>
an optional <code class="literal">WHERE</code> clause, which may be used to restrict the
results that are returned by the query.
</p>
</li><li class="listitem">
<p>
an optional <code class="literal">GROUP BY</code> clause, which allows query results to be
aggregated in terms of groups.
</p>
</li><li class="listitem">
<p>
an optional <code class="literal">HAVING</code> clause, which allows filtering over
aggregated groups.
</p>
</li><li class="listitem">
<p>
an optional <code class="literal">ORDER BY</code> clause, which may be used to order the
results that are returned by the query.
</p>
</li></ul></div>
<p>
In BNF syntax, a select statement is defined as:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
select_statement ::= select_clause from_clause [where_clause] [groupby_clause]
[having_clause] [orderby_clause]
</p>
</li></ul></div>
<p>
A select statement must always have a <code class="literal">SELECT</code> and a
<code class="literal">FROM</code> clause. The square brackets [] indicate that the other
clauses are optional.
</p>
</div>
<div class="section" id="jpa_langref_bulk"><div class="titlepage"><div><div><h4 class="title">2.1.2.&nbsp;
JPQL Update and Delete Statements
</h4></div></div></div>
<p>
Update and delete statements provide bulk operations over sets of entities. In
BNF syntax, these operations are defined as:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
update_statement ::= update_clause [where_clause]
</p>
</li><li class="listitem">
<p>
delete_statement ::= delete_clause [where_clause]
</p>
</li></ul></div>
<p>
The update and delete clauses determine the type of the entities to be updated
or deleted. The <code class="literal">WHERE</code> clause may be used to restrict the
scope of the update or delete operation. Update and delete statements are
described further in <a class="xref" href="#jpa_langref_bulk_ops" title="2.10.&nbsp; JPQL Bulk Update and Delete">Section&nbsp;2.10, &#8220;
JPQL Bulk Update and Delete
&#8221;</a>.
</p>
</div>
</div>
<div class="section" id="jpa_langref_schematypes"><div class="titlepage"><div><div><h3 class="title">2.2.&nbsp;
JPQL Abstract Schema Types and Query Domains
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_schemanaming">2.2.1.
JPQL Entity Naming
</a></span></dt><dt><span class="section"><a href="#jpa_langref_schemaexample">2.2.2.
JPQL Schema Example
</a></span></dt></dl></div>
<p>
The Java Persistence query language is a typed language, and every expression
has a type. The type of an expression is derived from the structure of the
expression, the abstract schema types of the identification variable
declarations, the types to which the persistent fields and relationships
evaluate, and the types of literals.
</p>
<p>
The abstract schema type of an entity or embeddable is
derived from the entity class and the metadata information provided by Java
language annotations or in the XML descriptor.
</p>
<p>
Informally, the abstract schema type of an entity or embeddable can be characterized as
follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
For every persistent field or get
accessor method (for a persistent property) of the entity class, there is a
field ("state-field") whose abstract schema type corresponds to that of the
field or the result type of the accessor method.
</p>
</li><li class="listitem">
<p>
For every persistent relationship field or get accessor method (for a persistent
relationship property) of the entity class, there is a field
("association-field") whose type is the abstract schema type of the related
entity (or, if the relationship is a one-to-many or many-to-many, a collection
of such).
</p>
</li></ul></div>
<p>
Abstract schema types are specific to the query language data model.
The persistence provider is not required to implement or otherwise materialize
an abstract schema type.
</p>
<p>
The domain of a query consists of the abstract schema
types of all entities and embeddables that are defined in the same persistence unit.
</p>
<p>
The domain
of a query may be restricted by the <code class="literal">navigability</code> of the relationships of the
entity and associated embeddable classes on which it is based. The association-fields of an entity's
or embeddable's abstract
schema type determine navigability. Using the association fields and their
values, a query can select related entities and use their abstract schema types
in the query.
</p>
<div class="section" id="jpa_langref_schemanaming"><div class="titlepage"><div><div><h4 class="title">2.2.1.&nbsp;
JPQL Entity Naming
</h4></div></div></div>
<p>
Entities are designated in query strings by their entity names. The entity name
is defined by the name element of the Entity annotation (or the entity-name XML
descriptor element), and defaults to the unqualified name of the entity class.
Entity names are scoped within the persistence unit and must be unique within
the persistence unit.
</p>
</div>
<div class="section" id="jpa_langref_schemaexample"><div class="titlepage"><div><div><h4 class="title">2.2.2.&nbsp;
JPQL Schema Example
</h4></div></div></div>
<p>
This example assumes that the application developer provides several entity
classes, representing magazines, publishers, authors, and articles. The abstract
schema types for these entities are <code class="literal">Magazine</code>, <code class="literal">
Publisher</code>, <code class="literal">Author</code>, and <code class="literal">Article</code>.
</p>
<p>
Several Entities with Abstract Persistence Schemas Defined in the Same
Persistence Unit. The entity <code class="literal">Publisher</code> has a one-to-many
relationships with <code class="literal">Magazine</code>. There is also a one-to-many
relationship between <code class="literal">Magazine</code> and <code class="literal">Article</code>
. The entity <code class="literal">Article</code> is related to <code class="literal">Author</code>
in a one-to-one relationship.
</p>
<p>
Queries to select magazines can be defined by navigating over the
association-fields and state-fields defined by <code class="literal">Magazine</code> and
<code class="literal">Author</code>. A query to
find all magazines that have unpublished articles is as follows:
</p>
<pre class="programlisting">
SELECT DISTINCT mag FROM Magazine AS mag JOIN mag.articles AS art WHERE art.published = FALSE
</pre>
<p>
This query navigates over the association-field <code class="literal">authors</code> of the
abstract schema type <code class="literal">Magazine</code> to find articles, and uses the
state-field <code class="literal">published</code> of <code class="literal">Article</code> to select
those magazines that have at least one article that is not published. Although
predefined reserved identifiers, such as <code class="literal">DISTINCT</code>, <code class="literal">
FROM</code>, <code class="literal">AS</code>, <code class="literal">JOIN</code>, <code class="literal">
WHERE</code>, and <code class="literal">FALSE</code> appear in upper case in this
example, predefined reserved identifiers are case insensitive.
</p>
<p>
The <code class="literal">
SELECT</code> clause of this example designates the return type of this
query to be of type <code class="literal">Magazine</code>.
</p>
<p>
Because the same persistence unit defines the
abstract persistence schemas of the related entities, the developer can also
specify a query over articles that utilizes the abstract
schema type for products, and hence the state-fields and association-fields of
both the abstract schema types <code class="literal">Magazine</code> and <code class="literal">Author</code>.
For example, if the
abstract schema type <code class="literal">Author</code> has a state-field named <code class="literal">firstName</code>,
a query over
articles can be specified using this state-field. Such a query might be to
find all magazines that have articles authored by someone with the first name
"John".
</p>
<pre class="programlisting">
SELECT DISTINCT mag FROM Magazine mag JOIN mag.articles art JOIN art.author auth WHERE auth.firstName = 'John'
</pre>
<p>
Because <code class="literal">Magazine</code> is related to <code class="literal">Author</code> by means of the
relationships between <code class="literal">Magazine</code> and <code class="literal">Article</code>
and between <code class="literal">Article</code> and <code class="literal">Author</code>,
navigation using the association-fields <code class="literal">authors</code> and
<code class="literal">product</code> is used to express
the query. This query is specified by using the abstract schema name <code class="literal">Magazine</code>,
which designates the abstract schema type over which the query ranges. The basis
for the navigation is provided by the association-fields <code class="literal">authors</code>
and <code class="literal">product</code> of
the abstract schema types <code class="literal">Magazine</code> and <code class="literal">Article</code> respectively.
</p>
</div>
</div>
<div class="section" id="jpa_langref_fromclause"><div class="titlepage"><div><div><h3 class="title">2.3.&nbsp;
JPQL FROM Clause and Navigational Declarations
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_from_identifiers">2.3.1.
JPQL FROM Identifiers
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_vars">2.3.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_range">2.3.3.
JPQL Range Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path">2.3.4.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_Joins">2.3.5.
JPQL Joins
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_inner_joins">2.3.5.1.
JPQL Inner Joins (Relationship Joins)
</a></span></dt><dt><span class="section"><a href="#jpa_langref_outer_joins">2.3.5.2.
JPQL Outer Joins
</a></span></dt><dt><span class="section"><a href="#jpa_langref_fetch_joins">2.3.5.3.
JPQL Fetch Joins
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_collection_dec">2.3.6.
JPQL Collection Member Declarations
</a></span></dt><dt><span class="section"><a href="#jpa_langref_from_clause_and_sql">2.3.7.
JPQL FROM Clause and SQL
</a></span></dt><dt><span class="section"><a href="#jpa_langref_polymorph">2.3.8.
JPQL Polymorphism
</a></span></dt></dl></div>
<p>
The <code class="literal">FROM</code> clause of a query defines the domain of the query by
declaring identification variables. An identification variable is an identifier
declared in the <code class="literal">FROM</code> clause of a query. The domain of the
query may be constrained by path expressions (See section <a class="xref" href="#jpa_langref_path" title="2.3.4.&nbsp; JPQL Path Expressions">Section&nbsp;2.3.4, &#8220;
JPQL Path Expressions
&#8221;</a>.
</p>
<p>
Identification variables designate
instances of a particular entity abstract schema type. The <code class="literal">FROM
</code> clause can contain multiple identification variable declarations
separated by a comma (,).
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
from_clause ::= FROM identification_variable_declaration {,
{identification_variable_declaration | collection_member_declaration}}*
</p>
</li><li class="listitem">
<p>
identification_variable_declaration ::= range_variable_declaration { join |
fetch_join }*
</p>
</li><li class="listitem">
<p>
range_variable_declaration ::= abstract_schema_name [AS] identification_variable
</p>
</li><li class="listitem">
<p>
join ::= join_spec join_association_path_expression [AS] identification_variable
</p>
</li><li class="listitem">
<p>
fetch_join ::= join_spec FETCH join_association_path_expression
</p>
</li><li class="listitem">
<p>
join_association_path_expression ::= join_collection_valued_path_expression |
join_single_valued_association_path_expression
</p>
</li><li class="listitem">
<p>
join_collection_valued_path_expression::=
identification_variable.{single_valued_embeddable_object_field.}*collection_valued_field
</p>
</li><li class="listitem">
<p>
join_single_valued_path_expression::=
identification_variable.{single_valued_embeddable_object_field.}*single_valued_object_field </p>
</li><li class="listitem">
<p>
join_spec ::= [ LEFT [OUTER] | INNER ] JOIN
</p>
</li><li class="listitem">
<p>
collection_member_declaration ::= IN (collection_valued_path_expression) [AS]
identification_variable
</p>
</li></ul></div>
<p>
The following subsections discuss the constructs used in the <code class="literal">FROM</code> clause.
</p>
<div class="section" id="jpa_langref_from_identifiers"><div class="titlepage"><div><div><h4 class="title">2.3.1.&nbsp;
JPQL FROM Identifiers
</h4></div></div></div>
<p>
An identifier is a character sequence of unlimited length. The character
sequence must begin with a Java identifier start character, and all other
characters must be Java identifier part characters. An identifier start
character is any character for which the method <code class="methodname">
Character.isJavaIdentifierStart</code> returns <code class="literal">true</code>.
This includes the underscore (_) character and the dollar sign ($) character. An
identifier part character is any character for which the method <code class="methodname">
Character.isJavaIdentifierPart</code> returns <code class="literal">true</code>.
The question mark (?) character is reserved for use by the Java Persistence
query language. The following are reserved identifiers:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">ABS</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ALL</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">AND</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ANY</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">AS</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ASC</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">AVG</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">BETWEEN</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">BOTH</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">BY</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CASE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CLASS</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">COALESCE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CONCAT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">COUNT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CURRENT_DATE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CURRENT_TIME</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CURRENT_TIMESTAMP</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">DELETE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">DESC</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">DISTINCT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ELSE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">EMPTY</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">END</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ENTRY</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ESCAPE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">EXISTS</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">FALSE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">FETCH</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">FROM</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">GROUP</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">HAVING</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">IN</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">INDEX</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">INNER</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">IS</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">JOIN</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">KEY</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">LEADING</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">LEFT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">LENGTH</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">LIKE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">LOCATE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">LOWER</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">MAX</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">MEMBER</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">MIN</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">MOD</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">NEW</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">NOT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">NULL</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">NULLIF</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">OBJECT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">OF</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">OR</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ORDER</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">OUTER</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">SELECT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">SET</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">SIZE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">SOME</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">SQRT</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">SIBSTRING</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">SUM</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">THEN</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">TRAILING</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">TRIM</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">TRUE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">TYPE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">UPDATE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">UPPER</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">VALUE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">WHEN</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">WHERE</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CHARACTER_LENGTH</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">CHAR_LENGTH</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">BIT_LENGTH</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">POSITION</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">UNKNOWN</code>
</p>
</li></ul></div>
<p>
Reserved identifiers are case insensitive. Reserved identifiers must not be
used as identification variables or result variables.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
It is recommended that other SQL reserved
words also not be used as identification variables in queries because they may be
used as reserved identifiers in future releases of the specification.
</p>
</div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
BIT_LENGTH, CHAR_LENGTH, CHARACTER_LENGTH, POSITION, and UNKNOWN are not currently used: they are
reserved for future use.
</p>
</div>
</div>
<div class="section" id="jpa_langref_from_vars"><div class="titlepage"><div><div><h4 class="title">2.3.2.&nbsp;
JPQL Identification Variables
</h4></div></div></div>
<p>
An identification variable is a valid identifier declared in the <code class="literal">FROM
</code> clause of a query.
</p>
<p>
All identification variables must be declared in
the <code class="literal">FROM</code> clause. Identification variables cannot be declared
in other clauses.
</p>
<p>
An identification variable must not be a reserved identifier
or have the same name as any entity in the same persistence unit.
</p>
<p>
Identification variables are case insensitive.
</p>
<p>
An identification variable evaluates to a value
of the type of the expression used in declaring the variable. For example,
consider the previous query: </p><pre class="programlisting">SELECT DISTINCT mag FROM Magazine mag JOIN mag.articles art JOIN art.author auth WHERE auth.firstName = 'John'
</pre><p>
In the <code class="literal">FROM</code> clause declaration <code class="literal">
mag.articles</code> <code class="literal">art</code>, the identification variable
<code class="literal">art</code> evaluates to any <code class="literal">Article</code> value
directly reachable from <code class="literal">Magazine</code>. The association-field
<code class="literal">articles</code> is a collection of instances of the abstract schema
type <code class="literal">Article</code> and the identification variable <code class="literal">art
</code> refers to an element of this collection. The type of <code class="literal">auth
</code> is the abstract schema type of <code class="literal">Author</code>.
</p>
<p>
An identification variable can range over an entity,
embeddable, or basic abstract schema type. An
identification variable designates an instance of an entity abstract schema type
or an element of a collection of entity abstract schema type instances.
</p>
<p>
Note that for identification variables referring to an instance of an association or collection represented
as a <code class="literal">java.util.Map</code>, the identification variable is of the abstract schema type of the map
<code class="literal">value</code>.
</p>
<p>
An
identification variable always designates a reference to a single value. It is
declared in one of three ways: in a range variable declaration, in a join
clause, or in a collection member declaration. The identification variable
declarations are evaluated from left to right in the <code class="literal">FROM</code>
clause, and an identification variable declaration can use the result of a
preceding identification variable declaration of the query string.
</p>
<p>
All identification variables used in the <code class="literal">SELECT</code>,
<code class="literal">WHERE</code>,
<code class="literal">ORDER BY</code>,
<code class="literal">GROUP BY</code>, or
<code class="literal">HAVING</code>
clause of a <code class="literal">SELECT</code> or
<code class="literal">DELETE</code> statement must be declared in the <code class="literal">FROM</code> clause.
The identification
variables used in the <code class="literal">WHERE</code> clause of
an <code class="literal">UPDATE</code> statement must be declared in the <code class="literal">UPDATE</code> clause.
</p>
<p>
Identification variables are existentially quantified in these clauses. This means that an identification
variable represents a member of a collection or an instance of an entity&#8217;s abstract schema type. An identification
variable never designates a collection in its entirety.
</p>
<p>
An identification variable is scoped to the query (or subquery) in which it is defined and is also visible
to any subqueries within that query scope that do not define an identification variable of the same name.
</p>
</div>
<div class="section" id="jpa_langref_range"><div class="titlepage"><div><div><h4 class="title">2.3.3.&nbsp;
JPQL Range Declarations
</h4></div></div></div>
<p>
The syntax for declaring an identification variable as a range variable is
similar to that of SQL; optionally, it uses the AS keyword. A range variable designates an
entity abstract schema type.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
A range variable must not designate an embeddable class abstract schema type.
</p>
</div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
range_variable_declaration ::= entity_name [AS]
identification_variable
</p>
</li></ul></div>
<p>
Range variable declarations allow the developer to designate a "root" for
objects which may not be reachable by navigation.
</p>
<p>
In order to select values by
comparing more than one instance of an entity abstract schema type, more than
one identification variable ranging over the abstract schema type is needed in
the <code class="literal">FROM</code> clause.
</p>
<p>
The following query returns magazines whose price is greater than the price of
magazines published by "Adventure" publishers. This example illustrates the use
of two different identification variables in the <code class="literal">FROM</code> clause,
both of the abstract schema type Magazine. The <code class="literal">SELECT</code> clause
of this query determines that it is the magazines with prices greater than those
of "Adventure" publisher's that are returned.
</p>
<pre class="programlisting">
SELECT DISTINCT mag1 FROM Magazine mag1, Magazine mag2
WHERE mag1.price &gt; mag2.price AND mag2.publisher.name = 'Adventure'
</pre>
</div>
<div class="section" id="jpa_langref_path"><div class="titlepage"><div><div><h4 class="title">2.3.4.&nbsp;
JPQL Path Expressions
</h4></div></div></div>
<p>
An identification variable followed by the navigation operator (.) and a
state-field or association-field is a path expression. The type of the path
expression is the type computed as the result of navigation; that is, the type
of the state-field or association-field to which the expression navigates.
</p>
<p>
An identification variable qualified by the <code class="literal">KEY</code>,
<code class="literal">VALUE</code>, or <code class="literal">ENTRY</code>
operator is a path expression. The
<code class="literal">KEY</code>, <code class="literal">VALUE</code>,
and <code class="literal">ENTRY</code> operators may only be applied to identification variables that correspond to
map-valued associations or map-valued element collections. The type of the path expression is the type
computed as the result of the operation; that is, the abstract schema type of the field that is the value of
the <code class="literal">KEY</code>,
<code class="literal">VALUE</code>, or <code class="literal">ENTRY</code>
operator (the map key, map value, or map entry respectively).
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Note that use of <code class="literal">VALUE</code> is optional,
as an identification variable referring to an association of type
<code class="literal">java.util.Map</code> is of the
abstract schema type of the map value.
</p>
</div>
<p>
The syntax for qualified identification variables is as follows.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
qualified_identification_variable :: =
KEY(identification_variable) |
VALUE(identification_variable) |
ENTRY(identification_variable)
</p>
</li></ul></div>
<p>
A path expression using the <code class="literal">KEY</code> or <code class="literal">VALUE</code>
operator may be further composed. A path expression
using the <code class="literal">ENTRY</code> operator is terminal.
It cannot be further composed and can only appear in the
<code class="literal">SELECT</code> list of a query.
</p>
<p>
In the following query, <code class="literal">photos</code> is a map from photo label to filename.
</p>
<pre class="programlisting">
SELECT i.name, VALUE(p)
FROM Item i JOIN i.photos p
WHERE KEY(p) LIKE &#8216;egret&#8217;
</pre>
<p>
In the above query the identification variable <code class="literal">p</code> designates
an abstract schema type corresponding to the
map value. The results of <code class="literal">VALUE(p)</code> and <code class="literal">KEY(p)</code>
are the map value and the map key associated with
p, respectively. The following query is equivalent:
</p>
<pre class="programlisting">
SELECT i.name, p
FROM Item i JOIN i.photos p
WHERE KEY(p) LIKE &#8216;egret&#8217;
</pre>
<p>
Depending on navigability, a path expression that leads to a association-field
or to a field whose type is an embeddable class
may be further composed. Path expressions can be composed from other path
expressions if the original path expression evaluates to a single-valued type
(not a collection) corresponding to a association-field.
</p>
<p>
In the following example, <code class="literal">contactInfo</code> denotes an embeddable
class consisting of an address and
set of phones. <code class="literal">Phone</code> is an entity.
</p>
<pre class="programlisting">
SELECT p.vendor
FROM Employee e JOIN e.contactInfo.phones p
WHERE e.contactInfo.address.zipcode = '95054'
</pre>
<p>
Path expression
navigability is composed using "inner join" semantics. That is, if the value of
a non-terminal association-field in the path expression is null, the path is
considered to have no value, and does not participate in the determination of
the result.
</p>
<p>
The following query is equivalent to the query above:
</p>
<pre class="programlisting">
SELECT p.vendor
FROM Employee e JOIN e.contactInfo c JOIN c.phones p
WHERE e.contactInfo.address.zipcode = '95054'
</pre>
<p>
The syntax for single-valued path expressions and collection valued
path expressions is as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
single_valued_path_expression ::=
qualified_identification_variable |
state_field_path_expression |
single_valued_object_path_expression
</p>
</li><li class="listitem">
<p>
state_field_path_expression ::=
general_identification_variable.{single_valued_object_field.}*state_field
</p>
</li><li class="listitem">
<p>
single_valued_object_path_expression ::=
general_identification_variable.{single_valued_object_field.}*single_valued_object_field
</p>
</li><li class="listitem">
<p>
collection_valued_path_expression ::=
general_identification_variable.{single_valued_object_field.}*collection_valued_field
</p>
</li></ul></div>
<p>
A <code class="literal">single_valued_object_field</code> is designated by the name of an
association-field in a one-to-one or many-to-one relationship
or a field of embeddable class type. The type of a
<code class="literal">single_valued_object_field</code> is the abstract schema type of the
related entity or embeddable class.
</p>
<p>
A <code class="literal">state_field</code> is designated by the name of an entity or
embeddable class state field that corresponds to
a basic type.
</p>
<p>
A collection_valued_field is designated by the name
of an association-field in a one-to-many or a many-to-many relationship
or by the name of an element collection field. The
type of a <code class="literal">collection_valued_field</code> is
a collection of values of the
abstract schema type of the related entity
or element type.
</p>
<p>
An identification variable used in a
<code class="literal">single_valued_object_path_expression</code> or in a
<code class="literal">collection_valued_path_expression</code>
may be an unqualified identification variable or an identification
variable to which the KEY or VALUE function has been applied.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
general_identification_variable ::=
identification_variable |
KEY(identification_variable) |
VALUE(identification_variable)
</p>
</li></ul></div>
<p>
It is syntactically illegal to compose a path expression from a
path expression that evaluates to a collection. For example, if <code class="literal">mag
</code> designates <code class="literal">Magazine</code>, the path expression <code class="literal">
mag.articles.author</code> is illegal since navigation to authors results in
a collection. This case should produce an error when the query string is
verified. To handle such a navigation, an identification variable must be
declared in the <code class="literal">FROM</code> clause to range over the elements of the
<code class="literal">articles</code> collection. Another path expression must be used to
navigate over each such element in the <code class="literal">WHERE</code> clause of the
query, as in the following query which returns all authors that have any
articles in any magazines:
</p>
<pre class="programlisting">
SELECT DISTINCT art.author FROM Magazine AS mag, IN(mag.articles) art
</pre>
<p>
It is illegal to use a <code class="literal">collection_valued_path_expression</code> other than
in the <code class="literal">FROM</code> clause of a query
except in an <code class="literal">empty_collection_comparison_expression</code>,
in a <code class="literal">collection_member_expression</code>, or
as an argument to the <code class="literal">SIZE</code> operator.
See <a class="xref" href="#jpa_langref_empty_comp" title="2.5.12.&nbsp; JPQL Empty Collection Comparison Expressions">Section&nbsp;2.5.12, &#8220;
JPQL Empty Collection Comparison Expressions
&#8221;</a>, <a class="xref" href="#jpa_langref_collection_member" title="2.5.13.&nbsp; JPQL Collection Member Expressions">Section&nbsp;2.5.13, &#8220;
JPQL Collection Member Expressions
&#8221;</a>,
and <a class="xref" href="#jpa_langref_arithmetic" title="2.6.2.2.&nbsp; JPQL Arithmetic Functions">Section&nbsp;2.6.2.2, &#8220;
JPQL Arithmetic Functions
&#8221;</a>.
</p>
</div>
<div class="section" id="jpa_langref_Joins"><div class="titlepage"><div><div><h4 class="title">2.3.5.&nbsp;
JPQL Joins
</h4></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_inner_joins">2.3.5.1.
JPQL Inner Joins (Relationship Joins)
</a></span></dt><dt><span class="section"><a href="#jpa_langref_outer_joins">2.3.5.2.
JPQL Outer Joins
</a></span></dt><dt><span class="section"><a href="#jpa_langref_fetch_joins">2.3.5.3.
JPQL Fetch Joins
</a></span></dt></dl></div>
<p>
An inner join may be implicitly specified by the use of a cartesian product in
the <code class="literal">FROM</code> clause and a join condition in the <code class="literal">WHERE
</code> clause. In the absence of a join condition, this reduces to the cartesian product.
</p>
<p>
The main use case for this generalized style of join is when a join condition does not involve
a foreign key relationship that is mapped to an entity relationship, for example:
</p>
<pre class="programlisting">SELECT c FROM Customer c, Employee e WHERE c.hatsize = e.shoesize</pre>
<p>
In general, use of this style of inner join (also referred to as theta-join) is less typical than explicitly
defined joins over relationships.
</p>
<p>
The syntax for explicit join operations is as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
join ::= join_spec join_association_path_expression [AS] identification_variable
</p>
</li><li class="listitem">
<p>
fetch_join ::= join_spec FETCH join_association_path_expression
</p>
</li><li class="listitem">
<p>
join_association_path_expression ::= join_collection_valued_path_expression |
join_single_valued_path_expression
</p>
</li><li class="listitem">
<p>
join_collection_valued_path_expression::=
identification_variable.{single_valued_embeddable_object_field.}*collection_valued_field
</p>
</li><li class="listitem">
<p>
join_single_valued_path_expression::=
identification_variable.{single_valued_embeddable_object_field.}*single_valued_object_field
</p>
</li><li class="listitem">
<p>
join_spec ::= [ LEFT [OUTER] | INNER ] JOIN
</p>
</li></ul></div>
<p>
The inner and outer join operation types described in
<a class="xref" href="#jpa_langref_inner_joins" title="2.3.5.1.&nbsp; JPQL Inner Joins (Relationship Joins)">Section&nbsp;2.3.5.1, &#8220;
JPQL Inner Joins (Relationship Joins)
&#8221;</a> and <a class="xref" href="#jpa_langref_outer_joins" title="2.3.5.2.&nbsp; JPQL Outer Joins">Section&nbsp;2.3.5.2, &#8220;
JPQL Outer Joins
&#8221;</a> are supported.
</p>
<div class="section" id="jpa_langref_inner_joins"><div class="titlepage"><div><div><h5 class="title">2.3.5.1.&nbsp;
JPQL Inner Joins (Relationship Joins)
</h5></div></div></div>
<p>
The syntax for the inner join operation is </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
[ INNER ] JOIN join_association_path_expression [AS] identification_variable
</li></ul></div><p> For example, the query below joins over the relationship
between publishers and magazines. This type of join typically equates to a join
over a foreign key relationship in the database.
</p>
<pre class="programlisting">
SELECT pub FROM Publisher pub JOIN pub.magazines mag WHERE pub.revenue &gt; 1000000
</pre>
<p>
The keyword <code class="literal">INNER</code> may optionally be used:
</p>
<pre class="programlisting">
SELECT pub FROM Publisher pub INNER JOIN pub.magazines mag WHERE pub.revenue &gt; 1000000
</pre>
<p>
This is equivalent to the following query using the earlier
<code class="literal">IN</code> construct. It selects those publishers with revenue of
over 1 million for which at least one magazine exists:
</p>
<pre class="programlisting">
SELECT OBJECT(pub) FROM Publisher pub, IN(pub.magazines) mag WHERE pub.revenue &gt; 1000000
</pre>
<p>
The query below joins over Employee, ContactInfo and Phone. ContactInfo is an
embeddable class that consists of an address and set of phones. Phone is an entity.
</p>
<pre class="programlisting">
SELECT p.vendor
FROM Employee e JOIN e.contactInfo c JOIN c.phones p
WHERE c.address.zipcode = '95054'
</pre>
</div>
<div class="section" id="jpa_langref_outer_joins"><div class="titlepage"><div><div><h5 class="title">2.3.5.2.&nbsp;
JPQL Outer Joins
</h5></div></div></div>
<p>
<code class="literal">LEFT JOIN</code> and <code class="literal">LEFT OUTER JOIN</code> are
synonymous. They enable the retrieval of a set of entities where matching values
in the join condition may be absent. The syntax for a left outer join is:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">LEFT [OUTER] JOIN join_association_path_expression [AS] identification_variable
</li></ul></div><p>
</p>
<p>
For example: </p><pre class="programlisting">SELECT pub FROM Publisher pub LEFT JOIN pub.magazines mag WHERE pub.revenue &gt; 1000000
</pre><p> The keyword <code class="literal">OUTER</code> may optionally be used:
</p><pre class="programlisting">SELECT pub FROM Publisher pub LEFT OUTER JOIN pub.magazines mags WHERE pub.revenue &gt; 1000000
</pre><p> An important use case for <code class="literal">LEFT JOIN</code> is in
enabling the prefetching of related data items as a side effect of a query. This
is accomplished by specifying the <code class="literal">LEFT JOIN</code> as a <code class="literal">
FETCH JOIN</code>.
</p>
</div>
<div class="section" id="jpa_langref_fetch_joins"><div class="titlepage"><div><div><h5 class="title">2.3.5.3.&nbsp;
JPQL Fetch Joins
</h5></div></div></div>
<p>
A <code class="literal">FETCH JOIN</code> enables the fetching of an association as a side
effect of the execution of a query. A <code class="literal">FETCH JOIN</code> is specified
over an entity and its related entities. The syntax for a fetch join is
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>fetch_join ::= [ LEFT [OUTER] | INNER ] JOIN
FETCH join_association_path_expression
</p>
</li></ul></div><p>
</p>
<p>
The association referenced by the right side of the <code class="literal">FETCH JOIN
</code> clause must be an association that belongs to an entity that is
returned as a result of the query. It is not permitted to specify an
identification variable for the entities referenced by the right side of the
<code class="literal">FETCH JOIN</code> clause, and hence references to the implicitly
fetched entities cannot appear elsewhere in the query.
</p>
<p>
The following query
returns a set of magazines. As a side effect, the associated articles for those
magazines are also retrieved, even though they are not part of the explicit
query result. The persistent fields or properties of the articles that are
eagerly fetched are fully initialized. The initialization of the relationship
properties of the <code class="literal">articles</code> that are retrieved is determined
by the metadata for the <code class="literal">Article</code> entity class.
</p><pre class="programlisting">SELECT mag FROM Magazine mag LEFT JOIN FETCH mag.articles WHERE mag.id = 1
</pre><p>
</p>
<p>
A fetch join has the same join semantics as the corresponding inner or outer
join, except that the related objects specified on the right-hand side of the
join operation are not returned in the query result or otherwise referenced in
the query. Hence, for example, if magazine id 1 has five articles, the above
query returns five references to the magazine 1 entity.
</p>
<p>
The <code class="literal">FETCH JOIN</code> construct must not be used in the FROM clause of a subquery.
</p>
</div>
</div>
<div class="section" id="jpa_langref_collection_dec"><div class="titlepage"><div><div><h4 class="title">2.3.6.&nbsp;
JPQL Collection Member Declarations
</h4></div></div></div>
<p>
An identification variable declared by a <code class="literal">collection_member_declaration</code> ranges
over values of a collection obtained by navigation using a path expression. Such
a path expression represents a navigation involving the association-fields of an
entity abstract schema type. Because a path expression can be based on another
path expression, the navigation can use the association-fields of related
entities.
</p>
<p>
An identification variable of a collection member declaration is
declared using a special operator, the reserved identifier <code class="literal">IN</code>
. The argument to the <code class="literal">IN</code> operator is a collection-valued path
expression. The path expression evaluates to a collection type specified as a
result of navigation to a collection-valued association-field of an entity
or embeddable class
abstract schema type.
</p>
<p>
The syntax for declaring a collection member
identification variable is as follows:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>collection_member_declaration ::= IN
(collection_valued_path_expression) [AS] identification_variable
</p>
</li></ul></div><p>
</p>
<p>
For example, the query </p><pre class="programlisting">SELECT DISTINCT mag FROM Magazine mag
JOIN mag.articles art
JOIN art.author auth
WHERE auth.lastName = 'Grisham'</pre><p> can equivalently be
expressed as follows, using the <code class="literal">IN</code> operator: </p><pre class="programlisting">SELECT DISTINCT mag FROM Magazine mag,
IN(mag.articles) art
WHERE art.author.lastName = 'Grisham'</pre><p> In this example,
<code class="literal">articles</code> is the name of an association-field whose value is a
collection of instances of the abstract schema type <code class="literal">Article</code>.
The identification variable <code class="literal">art</code> designates a member of this
collection, a single <code class="literal">Article</code> abstract schema type instance.
In this example, <code class="literal">mag</code> is an identification variable of the
abstract schema type <code class="literal">Magazine</code>.
</p>
</div>
<div class="section" id="jpa_langref_from_clause_and_sql"><div class="titlepage"><div><div><h4 class="title">2.3.7.&nbsp;
JPQL FROM Clause and SQL
</h4></div></div></div>
<p>
The Java Persistence query language treats the FROM clause similarly to SQL in that the declared identification
variables affect the results of the query even if they are not used in the WHERE clause. Application
developers should use caution in defining identification variables because the domain of the
query can depend on whether there are any values of the declared type.
</p>
<p>
For example, the <code class="literal">FROM</code> clause below defines a query over
all orders that have line items and existing
products. If there are no <code class="literal">Product</code> instances in the database,
the domain of the query is empty and no
order is selected.
</p>
<pre class="programlisting">
SELECT o
FROM Order AS o JOIN o.lineItems l JOIN l.product p
</pre>
</div>
<div class="section" id="jpa_langref_polymorph"><div class="titlepage"><div><div><h4 class="title">2.3.8.&nbsp;
JPQL Polymorphism
</h4></div></div></div>
<p>
Java Persistence queries are automatically polymorphic. The <code class="literal">FROM
</code> clause of a query designates not only instances of the specific
entity classes to which explicitly refers but of subclasses as well. The
instances returned by a query include instances of the subclasses that satisfy
the query criteria.
</p>
<p>
Non-polymorphic queries or queries whose polymorphism is restricted can be specified using entity
type expressions in the <code class="literal">WHERE</code> clause to restrict the domain of the query.
See <a class="xref" href="#jpa_langref_entity_type_expressions" title="2.6.4.&nbsp; Entity Type Expressions">Section&nbsp;2.6.4, &#8220;
Entity Type Expressions
&#8221;</a>.
</p>
</div>
</div>
<div class="section" id="jpa_langref_where"><div class="titlepage"><div><div><h3 class="title">2.4.&nbsp;
JPQL WHERE Clause
</h3></div></div></div>
<p>
The <code class="literal">WHERE</code> clause of a query consists of a conditional
expression used to select objects or values that satisfy the expression. The
<code class="literal">WHERE</code> clause restricts the result of a select statement or
the scope of an update or delete operation.
</p>
<p>
A <code class="literal">WHERE</code> clause is
defined as follows: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>where_clause ::= WHERE
conditional_expression
</p>
</li></ul></div><p>
</p>
<p>
The <code class="literal">GROUP BY</code> construct enables the aggregation of values
according to the properties of an entity class. The <code class="literal">HAVING</code>
construct enables conditions to be specified that further restrict the query
result as restrictions upon the groups.
</p>
<p>
The syntax of the <code class="literal">HAVING
</code> clause is as follows: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>having_clause
::= HAVING conditional_expression
</p>
</li></ul></div><p>
</p>
<p>
The <code class="literal">GROUP BY</code> and <code class="literal">HAVING</code> constructs are
further discussed in <a class="xref" href="#jpa_langref_group" title="2.7.&nbsp; JPQL GROUP BY, HAVING">Section&nbsp;2.7, &#8220;
JPQL GROUP BY, HAVING
&#8221;</a>.
</p>
</div>
<div class="section" id="jpa_langref_cond"><div class="titlepage"><div><div><h3 class="title">2.5.&nbsp;
JPQL Conditional Expressions
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_lit">2.5.1.
JPQL Literals
</a></span></dt><dt><span class="section"><a href="#jpa_langref_idvar">2.5.2.
JPQL Identification Variables
</a></span></dt><dt><span class="section"><a href="#jpa_langref_path_exp">2.5.3.
JPQL Path Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_input_params">2.5.4.
JPQL Input Parameters
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_pos_params">2.5.4.1.
JPQL Positional Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_langref_named_params">2.5.4.2.
JPQL Named Parameters
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_cond_comp">2.5.5.
JPQL Conditional Expression Composition
</a></span></dt><dt><span class="section"><a href="#jpa_langref_operators">2.5.6.
JPQL Operators and Operator Precedence
</a></span></dt><dt><span class="section"><a href="#jpa_langref_comparison_expressions">2.5.7.
JPQL Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_between">2.5.8.
JPQL Between Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_in_expressions">2.5.9.
JPQL In Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_like">2.5.10.
JPQL Like Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null">2.5.11.
JPQL Null Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_empty_comp">2.5.12.
JPQL Empty Collection Comparison Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_collection_member">2.5.13.
JPQL Collection Member Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_exists">2.5.14.
JPQL Exists Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_all_any">2.5.15.
JPQL All or Any Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_subqueries">2.5.16.
JPQL Subqueries
</a></span></dt></dl></div>
<p>
The following sections describe the language constructs that can be used in a
conditional expression of the <code class="literal">WHERE</code> clause or <code class="literal">
HAVING</code> clause.
</p>
<p>
State-fields that are mapped in serialized form or as
LOBs may not be portably used in conditional expressions. </p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3><p> The
implementation is not expected to perform such query operations involving such
fields in memory rather than in the database.
</p>
</div><p>
</p>
<div class="section" id="jpa_langref_lit"><div class="titlepage"><div><div><h4 class="title">2.5.1.&nbsp;
JPQL Literals
</h4></div></div></div>
<p>
A string literal is enclosed in single quotes--for example: 'literal'. A string
literal that includes a single quote is represented by two single quotes--for
example: 'literal''s'. String literals in queries, like Java String literals,
use unicode character encoding. The use of Java escape notation is not supported
in query string literals.
</p>
<p>
Exact numeric literals support the use of Java integer
literal syntax as well as SQL exact numeric literal syntax.
</p>
<p>
Approximate literals
support the use of Java floating point literal syntax as well as SQL approximate
numeric literal syntax.
</p>
<p>
Enum literals support the use of Java enum literal
syntax. The enum class name must be specified.
</p>
<p>
Appropriate suffixes can be used
to indicate the specific type of a numeric literal in accordance with the Java
Language Specification. The boolean literals are <code class="literal">TRUE</code> and
<code class="literal">FALSE</code>. Although predefined reserved literals appear in upper
case, they are case insensitive.
</p>
<p>
The JDBC escape syntax may be used for the specification of date, time, and timestamp literals. For
example:
</p>
<pre class="programlisting">
SELECT o
FROM Customer c JOIN c.orders o
WHERE c.name = 'Smith'
AND o.submissionDate &lt; {d '2008-12-31'}
</pre>
<p>
Date, time, and timestamp literals are passed as is to the JDBC driver
in use.
</p>
<p>
Entity type literals are specified by entity names&#8212;for example: <code class="literal">Customer</code>.
</p>
<p>
Although reserved literals appear in upper case, they are case insensitive.
</p>
</div>
<div class="section" id="jpa_langref_idvar"><div class="titlepage"><div><div><h4 class="title">2.5.2.&nbsp;
JPQL Identification Variables
</h4></div></div></div>
<p>
All identification variables used in the <code class="literal">WHERE</code> or <code class="literal">
HAVING</code> clause of a <code class="literal">SELECT</code> or <code class="literal">DELETE
</code> statement must be declared in the <code class="literal">FROM</code> clause, as
described in <a class="xref" href="#jpa_langref_from_vars" title="2.3.2.&nbsp; JPQL Identification Variables">Section&nbsp;2.3.2, &#8220;
JPQL Identification Variables
&#8221;</a>. The identification
variables used in the <code class="literal">WHERE</code> clause of an <code class="literal">UPDATE
</code> statement must be declared in the <code class="literal">UPDATE</code> clause.
</p>
<p>
Identification variables are existentially quantified in the <code class="literal">WHERE
</code> and <code class="literal">HAVING</code> clause. This means that an
identification variable represents a member of a collection or an instance of an
entity's abstract schema type. An identification variable never designates a
collection in its entirety.
</p>
</div>
<div class="section" id="jpa_langref_path_exp"><div class="titlepage"><div><div><h4 class="title">2.5.3.&nbsp;
JPQL Path Expressions
</h4></div></div></div>
<p>
It is illegal to use a <code class="literal">collection_valued_path_expression</code> within a <code class="literal">
WHERE</code> or <code class="literal">HAVING</code> clause as part of a conditional
expression except in an <code class="literal">empty_collection_comparison_expression</code>, in a
<code class="literal">collection_member_expression</code>, or as an argument to the <code class="literal">SIZE</code>
operator.
</p>
</div>
<div class="section" id="jpa_langref_input_params"><div class="titlepage"><div><div><h4 class="title">2.5.4.&nbsp;
JPQL Input Parameters
</h4></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_pos_params">2.5.4.1.
JPQL Positional Parameters
</a></span></dt><dt><span class="section"><a href="#jpa_langref_named_params">2.5.4.2.
JPQL Named Parameters
</a></span></dt></dl></div>
<p>
Either positional or named parameters may be used. Positional and named
parameters may not be mixed in a single query.
</p>
<p>
Input parameters can only be used
in the <code class="literal">WHERE</code> clause or <code class="literal">HAVING</code> clause of a
query.
</p>
<p>
Note that if an input parameter value is null, comparison operations or
arithmetic operations involving the input parameter will return an unknown
value. See <a class="xref" href="#jpa_langref_null_values" title="2.11.&nbsp; JPQL Null Values">Section&nbsp;2.11, &#8220;
JPQL Null Values
&#8221;</a>.
</p>
<p>
All input parameters must be single-valued, except in IN expressions (see
<a class="xref" href="#jpa_langref_in_expressions" title="2.5.9.&nbsp; JPQL In Expressions">Section&nbsp;2.5.9, &#8220;
JPQL In Expressions
&#8221;</a> ), which support the use of collection-valued
input parameters.
</p>
<div class="section" id="jpa_langref_pos_params"><div class="titlepage"><div><div><h5 class="title">2.5.4.1.&nbsp;
JPQL Positional Parameters
</h5></div></div></div>
<p>
The following rules apply to positional parameters. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p> Input parameters are designated by the question mark (?) prefix followed
by an integer. For example: ?1.
</p>
</li><li class="listitem">
<p>
Input parameters are numbered starting from 1.
</p>
</li><li class="listitem">
<p>
The same parameter can
be used more than once in the query string.
</p>
</li><li class="listitem">
<p>
The ordering of the use of
parameters within the query string need not conform to the order of the
positional parameters.
</p>
</li></ul></div><p>
</p>
</div>
<div class="section" id="jpa_langref_named_params"><div class="titlepage"><div><div><h5 class="title">2.5.4.2.&nbsp;
JPQL Named Parameters
</h5></div></div></div>
<p>
A named parameter is an identifier that is prefixed by the ":" symbol. It
follows the rules for identifiers defined in
<a class="xref" href="#jpa_langref_from_identifiers" title="2.3.1.&nbsp; JPQL FROM Identifiers">Section&nbsp;2.3.1, &#8220;
JPQL FROM Identifiers
&#8221;</a>. Named parameters are case
sensitive.
</p>
<p>
Example: </p><pre class="programlisting">SELECT pub FROM Publisher pub WHERE pub.revenue &gt; :rev
</pre><p>
</p>
<p>
The same named parameter can be used more than once in the query string.
</p>
</div>
</div>
<div class="section" id="jpa_langref_cond_comp"><div class="titlepage"><div><div><h4 class="title">2.5.5.&nbsp;
JPQL Conditional Expression Composition
</h4></div></div></div>
<p>
Conditional expressions are composed of other conditional expressions,
comparison operations, logical operations, path expressions that evaluate to
boolean values, boolean literals, and boolean input parameters.
</p>
<p>
The scalar expressions described in <a class="xref" href="#jpa_langref_scalar_expressions" title="2.6.&nbsp; JPQL Scalar Expressions">Section&nbsp;2.6, &#8220;
JPQL Scalar Expressions
&#8221;</a>
can be used in conditional expressions.
</p>
<p>
Standard bracketing ()
for ordering expression evaluation is supported.
</p>
<p>
Aggregate functions can only be used in conditional expressions in a <code class="literal">
HAVING</code> clause. See <a class="xref" href="#jpa_langref_group" title="2.7.&nbsp; JPQL GROUP BY, HAVING">Section&nbsp;2.7, &#8220;
JPQL GROUP BY, HAVING
&#8221;</a>.
</p>
<p>
Conditional expressions are
defined as follows:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>conditional_expression ::= conditional_term |
conditional_expression OR conditional_term
</p>
</li><li class="listitem">
<p>
conditional_term ::= conditional_factor | conditional_term AND
conditional_factor
</p>
</li><li class="listitem">
<p>
conditional_factor ::= [ NOT ] conditional_primary
</p>
</li><li class="listitem">
<p>
conditional_primary ::= simple_cond_expression | (conditional_expression)
</p>
</li><li class="listitem">
<p>
simple_cond_expression ::= comparison_expression | between_expression |
like_expression | in_expression | null_comparison_expression |
empty_collection_comparison_expression | collection_member_expression |
exists_expression
</p>
</li></ul></div><p>
</p>
</div>
<div class="section" id="jpa_langref_operators"><div class="titlepage"><div><div><h4 class="title">2.5.6.&nbsp;
JPQL Operators and Operator Precedence
</h4></div></div></div>
<p>
The operators are listed below in order of decreasing precedence. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> Navigation operator (.)
</p>
</li><li class="listitem">
<p>
Arithmetic operators: +, - unary *, / multiplication and division +, - addition
and subtraction
</p>
</li><li class="listitem">
<p>
Comparison operators: =, &gt;, &gt;=, &lt;, &lt;=, &lt;&gt; (not equal), [
<code class="literal">NOT</code> ] <code class="literal">BETWEEN</code>, [ <code class="literal">NOT</code> ]
<code class="literal">LIKE</code>, [ <code class="literal">NOT</code> ] <code class="literal">IN</code>,
<code class="literal">IS</code> [ <code class="literal">NOT</code> ] <code class="literal">NULL</code>,
<code class="literal">IS</code> [ <code class="literal">NOT</code> ] <code class="literal">EMPTY</code>, [
<code class="literal">NOT</code> ] <code class="literal">MEMBER</code> [ <code class="literal">OF</code> ]
</p>
</li><li class="listitem">
<p>
Logical operators: <code class="literal">NOT</code>, <code class="literal">AND</code>,
<code class="literal">OR</code>
</p>
</li></ul></div><p>
The following sections describe other operators used in specific expressions.
</p>
</div>
<div class="section" id="jpa_langref_comparison_expressions"><div class="titlepage"><div><div><h4 class="title">2.5.7.&nbsp;
JPQL Comparison Expressions
</h4></div></div></div>
<p>
The syntax for the use of comparison expressions in a conditional expression is as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
comparison_expression ::=
string_expression comparison_operator {string_expression | all_or_any_expression} |
boolean_expression { =|&lt;&gt; } {boolean_expression | all_or_any_expression} |
enum_expression { =|&lt;&gt; } {enum_expression | all_or_any_expression} |
datetime_expression comparison_operator
{datetime_expression | all_or_any_expression} |
entity_expression { = | &lt;&gt; } {entity_expression | all_or_any_expression} |
arithmetic_expression comparison_operator
{arithmetic_expression | all_or_any_expression} |
entity_type_expression { = | &lt;&gt; } entity_type_expression}
</p>
</li><li class="listitem">
<p>
comparison_operator ::= = | &gt; | &gt;= | &lt; | &lt;= | &lt;&gt;
</p>
</li></ul></div>
<p>
Examples:
</p>
<pre class="programlisting">
item.cost * 1.08 &lt;= 100.00
</pre>
<pre class="programlisting">
CONCAT(person.lastName, &#8216;, &#8217;, person.firstName)) = &#8216;Jones, Sam&#8217;
</pre>
<pre class="programlisting">
TYPE(e) = ExemptEmployee
</pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
Comparisons over instances of embeddable class types are not supported.
</div>
</div>
<div class="section" id="jpa_langref_between"><div class="titlepage"><div><div><h4 class="title">2.5.8.&nbsp;
JPQL Between Expressions
</h4></div></div></div>
<p>
The syntax for the use of the comparison operator [ <code class="literal">NOT</code> ]
<code class="literal">BETWEEN</code> in a conditional expression is as follows:
</p>
<p>
arithmetic_expression [NOT] BETWEEN arithmetic_expression AND
arithmetic_expression | string_expression [NOT] BETWEEN string_expression AND
string_expression | datetime_expression [NOT] BETWEEN datetime_expression AND
datetime_expression
</p>
<p>
The BETWEEN expression </p><pre class="programlisting">x BETWEEN y AND z</pre><p> is
semantically equivalent to: </p><pre class="programlisting">y &lt;= x AND x &lt;= z
</pre><p> The rules for unknown and <code class="literal">NULL</code> values in
comparison operations apply. See <a class="xref" href="#jpa_langref_null_values" title="2.11.&nbsp; JPQL Null Values">Section&nbsp;2.11, &#8220;
JPQL Null Values
&#8221;</a>
.
</p>
<p>
Examples are: </p><pre class="programlisting">p.age BETWEEN 15 and 19</pre><p> is
equivalent to: </p><pre class="programlisting">p.age &gt;= 15 AND p.age &lt;= 19</pre><p>
</p>
<p>
The following expression:
</p><pre class="programlisting">p.age NOT BETWEEN 15 and 19</pre><p> excludes the range, and is equivalent to:
</p><pre class="programlisting">p.age &lt; 15 OR p.age &gt; 19</pre><p>
</p>
<p>
In the following example, <code class="literal">transactionHistory</code> is a list of credit card
transactions defined using an order column.
</p>
<pre class="programlisting">
SELECT t
FROM CreditCard c JOIN c.transactionHistory t
WHERE c.holder.name = &#8216;John Doe&#8217; AND INDEX(t) BETWEEN 0 AND 9
</pre>
</div>
<div class="section" id="jpa_langref_in_expressions"><div class="titlepage"><div><div><h4 class="title">2.5.9.&nbsp;
JPQL In Expressions
</h4></div></div></div>
<p>
The syntax for the use of the comparison operator [ <code class="literal">NOT</code> ]
<code class="literal">IN</code> in a conditional expression is as follows:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>in_expression ::= state_field_path_expression
[NOT] IN {( in_item {, in_item}* ) | (subquery) | collection_valued_input_parameter }
</p>
</li><li class="listitem">
<p>
in_item ::= literal | single_valued_input_parameter
</p>
</li></ul></div><p>
</p>
<p>
The <code class="literal">state_field_path_expression</code> must have a string, numeric,
date, time, timestamp, or enum value.
</p>
<p>
The literal and/or input_parameter values must be <code class="literal">like</code>
the same abstract schema type
of the <code class="literal">state_field_path_expression</code> in type. (See
<a class="xref" href="#jpa_langref_equality" title="2.12.&nbsp; JPQL Equality and Comparison Semantics">Section&nbsp;2.12, &#8220;
JPQL Equality and Comparison Semantics
&#8221;</a> ).
</p>
<p>
The results of the subquery must be <code class="literal">like</code> the same abstract schema type of the
<code class="literal">state_field_path_expression</code> in type. Subqueries are discussed in
<a class="xref" href="#jpa_langref_subqueries" title="2.5.16.&nbsp; JPQL Subqueries">Section&nbsp;2.5.16, &#8220;
JPQL Subqueries
&#8221;</a>.
</p>
<p>
Examples:
</p>
<pre class="programlisting">o.country IN ('UK', 'US', 'France')
</pre> is true for UK and false for Peru, and is equivalent to the
expression: <pre class="programlisting">(o.country = 'UK') OR (o.country = 'US') OR (o.country = ' France')
</pre> In the following expression: <pre class="programlisting">o.country NOT IN ('UK', 'US', 'France')
</pre> is false for UK and true for Peru, and is equivalent to the
expression: <pre class="programlisting">NOT ((o.country = 'UK') OR (o.country = 'US') OR (o.country = 'France'))
</pre>
<p>
There must be at least one element in the comma separated list
that defines the set of values for the <code class="literal">IN</code> expression.
</p>
<p>
If the
value of a <code class="literal">state_field_path_expression</code> or <code class="literal">in_item</code>
in an <code class="literal">IN</code> or <code class="literal">
NOT IN</code> expression is <code class="literal">NULL</code> or unknown, the value of
the expression is unknown.
</p>
<p>
Note that use of a collection-valued input parameter will mean that a static query cannot
be precompiled.
</p>
</div>
<div class="section" id="jpa_langref_like"><div class="titlepage"><div><div><h4 class="title">2.5.10.&nbsp;
JPQL Like Expressions
</h4></div></div></div>
<p>
The syntax for the use of the comparison operator [ <code class="literal">NOT</code> ]
<code class="literal">LIKE</code> in a conditional expression is as follows:
</p>
<p>
like_expression ::=
string_expression [NOT] LIKE <code class="literal">pattern_value</code> [ESCAPE <code class="literal">escape_character</code>]
</p>
<p>
The <code class="literal">string_expression</code> must have a string value.
The <code class="literal">pattern_value</code> is a string
literal or a string-valued input parameter in which an underscore (_) stands for
any single character, a percent (%) character stands for any sequence of
characters (including the empty sequence), and all other characters stand for
themselves. The optional escape_character is a single-character string literal
or a character-valued input parameter (i.e., char or Character) and is used to
escape the special meaning of the underscore and percent characters in
pattern_value. </p>
<p>
Examples:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><pre class="programlisting">address.phone LIKE '12%3'
</pre><p> is true for '123' '12993' and false for '1234'
</p>
</li><li class="listitem">
<p>
</p><pre class="programlisting">asentence.word LIKE 'l_se'</pre><p> is true for 'lose'
and false for 'loose'
</p>
</li><li class="listitem">
<p>
</p><pre class="programlisting">aword.underscored LIKE '\_%' ESCAPE '\'</pre><p> is true
for '_foo' and false for 'bar'
</p>
</li><li class="listitem">
<p>
</p><pre class="programlisting">address.phone NOT LIKE '12%3'</pre><p> is false for
'123' and '12993' and true for '1234'.
</p>
</li></ul></div><p>
</p>
<p>
If the value of the <code class="literal">string_expression</code> or
<code class="literal">pattern_value</code> is <code class="literal">NULL</code> or unknown, the value of the <code class="literal">
LIKE</code> expression is unknown. If the <code class="literal">escape_character</code> is specified and
is <code class="literal">NULL</code>, the value of the <code class="literal">LIKE</code> expression
is unknown.
</p>
</div>
<div class="section" id="jpa_langref_null"><div class="titlepage"><div><div><h4 class="title">2.5.11.&nbsp;
JPQL Null Comparison Expressions
</h4></div></div></div>
<p>
The syntax for the use of the comparison operator <code class="literal">IS NULL</code> in
a conditional expression is as follows:
</p>
<p>
null_comparison_expression ::= {single_valued_path_expression | input_parameter } IS [NOT] NULL
</p>
<p>
A null comparison expression tests whether or not the single-valued path
expression or input parameter is a <code class="literal">NULL</code> value.
</p>
<p>
Null comparisons over instances of embeddable class types are not supported.
</p>
</div>
<div class="section" id="jpa_langref_empty_comp"><div class="titlepage"><div><div><h4 class="title">2.5.12.&nbsp;
JPQL Empty Collection Comparison Expressions
</h4></div></div></div>
<p>
The syntax for the use of the comparison operator <code class="literal">IS EMPTY</code> in
an <code class="literal">empty_collection_comparison_expression</code> is as follows:
</p>
<p>
empty_collection_comparison_expression ::=
collection_valued_path_expression IS [NOT] EMPTY
</p>
<p>
This expression tests whether or not the collection designated by the
collection-valued path expression is empty (i.e. has no elements).
</p>
<p>
For example, the following query will return all magazines that don't have any
articles at all: </p><pre class="programlisting">SELECT mag FROM Magazine mag WHERE mag.articles IS EMPTY
</pre><p>
</p>
<p>
If the value of the collection-valued path expression in an
empty collection comparison expression is unknown, the value of the empty
comparison expression is unknown.
</p>
</div>
<div class="section" id="jpa_langref_collection_member"><div class="titlepage"><div><div><h4 class="title">2.5.13.&nbsp;
JPQL Collection Member Expressions
</h4></div></div></div>
<p>
The syntax for the use of the comparison operator <code class="literal">MEMBER OF</code>
in an <code class="literal">collection_member_expression</code> is as follows:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
collection_member_expression ::= entity_or_value_expression [NOT] MEMBER [OF]
collection_valued_path_expression
</p>
</li><li class="listitem">
<p>
entity_or_value_expression ::= single_valued_object_path_expression |
state_field_path_expression |
simple_entity_or_value_expression
</p>
</li><li class="listitem">
<p>
simple_entity_or_value_expression ::=
identification_variable |
input_parameter |
literal
</p>
</li></ul></div><p>
</p>
<p>
This expression tests whether the designated value is a member of the collection
specified by the collection-valued path expression.
</p>
<p>
</p>
Expressions that evaluate to embeddable types are not supported in collection member expressions.
<p>
If the collection valued
path expression designates an empty collection, the value of the <code class="literal">
MEMBER OF</code> expression is <code class="literal">FALSE</code> and the value of the
<code class="literal">NOT MEMBER OF</code> expression is <code class="literal">TRUE</code>.
Otherwise, if the value of the <code class="literal">collection_valued_path_expression</code> or
<code class="literal">entity_or_value_expression</code> in the collection member
expression is <code class="literal">NULL</code> or unknown, the value of the collection
member expression is unknown.
</p>
<p>
The use of the reserved word OF is optional in this expression.
</p>
<p>
Example:
</p>
<pre class="programlisting">
SELECT p
FROM Person p
WHERE 'Joe' MEMBER OF p.nicknames
</pre>
</div>
<div class="section" id="jpa_langref_exists"><div class="titlepage"><div><div><h4 class="title">2.5.14.&nbsp;
JPQL Exists Expressions
</h4></div></div></div>
<p>
An <code class="literal">EXISTS</code> expression is a predicate that is true only if the
result of the subquery consists of one or more values and that is false
otherwise. The syntax of an exists expression is </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
exists_expression ::= [NOT] EXISTS (subquery)
</p>
</li></ul></div><p>
</p>
<p>
Example: </p><pre class="programlisting">SELECT DISTINCT auth FROM Author auth
WHERE EXISTS
(SELECT spouseAuthor FROM Author spouseAuthor WHERE spouseAuthor = auth.spouse)
</pre><p> The result of this query consists of all authors whose spouse
is also an author.
</p>
</div>
<div class="section" id="jpa_langref_all_any"><div class="titlepage"><div><div><h4 class="title">2.5.15.&nbsp;
JPQL All or Any Expressions
</h4></div></div></div>
<p>
An <code class="literal">ALL</code> conditional expression is a predicate
over a subquery that is true if the comparison operation is
true for all values in the result of the subquery or the result of the subquery is empty.
An <code class="literal">ALL</code> conditional
expression is false if the result of the comparison is false for at least one
value of the result of the subquery,
and is unknown if neither true nor false.
</p>
<p>
An <code class="literal">ANY</code>
conditional expression is a predicate over a subquery that is true if the comparison operation
is true for some value in the result of the subquery. An <code class="literal">ANY</code>
conditional expression is false if the result of the subquery is empty or if the
comparison operation is false for every value in the result of the subquery, and
is unknown if neither true nor false. The keyword <code class="literal">SOME</code> is
synonymous with <code class="literal">ANY</code>.
</p>
<p>
The comparison operators used with
<code class="literal">ALL</code> or <code class="literal">ANY</code> conditional expressions are =,
&lt;, &lt;=, &gt;, &gt;=, &lt;&gt;. The result of the subquery must be like that
of the other argument to the comparison operator in type. See
<a class="xref" href="#jpa_langref_equality" title="2.12.&nbsp; JPQL Equality and Comparison Semantics">Section&nbsp;2.12, &#8220;
JPQL Equality and Comparison Semantics
&#8221;</a>. The syntax of an <code class="literal">ALL
</code> or <code class="literal">ANY</code> expression is specified as follows:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>all_or_any_expression ::= { ALL | ANY | SOME}
(subquery)
</p>
</li></ul></div><p>
</p>
<p>
The following example select the authors who make the highest salary for their
magazine: </p><pre class="programlisting">SELECT auth FROM Author auth
WHERE auth.salary &gt;= ALL(SELECT a.salary FROM Author a WHERE a.magazine = auth.magazine)
</pre><p>
</p>
</div>
<div class="section" id="jpa_langref_subqueries"><div class="titlepage"><div><div><h4 class="title">2.5.16.&nbsp;
JPQL Subqueries
</h4></div></div></div>
<p>
Subqueries may be used in the <code class="literal">WHERE</code> or <code class="literal">HAVING
</code> clause. The syntax for subqueries is as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
subquery ::= simple_select_clause subquery_from_clause
[where_clause] [groupby_clause] [having_clause]
</p>
</li><li class="listitem">
<p>
simple_select_clause ::= SELECT [DISTINCT]
simple_select_expression
</p>
</li><li class="listitem">
<p>
subquery_from_clause ::= FROM subselect_identification_variable_declaration {,
subselect_identification_variable_declaration |
collection_member_declaration }*
</p>
</li><li class="listitem">
<p>
subselect_identification_variable_declaration ::=
identification_variable_declaration | derived_path_expression [AS]
identification_variable {join}* | derived_collection_member_declaration
</p>
</li><li class="listitem">
<p>
simple_select_expression ::= single_valued_path_expression |
scalar_expression |
aggregate_expression | identification_variable
</p>
</li><li class="listitem">
<p>
derived_path_expression ::=
superquery_identification_variable.{single_valued_object_field.}*collection_valued_field |
superquery_identification_variable.{single_valued_object_field.}*single_valued_object_field
</p>
</li><li class="listitem">
<p>
derived_collection_member_declaration ::=
IN superquery_identification_variable.{single_valued_object_field.}*collection_valued_field
</p>
</li></ul></div>
<p>
Subqueries are restricted to the <code class="literal">WHERE</code> and <code class="literal">HAVING
</code> clauses in this release. Support for subqueries in the <code class="literal">FROM
</code> clause will be considered in a later release of the specification.
</p>
<p>
Examples: </p><pre class="programlisting">SELECT DISTINCT auth FROM Author auth
WHERE EXISTS (SELECT spouseAuth FROM Author spouseAuth WHERE spouseAuth = auth.spouse)
</pre><pre class="programlisting">SELECT mag FROM Magazine mag
WHERE (SELECT COUNT(art) FROM mag.articles art) &gt; 10</pre><p>
Note that some contexts in which a subquery can be used require that the
subquery be a scalar subquery (i.e., produce a single result). This is
illustrated in the following example involving a numeric comparison operation.
</p><pre class="programlisting">SELECT goodPublisher FROM Publisher goodPublisher
WHERE goodPublisher.revenue &lt; (SELECT AVG(p.revenue) FROM Publisher p)
</pre><p>
</p><pre class="programlisting">
SELECT goodCustomer
FROM Customer goodCustomer
WHERE goodCustomer.balanceOwed &lt; (
SELECT AVG(c.balanceOwed)/2.0 FROM Customer c)
</pre><p>
</p>
</div>
</div>
<div class="section" id="jpa_langref_scalar_expressions"><div class="titlepage"><div><div><h3 class="title">2.6.&nbsp;
JPQL Scalar Expressions
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_math_expressions">2.6.1.
Arithmetic Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_functional_expressions">2.6.2.
String, Arithmetic, and Datetime Functional Expressions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_string_fun">2.6.2.1.
JPQL String Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_arithmetic">2.6.2.2.
JPQL Arithmetic Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_datetime">2.6.2.3.
JPQL Datetime Functions
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_langref_case_expressions">2.6.3.
Case Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_entity_type_expressions">2.6.4.
Entity Type Expressions
</a></span></dt></dl></div>
<p>
Numeric, string, datetime, case, and entity type expressions result in scalar values.
</p>
<p>
Scalar expressions may be used in the <code class="literal">SELECT</code> clause of a query as well as in the
<code class="literal">WHERE</code> and <code class="literal">HAVING</code> clauses.
</p>
<p>
scalar_expression::=
arithmetic_expression |
string_primary |
enum_primary |
datetime_primary |
boolean_primary |
case_expression |
entity_type_expression
</p>
<div class="section" id="jpa_langref_math_expressions"><div class="titlepage"><div><div><h4 class="title">2.6.1.&nbsp;
Arithmetic Expressions
</h4></div></div></div>
<p>
The arithmetic operators are:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">+, - unary</li><li class="listitem">*, / multiplication and division</li><li class="listitem">+, - addition and subtraction</li></ul></div><p>
</p><p>
Arithmetic operations use numeric promotion.
</p><p>
</p><p>
Arithmetic functions are described in <a class="xref" href="#jpa_langref_arithmetic" title="2.6.2.2.&nbsp; JPQL Arithmetic Functions">Section&nbsp;2.6.2.2, &#8220;
JPQL Arithmetic Functions
&#8221;</a>.
</p><p>
</p>
</div>
<div class="section" id="jpa_langref_functional_expressions"><div class="titlepage"><div><div><h4 class="title">2.6.2.&nbsp;
String, Arithmetic, and Datetime Functional Expressions
</h4></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_string_fun">2.6.2.1.
JPQL String Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_arithmetic">2.6.2.2.
JPQL Arithmetic Functions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_datetime">2.6.2.3.
JPQL Datetime Functions
</a></span></dt></dl></div>
<p>
JPQL includes the built-in functions described in subsections
<a class="xref" href="#jpa_langref_string_fun" title="2.6.2.1.&nbsp; JPQL String Functions">Section&nbsp;2.6.2.1, &#8220;
JPQL String Functions
&#8221;</a>,
<a class="xref" href="#jpa_langref_arithmetic" title="2.6.2.2.&nbsp; JPQL Arithmetic Functions">Section&nbsp;2.6.2.2, &#8220;
JPQL Arithmetic Functions
&#8221;</a>,
<a class="xref" href="#jpa_langref_datetime" title="2.6.2.3.&nbsp; JPQL Datetime Functions">Section&nbsp;2.6.2.3, &#8220;
JPQL Datetime Functions
&#8221;</a>,
which may be used in the <code class="literal">SELECT</code>,
<code class="literal">WHERE</code>
or <code class="literal">HAVING</code> clause of a query.
</p><p>
</p><p>
If the
value of any argument to a functional expression is null or unknown, the value
of the functional expression is unknown.
</p>
<div class="section" id="jpa_langref_string_fun"><div class="titlepage"><div><div><h5 class="title">2.6.2.1.&nbsp;
JPQL String Functions
</h5></div></div></div>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>functions_returning_strings ::=
CONCAT(string_primary, string_primary) | SUBSTRING(string_primary,
simple_arithmetic_expression[, simple_arithmetic_expression]) |
TRIM([[trim_specification] [trim_character] FROM] string_primary) |
LOWER(string_primary) | UPPER(string_primary)
</p>
</li><li class="listitem">
<p>
trim_specification ::= LEADING | TRAILING | BOTH
</p>
</li><li class="listitem">
<p>
functions_returning_numerics ::= LENGTH(string_primary) |
LOCATE(string_primary, string_primary[, simple_arithmetic_expression])
</p>
</li></ul></div><p>
</p>
<p>
The <code class="literal">CONCAT</code> function returns a string that is a concatenation
of its arguments.
</p>
<p>
The second and third arguments of the <code class="literal">SUBSTRING
</code> function denote the starting position and length of the substring to
be returned. These arguments are integers.
The third argument is optional. If it is not specified,
the substring from the start position to the end of the string is returned.
The first position of a string is
denoted by 1. The <code class="literal">SUBSTRING</code> function returns a string.
</p>
<p>
The
<code class="literal">TRIM</code> function trims the specified character from a string. If
the character to be trimmed is not specified, it is assumed to be space (or
blank). The optional trim_character is a single-character string literal or a
character-valued input parameter (i.e., char or Character). If a trim
specification is not provided, <code class="literal">BOTH</code> is assumed. The <code class="literal">
TRIM</code> function returns the trimmed string.
</p>
<p>
The <code class="literal">LOWER</code>
and <code class="literal">UPPER</code> functions convert a string to lower and upper case,
respectively. They return a string.
</p>
<p>
The <code class="literal">LOCATE</code> function
returns the position of a given string within a string, starting the search at a
specified position. It returns the first position at which the string was found
as an integer. The first argument is the string to be located; the second
argument is the string to be searched; the optional third argument is an integer
that represents the string position at which the search is started (by default,
the beginning of the string to be searched). The first position in a string is
denoted by 1. If the string is not found, 0 is returned.
</p>
<p>
The <code class="literal">LENGTH
</code> function returns the length of the string in characters as an
integer.
</p>
</div>
<div class="section" id="jpa_langref_arithmetic"><div class="titlepage"><div><div><h5 class="title">2.6.2.2.&nbsp;
JPQL Arithmetic Functions
</h5></div></div></div>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>functions_returning_numerics ::=
ABS(simple_arithmetic_expression) |
SQRT(simple_arithmetic_expression) |
MOD(simple_arithmetic_expression, simple_arithmetic_expression) |
SIZE(collection_valued_path_expression) |
INDEX(identification_variable)
</p>
</li></ul></div><p>
</p>
<p>
The <code class="literal">ABS</code> function takes a numeric argument and returns a
number (integer, float, or double) of the same type as the argument to the
function.
</p>
<p>
The <code class="literal">SQRT</code> function takes a numeric argument and
returns a double.
</p>
<p>
Note that not all databases support the use of a trim character other than the
space character; use of this argument may result in queries that are not
portable. Note that not all databases support the use of the third argument to
<code class="literal">LOCATE</code>; use of this argument may result in queries that are
not portable.
</p>
<p>
The <code class="literal">MOD</code> function takes two integer arguments and returns an
integer.
</p>
<p>
The <code class="literal">SIZE</code> function returns an integer value, the
number of elements of the collection. If the collection is empty, the <code class="literal">
SIZE</code> function evaluates to zero. Numeric arguments to these functions
may correspond to the numeric Java object types as well as the primitive numeric
types.
</p>
<p>
The INDEX function returns an integer value corresponding to the position of its argument in an
ordered list. The INDEX function can only be applied to identification variables denoting types for
which an order column has been specified.
</p>
</div>
<div class="section" id="jpa_langref_datetime"><div class="titlepage"><div><div><h5 class="title">2.6.2.3.&nbsp;
JPQL Datetime Functions
</h5></div></div></div>
<p>
functions_returning_datetime:= CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP
</p>
<p>
The datetime functions return the value of current date, time, and timestamp on
the database server.
</p>
</div>
</div>
<div class="section" id="jpa_langref_case_expressions"><div class="titlepage"><div><div><h4 class="title">2.6.3.&nbsp;
Case Expressions
</h4></div></div></div>
<p>
The following forms of case expressions are supported: general case expressions, simple case expressions,
coalesce expressions, and nullif expressions.
</p><div class="itemizedlist"><code class="literal">CASE</code><code class="literal">ELSE</code><code class="literal">END</code><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
case_expression::=
general_case_expression |
simple_case_expression |
coalesce_expression |
nullif_expression
</li><li class="listitem">
general_case_expression::=
<code class="literal">CASE</code> when_clause {when_clause}* <code class="literal">ELSE</code> scalar_expression <code class="literal">END</code>
</li><li class="listitem">
when_clause::= <code class="literal">WHEN</code> conditional_expression <code class="literal">THEN</code> scalar_expression
</li><li class="listitem">
case_operand::= state_field_path_expression | type_discriminator
</li><li class="listitem">
simple_when_clause::= <code class="literal">WHEN</code> scalar_expression <code class="literal">THEN</code> scalar_expression
</li><li class="listitem">
coalesce_expression::= <code class="literal">COALESCE</code>(scalar_expression {, scalar_expression}+)
</li><li class="listitem">
nullif_expression::= <code class="literal">NULLIF</code>(scalar_expression, scalar_expression)
</li></ul></div><p>
</p>
<p>
Examples:
</p>
<pre class="programlisting">
UPDATE Employee e
SET e.salary =
CASE WHEN e.rating = 1 THEN e.salary * 1.1
WHEN e.rating = 2 THEN e.salary * 1.05
ELSE e.salary * 1.01
END
</pre>
<pre class="programlisting">
UPDATE Employee e
SET e.salary =
CASE e.rating WHEN 1 THEN e.salary * 1.1
WHEN 2 THEN e.salary * 1.05
ELSE e.salary * 1.01
END
</pre>
<pre class="programlisting">
SELECT e.name,
CASE TYPE(e) WHEN Exempt THEN 'Exempt'
WHEN Contractor THEN 'Contractor'
WHEN Intern THEN 'Intern'
ELSE 'NonExempt'
END
FROM Employee e
WHERE e.dept.name = 'Engineering'
</pre>
<pre class="programlisting">
SELECT e.name,
f.name,
CONCAT(CASE WHEN f.annualMiles &gt; 50000 THEN 'Platinum '
WHEN f.annualMiles &gt; 25000 THEN 'Gold '
ELSE ''
END,
'Frequent Flyer')
FROM Employee e JOIN e.frequentFlierPlan f
</pre>
</div>
<div class="section" id="jpa_langref_entity_type_expressions"><div class="titlepage"><div><div><h4 class="title">2.6.4.&nbsp;
Entity Type Expressions
</h4></div></div></div>
<p>
An entity type expression can be used to restrict query polymorphism.
The <code class="literal">TYPE</code> operator returns the
exact type of the argument.
</p>
<p>
The syntax of an entity type expression is as follows:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
entity_type_expression ::=
type_discriminator |
entity_type_literal |
input_parameter
</li><li class="listitem">
type_discriminator ::=
TYPE(identification_variable |
single_valued_object_path_expression |
input_parameter )
</li></ul></div>
<p>
An <code class="literal">entity_type_literal</code> is designated by the entity name.
</p>
<p>
The Java class of the entity is used as an input parameter to specify the entity type.
</p>
<p>
Examples:
</p>
<pre class="programlisting">
SELECT e
FROM Employee e
WHERE TYPE(e) IN (Exempt, Contractor)
</pre>
<pre class="programlisting">
SELECT e
FROM Employee e
WHERE TYPE(e) IN (:empType1, :empType2)
</pre>
<pre class="programlisting">
SELECT e
FROM Employee e
WHERE TYPE(e) IN :empTypes
</pre>
<pre class="programlisting">
SELECT TYPE(e)
FROM Employee e
WHERE TYPE(e) &lt;&gt; Exempt
</pre>
</div>
</div>
<div class="section" id="jpa_langref_group"><div class="titlepage"><div><div><h3 class="title">2.7.&nbsp;
JPQL GROUP BY, HAVING
</h3></div></div></div>
<p>
The <code class="literal">GROUP BY</code> construct enables the aggregation of values
according to a set of properties. The <code class="literal">HAVING</code> construct
enables conditions to be specified that further restrict the query result. Such
conditions are restrictions upon the groups.
</p>
<p>
The syntax of the <code class="literal">GROUP
BY</code> and <code class="literal">HAVING</code> clauses is as follows:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>groupby_clause ::= GROUP BY groupby_item {,
groupby_item}*
</p>
</li><li class="listitem">
<p>
groupby_item ::= single_valued_path_expression | identification_variable
</p>
</li><li class="listitem">
<p>
having_clause ::= HAVING conditional_expression
</p>
</li></ul></div><p>
</p>
<p>
If a query contains both a <code class="literal">WHERE</code> clause and a <code class="literal">GROUP
BY</code> clause, the effect is that of first applying the where clause, and
then forming the groups and filtering them according to the <code class="literal">HAVING
</code> clause. The <code class="literal">HAVING</code> clause causes those groups to
be retained that satisfy the condition of the <code class="literal">HAVING</code> clause.
</p>
<p>
The requirements for the <code class="literal">SELECT</code> clause when <code class="literal">GROUP
BY</code> is used follow those of SQL: namely, any item that appears in the
<code class="literal">SELECT</code> clause (other than as an argument to an aggregate
function) must also appear in the <code class="literal">GROUP BY</code> clause. In forming
the groups, null values are treated as the same for grouping purposes.
</p>
<p>
Grouping
by an entity is permitted. In this case, the entity must contain no serialized
state fields or LOB-valued state fields that are eagerly fetched.
</p>
<p>
Grouping by embeddables is not supported.
</p>
<p>
The <code class="literal">HAVING</code> clause
must specify search conditions over the grouping items or aggregate functions
that apply to grouping items.
</p>
<p>
If there is no <code class="literal">GROUP BY</code> clause and the <code class="literal">HAVING
</code> clause is used, the result is treated as a single group, and the
select list can only consist of aggregate functions.
The use of <code class="literal">HAVING</code> in the absence of
<code class="literal">GROUP BY</code> is not required to be supported by a JPA implementation.
Portable applications should not rely on <code class="literal">HAVING</code> without the use of
<code class="literal">GROUP BY</code>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA supports the use of <code class="literal">HAVING</code> in the absence of
<code class="literal">GROUP BY</code> if the underlying database supports it.
</p>
</div>
<p>
Examples:
</p>
<pre class="programlisting">
SELECT c.status, AVG(c.filledOrderCount), COUNT(c)
FROM Customer c
GROUP BY c.status
HAVING c.status IN (1, 2)
</pre>
<pre class="programlisting">
SELECT c.country, COUNT(c)
FROM Customer c
GROUP BY c.country
HAVING COUNT(c) &gt; 30
</pre>
</div>
<div class="section" id="jpa_langref_select_clause"><div class="titlepage"><div><div><h3 class="title">2.8.&nbsp;
JPQL SELECT Clause
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_resulttype">2.8.1.
JPQL Result Type of the SELECT Clause
</a></span></dt><dt><span class="section"><a href="#jpa_langref_constructor">2.8.2.
JPQL Constructor Expressions
</a></span></dt><dt><span class="section"><a href="#jpa_langref_null_select">2.8.3.
JPQL Null Values in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_embeddables">2.8.4.
JPQL Embeddables in the Query Result
</a></span></dt><dt><span class="section"><a href="#jpa_langref_aggregates">2.8.5.
JPQL Aggregate Functions
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_langref_agg_examples">2.8.5.1.
JPQL Aggregate Examples
</a></span></dt><dt><span class="section"><a href="#jpa_langref_numeric_expressions_in_select">2.8.5.2.
JPQL Numeric Expressions in the SELECT Clause
</a></span></dt></dl></dd></dl></div>
<p>
The <code class="literal">SELECT</code> clause denotes the query result. More than one
value may be returned from the <code class="literal">SELECT</code> clause of a query.
</p>
<p>
The <code class="literal">SELECT</code> clause can contain one or more of the following
elements: a single range variable or identification variable that ranges over an
entity abstract schema type, a single-valued path expression,
a scalar expression,
an aggregate expression, a constructor expression.
</p>
<p>
The <code class="literal">SELECT</code>
clause has the following syntax:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>select_clause ::= SELECT [DISTINCT]
select_item {, select_item}*
</p>
</li><li class="listitem">
<p>
select_item ::= select_expression [ [AS] result_variable]
</p>
</li><li class="listitem">
<p>
select_expression ::= single_valued_path_expression |
scalar_expression |
aggregate_expression |
identification_variable | OBJECT(identification_variable) |
constructor_expression
</p>
</li><li class="listitem">
<p>
constructor_expression ::= NEW constructor_name ( constructor_item {,
constructor_item}*)
</p>
</li><li class="listitem">
<p>
constructor_item ::= single_valued_path_expression |
scalar_expression |
aggregate_expression |
identification_variable
</p>
</li><li class="listitem">
<p>
aggregate_expression ::= { AVG | MAX | MIN | SUM } ([DISTINCT]
state_field_path_expression) | COUNT ([DISTINCT] identification_variable |
state_field_path_expression | single_valued_object_path_expression)
</p>
</li></ul></div><p>
</p>
<p>
For example: </p><pre class="programlisting">SELECT pub.id, pub.revenue
FROM Publisher pub JOIN pub.magazines mag WHERE mag.price &gt; 5.00
</pre><p>
</p>
<p>
In the following example, videoInventory is a Map from the entity Movie to the number of copies
in stock:
</p>
<pre class="programlisting">
SELECT v.location.street, KEY(i).title, VALUE(i)
FROM VideoStore v JOIN v.videoInventory i
WHERE v.location.zipcode = '94301' AND VALUE(i) &gt; 0
</pre>
<p>
Note that the <code class="literal">SELECT</code> clause must be specified to return only
single-valued expressions. The query below is therefore not valid:
</p><pre class="programlisting">SELECT mag.authors FROM Magazine AS mag</pre><p>
</p>
<p>
The <code class="literal">DISTINCT</code> keyword is used to specify that duplicate values
must be eliminated from the query result.
</p>
<p>
If <code class="literal">DISTINCT</code> is not
specified, duplicate values are not eliminated.
</p>
<p>
The result of DISTINCT over embeddable objects or map entry results is undefined.
</p>
<p>
Standalone identification
variables in the <code class="literal">SELECT</code> clause may optionally be qualified by
the <code class="literal">OBJECT</code> operator. The <code class="literal">SELECT</code> clause
must not use the OBJECT operator to qualify path expressions.
</p>
<p>
A <code class="literal">result_variable</code> may be used to name a <code class="literal">select_item</code> in the query result.
For example,
</p><pre class="programlisting">
SELECT c, COUNT(l) AS itemCount
FROM Customer c JOIN c.Orders o JOIN o.lineItems l
WHERE c.address.state = &#8216;CA&#8217;
ORDER BY itemCount
</pre><p>
</p>
<div class="section" id="jpa_langref_resulttype"><div class="titlepage"><div><div><h4 class="title">2.8.1.&nbsp;
JPQL Result Type of the SELECT Clause
</h4></div></div></div>
<p>
The type of the query result specified by the <code class="literal">SELECT</code> clause
of a query is an entity abstract schema type, a state-field type,
the result of of a scalar expression, the result of
an aggregate function, the result of a construction operation, or some sequence
of these.
</p>
<p>
The result type of the <code class="literal">SELECT</code> clause is defined by
the result types of the select_expressions contained in it. When multiple
select expressions are used in the <code class="literal">SELECT</code> clause, the result
of the query is of type Object[], and the elements in this result correspond in
order to the order of their specification in the <code class="literal">SELECT</code>
clause and in type to the result types of each of the select expressions.
</p>
<p>
The type of the result of a <code class="literal">select_expression</code> is as follows:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The result type of an <code class="literal">identification_variable</code>
is the type of the entity object or embeddable
object to which the identification variable corresponds. The type of an
<code class="literal">identification_variable</code>
that refers to an entity abstract schema type is the type of the entity to which that identification
variable corresponds or a subtype as determined by the object/relational mapping.
</p>
</li><li class="listitem">
<p>
The result type of a <code class="literal">single_valued_path_expression</code> that is a
<code class="literal">state_field_path_expression</code>
results in an object of the same type as the
corresponding state field of the entity or embeddable class.
If the state field of the entity is a
primitive type, the result type is the corresponding object type.
</p>
</li><li class="listitem">
<p>
The result type of a <code class="literal">single_valued_path_expression</code> that is a
<code class="literal">single_valued_object_path_expression</code>
is the type of the entity object or embeddable
object to which the path expression corresponds.
A <code class="literal">single_valued_object_path_expression</code>
that results in an entity object will result in an entity of the type of
the relationship field or the
subtype of the relationship field of the entity object as determined by
the object/relational mapping.
</p>
</li><li class="listitem">
<p>
The result type of a
<code class="literal">single_valued_path_expression</code>
that is an identification_variable to
which the <code class="literal">KEY</code> or <code class="literal">VALUE</code> function
has been applied is determined by the type of the map key
or value respectively, as defined by the above rules
</p>
</li><li class="listitem">
<p>
The result type of a
<code class="literal">single_valued_path_expression</code> that is an
<code class="literal">identification_variable</code> to
which the <code class="literal">ENTRY</code> function has been applied is
<code class="literal">java.util.Map.Entry</code>, where the key
and value types of the map entry are determined by the above rules as applied to the map key
and map value respectively.
</p>
</li><li class="listitem">
<p>
The result type of a
<code class="literal">scalar_expression</code> is the type of the scalar value to which the expression
evaluates. The result type of a numeric <code class="literal">scalar_expression</code> is defined in
<a class="xref" href="#jpa_langref_scalar_expressions" title="2.6.&nbsp; JPQL Scalar Expressions">Section&nbsp;2.6, &#8220;
JPQL Scalar Expressions
&#8221;</a>
</p>
</li><li class="listitem">
<p>
The result type of an
<code class="literal">entity_type_expression</code> scalar expression is the Java class to which the
resulting abstract schema type corresponds.
</p>
</li><li class="listitem">
<p>
The result type of aggregate_expression is defined in
<a class="xref" href="#jpa_langref_aggregates" title="2.8.5.&nbsp; JPQL Aggregate Functions">Section&nbsp;2.8.5, &#8220;
JPQL Aggregate Functions
&#8221;</a>.
</p>
</li><li class="listitem">
<p>
The result type of a
<code class="literal">constructor_expression</code> is the type of the class for which
the constructor is defined. The types of the arguments to the constructor are
defined by the above rules.
</p>
</li></ul></div><p>
</p>
</div>
<div class="section" id="jpa_langref_constructor"><div class="titlepage"><div><div><h4 class="title">2.8.2.&nbsp;
JPQL Constructor Expressions
</h4></div></div></div>
<p>
A constructor may be used in the
<code class="literal">SELECT</code> list to return one or more Java instances. The
specified class is not required to be an entity or to be mapped to the database.
The constructor name must be fully qualified.
</p>
<p>
If an entity class name is specified in the <code class="literal">SELECT NEW</code>
clause, the resulting entity instances are in the new state.
</p>
<p>
If a <code class="literal">single_valued_path_expression</code> or
<code class="literal">identification_variable</code> that is an argument to the constructor
references an entity, the resulting entity instance referenced by that
<code class="literal">single_valued_path_expression</code> or
<code class="literal">identification_variable</code>
will be in the managed state.
</p>
<p>
If <code class="literal">PublisherInfo</code> is an entity class, the following 2 queries return
instances of <code class="literal">PublisherInfo</code> that will be in the new state.
In the second example, <code class="literal">mag</code> is an <code class="literal">identification_variable</code>
passed as an argument to the constructor <code class="literal">PublisherInfo(Magazine mag)</code>;
the entity instances of <code class="literal">Magazine</code> created during query evaluation
will be in the managed state.
Example:
</p>
<pre class="programlisting">SELECT NEW com.company.PublisherInfo(pub.id, pub.revenue, mag.price)
FROM Publisher pub JOIN pub.magazines mag WHERE mag.price &gt; 5.00
</pre>
<pre class="programlisting">SELECT NEW com.company.PublisherInfo(mag)
FROM Publisher pub JOIN pub.magazines mag WHERE mag.price &gt; 5.00
</pre>
</div>
<div class="section" id="jpa_langref_null_select"><div class="titlepage"><div><div><h4 class="title">2.8.3.&nbsp;
JPQL Null Values in the Query Result
</h4></div></div></div>
<p>
If the result of a query corresponds to a association-field or state-field whose
value is null, that null value is returned in the result of the query method.
The <code class="literal">IS NOT NULL</code> construct can be used to eliminate such null
values from the result set of the query.
</p>
<p>
Note, however, that state-field types
defined in terms of Java numeric primitive types cannot produce <code class="literal">NULL
</code> values in the query result. A query that returns such a state-field
type as a result type must not return a null value.
</p>
</div>
<div class="section" id="jpa_langref_embeddables"><div class="titlepage"><div><div><h4 class="title">2.8.4.&nbsp;
JPQL Embeddables in the Query Result
</h4></div></div></div>
<p>
If the result of a query corresponds to an identification variable or state field whose value is an
embeddable, the embeddable instance returned by the query will not be in the managed state (i.e., it will
not be part of the state of any managed entity).
</p>
<p>
In the following example, the <code class="literal">Address</code> instances returned by the query will reference Phone
instances. While the <code class="literal">Phone</code> instances will be managed,
the <code class="literal">Address</code>&gt; instances referenced by the
<code class="literal">addr</code> result variable will not be.
Modifications to these embeddable instances are not allowed.
</p>
<pre class="programlisting">
@Entity
public class Employee {
@Id int id;
Address address;
...
}
@Embeddable
public class Address {
String street;
...
@OneToOne Phone phone; // fetch=EAGER
}
@Entity
public class Phone {
@Id int id;
...
@OneToOne(mappedBy="address.phone") Employee emp; // fetch=EAGER
}
SELECT e.address AS addr
FROM Employee e
</pre>
</div>
<div class="section" id="jpa_langref_aggregates"><div class="titlepage"><div><div><h4 class="title">2.8.5.&nbsp;
JPQL Aggregate Functions
</h4></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_langref_agg_examples">2.8.5.1.
JPQL Aggregate Examples
</a></span></dt><dt><span class="section"><a href="#jpa_langref_numeric_expressions_in_select">2.8.5.2.
JPQL Numeric Expressions in the SELECT Clause
</a></span></dt></dl></div>
<p>
The result of a query may be the result
of an aggregate function applied to a path expression.
</p>
<p>
The following aggregate
functions can be used in the <code class="literal">SELECT</code> clause of a query:
<code class="literal">AVG</code>, <code class="literal">COUNT</code>, <code class="literal">MAX</code>,
<code class="literal">MIN</code>, <code class="literal">SUM</code>.
</p>
<p>
For all aggregate functions
except <code class="literal">COUNT</code>, the path expression that is the argument to
the aggregate function must terminate in a state-field. The path expression
argument to <code class="literal">COUNT</code> may terminate in either a state-field or a
association-field, or the argument to <code class="literal">COUNT</code> may be an
identification variable.
</p>
<p>
Arguments to the functions <code class="literal">SUM</code> and
<code class="literal">AVG</code> must be numeric. Arguments to the functions <code class="literal">MAX
</code> and <code class="literal">MIN</code> must correspond to orderable state-field
types (i.e., numeric types, string types, character types, or date types).
</p>
<p>
The Java type that is contained in the result of a query using an aggregate function
is as follows: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p><code class="literal">COUNT</code> returns
Long.
</p>
</li><li class="listitem">
<p>
<code class="literal">MAX</code>, <code class="literal">MIN</code> return the type of the
state-field to which they are applied.
</p>
</li><li class="listitem">
<p>
<code class="literal">AVG</code> returns Double.
</p>
</li><li class="listitem">
<p>
<code class="literal">SUM</code> returns Long when applied to state-fields of integral
types (other than BigInteger); Double when applied to state-fields of floating
point types; BigInteger when applied to state-fields of type BigInteger; and
BigDecimal when applied to state-fields of type BigDecimal.
</p>
</li></ul></div><p>
</p>
<p>
If <code class="literal">SUM
</code>, <code class="literal">AVG</code>, <code class="literal">MAX</code>, or <code class="literal">MIN
</code> is used, and there are no values to which the aggregate function can
be applied, the result of the aggregate function is <code class="literal">NULL</code>.
</p>
<p>
If <code class="literal">COUNT</code> is used, and there are no values to which <code class="literal">
COUNT</code> can be applied, the result of the aggregate function is 0.
</p>
<p>
The argument to an aggregate function may be preceded by the keyword <code class="literal">
DISTINCT</code> to specify that duplicate values are to be eliminated before
the aggregate function is applied.
It is legal to specify <code class="literal">DISTINCT</code> with <code class="literal">MAX</code>
or <code class="literal">MIN</code>, but it does not affect the result.
</p>
<p>
Null values are eliminated before the
aggregate function is applied, regardless of whether the keyword <code class="literal">
DISTINCT</code> is specified.
</p>
<p>
The use of <code class="literal">DISTINCT</code> with <code class="literal">COUNT</code> is not supported for arguments of
embeddable types or map entry types.
</p>
<div class="section" id="jpa_langref_agg_examples"><div class="titlepage"><div><div><h5 class="title">2.8.5.1.&nbsp;
JPQL Aggregate Examples
</h5></div></div></div>
<p>
The following query returns the average price of all magazines:
</p><pre class="programlisting">SELECT AVG(mag.price) FROM Magazine mag</pre><p> The
following query returns the sum of all the prices from all the
magazines published by 'Larry': </p><pre class="programlisting">SELECT SUM(mag.price) FROM Publisher pub JOIN pub.magazines mag WHERE pub.firstName = 'Larry'
</pre><p> The following query returns the total number of magazines:
</p><pre class="programlisting">SELECT COUNT(mag) FROM Magazine mag</pre><p>
</p>
</div>
<div class="section" id="jpa_langref_numeric_expressions_in_select"><div class="titlepage"><div><div><h5 class="title">2.8.5.2.&nbsp;
JPQL Numeric Expressions in the SELECT Clause
</h5></div></div></div>
<p>
The type of a numeric expression in the query result is determined as follows:
</p>
<p>
An operand that corresponds to a persistent state-field is of the same type as that persistent state-field.
</p>
<p>
An operand that corresponds to one of arithmetic functions described in
<a class="xref" href="#jpa_langref_arithmetic" title="2.6.2.2.&nbsp; JPQL Arithmetic Functions">Section&nbsp;2.6.2.2, &#8220;
JPQL Arithmetic Functions
&#8221;</a> is of the type defined by
<a class="xref" href="#jpa_langref_arithmetic" title="2.6.2.2.&nbsp; JPQL Arithmetic Functions">Section&nbsp;2.6.2.2, &#8220;
JPQL Arithmetic Functions
&#8221;</a>.
</p>
<p>
An operand that corresponds to one of an aggregate functions described in
<a class="xref" href="#jpa_langref_aggregates" title="2.8.5.&nbsp; JPQL Aggregate Functions">Section&nbsp;2.8.5, &#8220;
JPQL Aggregate Functions
&#8221;</a> is of the type defined by
<a class="xref" href="#jpa_langref_aggregates" title="2.8.5.&nbsp; JPQL Aggregate Functions">Section&nbsp;2.8.5, &#8220;
JPQL Aggregate Functions
&#8221;</a>.
</p>
<p>
The result of a case expression, coalesce expression, nullif expression, or arithmetic expression (+, -, *,
/) is determined by applying the following rule to its operands.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
If there is an operand of type Double or double, the result of the operation is of type Double;
</p>
</li><li class="listitem">
<p>
otherwise, if there is an operand of type Float or float, the result of the operation is of type
Float;
</p>
</li><li class="listitem">
<p>
otherwise, if there is an operand of type BigDecimal, the result of the operation is of type Big-
Decimal;
</p>
</li><li class="listitem">
<p>
otherwise, if there is an operand of type BigInteger, the result of the operation is of type BigInteger;
</p>
</li><li class="listitem">
<p>
otherwise, if there is an operand of type Long or long, the result of the operation is of type
Long;
</p>
</li><li class="listitem">
<p>
otherwise, if there is an operand of integral type, the result of the operation is of type Integer.
</p>
</li></ul></div>
</div>
</div>
</div>
<div class="section" id="jpa_langref_orderby"><div class="titlepage"><div><div><h3 class="title">2.9.&nbsp;
JPQL ORDER BY Clause
</h3></div></div></div>
<p>
The <code class="literal">ORDER BY</code> clause allows the objects or values that are
returned by the query to be ordered. The syntax of the <code class="literal">ORDER BY
</code> clause is
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>orderby_clause ::= ORDER BY orderby_item {,
orderby_item}*
</p>
</li><li class="listitem">
<p>
orderby_item ::= { state_field_path_expression | result_variable } [ASC | DESC]
</p>
</li></ul></div><p>
</p>
<p>
An orderby_item must be one of the following:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
A <code class="literal">state_field_path_expression</code> that evaluates to an orderable state field of an entity or
embeddable class abstract schema type designated in the SELECT clause by one of the following:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>a <code class="literal">general_identification_variable</code></p>
</li><li class="listitem">
<p>a <code class="literal">single_valued_object_path_expression</code></p>
</li></ul></div>
</li><li class="listitem">
<p>
A <code class="literal">state_field_path_expression</code> that evaluates to the same state field of the same entity or
embeddable abstract schema type as a <code class="literal">state_field_path_expression</code>
in the <code class="literal">SELECT</code> clause.
</p>
</li><li class="listitem">
<p>
A <code class="literal">result_variable</code> that refers to an orderable item in the
<code class="literal">SELECT</code> clause for which the same
<code class="literal">result_variable</code> has been specified.
This may be the result of an <code class="literal">aggregate_expression</code>, a
<code class="literal">scalar_expression</code>,
or a <code class="literal">state_field_path_expression</code> in the <code class="literal">SELECT</code> clause.
</p>
</li></ul></div>
<p>
For example, the five queries below are legal.
</p>
<pre class="programlisting">
SELECT pub FROM Publisher pub ORDER BY pub.revenue, pub.name
</pre>
<pre class="programlisting">
SELECT o
FROM Customer c JOIN c.orders o JOIN c.address a
WHERE a.state = &#8216;CA&#8217;
ORDER BY o.quantity DESC, o.totalcost
</pre>
<pre class="programlisting">
SELECT o.quantity, a.zipcode
FROM Customer c JOIN c.orders o JOIN c.address a
WHERE a.state = &#8216;CA&#8217;
ORDER BY o.quantity, a.zipcode
</pre>
<pre class="programlisting">
SELECT o.quantity, o.cost*1.08 AS taxedCost, a.zipcode
FROM Customer c JOIN c.orders o JOIN c.address a
WHERE a.state = &#8216;CA&#8217; AND a.county = &#8216;Santa Clara&#8217;
ORDER BY o.quantity, taxedCost, a.zipcode
</pre>
<pre class="programlisting">
SELECT AVG(o.quantity) as q, a.zipcode
FROM Customer c JOIN c.orders o JOIN c.address a
WHERE a.state = &#8216;CA&#8217;
GROUP BY a.zipcode
ORDER BY q DESC
</pre>
<p>
The following two queries are not legal because the <code class="literal">orderby_item</code>
is not reflected in the <code class="literal">SELECT</code>
clause of the query.
</p>
<pre class="programlisting">
SELECT p.product_name
FROM Order o JOIN o.lineItems l JOIN l.product p JOIN o.customer c
WHERE c.lastname = &#8216;Smith&#8217; AND c.firstname = &#8216;John&#8217;
ORDER BY p.price
</pre>
<pre class="programlisting">
SELECT p.product_name
FROM Order o, IN(o.lineItems) l JOIN o.customer c
WHERE c.lastname = &#8216;Smith&#8217; AND c.firstname = &#8216;John&#8217;
ORDER BY o.quantity
</pre>
<p>
If more than one <code class="literal">orderby_item</code> is specified, the left-to-right
sequence of the <code class="literal">orderby_item</code> elements determines the precedence, whereby the
leftmost <code class="literal">orderby_item</code> has highest precedence.
</p>
<p>
The keyword <code class="literal">ASC</code>
specifies that ascending ordering be used; the keyword <code class="literal">DESC</code>
specifies that descending ordering be used. Ascending ordering is the default.
</p>
<p>
SQL rules for the ordering of null values apply: that is, all null values must
appear before all non-null values in the ordering or all null values must appear
after all non-null values in the ordering, but it is not specified which.
</p>
<p>
The
ordering of the query result is preserved in the result of the query method if
the <code class="literal">ORDER BY</code> clause is used.
</p>
</div>
<div class="section" id="jpa_langref_bulk_ops"><div class="titlepage"><div><div><h3 class="title">2.10.&nbsp;
JPQL Bulk Update and Delete
</h3></div></div></div>
<p>
Bulk update and delete operations apply to entities of a single
entity class (together with its subclasses, if any). Only one entity abstract
schema type may be specified in the <code class="literal">FROM</code> or <code class="literal">UPDATE
</code> clause. The syntax of these operations is as follows:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>update_statement ::= update_clause [where_clause]
</p>
</li><li class="listitem">
<p>
update_clause ::= UPDATE entity_name [[AS] identification_variable] SET
update_item {, update_item}*
</p>
</li><li class="listitem">
<p>
update_item ::= [identification_variable.]{state_field |
single_valued_object_field} = new_value
</p>
</li><li class="listitem">
<p>
new_value ::= scalar_expression |
simple_entity_expression | NULL
</p>
</li><li class="listitem">
<p>
delete_statement ::= delete_clause [where_clause]
</p>
</li><li class="listitem">
<p>
delete_clause ::= DELETE FROM entity_name [[AS]
identification_variable]
</p>
</li></ul></div><p>
</p>
<p>
The syntax of the <code class="literal">WHERE</code> clause is described in
<a class="xref" href="#jpa_langref_where" title="2.4.&nbsp; JPQL WHERE Clause">Section&nbsp;2.4, &#8220;
JPQL WHERE Clause
&#8221;</a>.
</p>
<p>
A delete operation only applies to
entities of the specified class and its subclasses. It does not cascade to
related entities.
</p>
<p>
The <code class="literal">new_value</code> specified for an update operation must be
compatible in type with the state-field to which it is assigned.
</p>
<p>
Bulk update
maps directly to a database update operation, bypassing optimistic locking
checks. Portable applications must manually update the value of the version
column, if desired, and/or manually validate the value of the version column.
</p>
<p>
The persistence context is not synchronized with the result of the bulk update
or delete.
</p>
<p>
Caution should be used when executing bulk update or delete
operations because they may result in inconsistencies between the database and
the entities in the active persistence context. In general, bulk update and
delete operations should only be performed within a transaction in a new persistence context or at
the beginning of a transaction (before entities have been accessed whose state
might be affected by such operations).
</p>
<p>
Examples: </p><pre class="programlisting">DELETE FROM Publisher pub WHERE pub.revenue &gt; 1000000.0
</pre><pre class="programlisting">DELETE FROM Publisher pub WHERE pub.revenue = 0 AND pub.magazines IS EMPTY
</pre><pre class="programlisting">UPDATE Publisher pub SET pub.status = 'outstanding'
WHERE pub.revenue &lt; 1000000 AND 20 &gt; (SELECT COUNT(mag) FROM pub.magazines mag)
</pre><p>
</p>
</div>
<div class="section" id="jpa_langref_null_values"><div class="titlepage"><div><div><h3 class="title">2.11.&nbsp;
JPQL Null Values
</h3></div></div></div>
<p>
When the target of a reference does not exist in the database, its value is
regarded as <code class="literal">NULL</code>. SQL 92 <code class="literal">NULL</code> semantics
defines the evaluation of conditional expressions containing <code class="literal">NULL
</code> values. The following is a brief description of these semantics:
</p>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> Comparison or arithmetic operations with a
<code class="literal">NULL</code> value always yield an unknown value.
</p>
</li><li class="listitem">
<p>
Two <code class="literal">NULL</code> values are not considered to be equal, the
comparison yields an unknown value.
</p>
</li><li class="listitem">
<p>
Comparison or arithmetic operations with an unknown value always yield an
unknown value.
</p>
</li><li class="listitem">
<p>
The <code class="literal">IS NULL</code> and <code class="literal">IS NOT NULL</code> operators
convert a <code class="literal">NULL</code> state-field or single-valued association-field
value into the respective <code class="literal">TRUE</code> or <code class="literal">FALSE</code>
value.
</p>
</li></ul></div><p>
</p>
<p>
Note: The JPQL defines the empty string, "", as a string with 0 length, which is
not equal to a <code class="literal">NULL</code> value. However, <code class="literal">NULL</code>
values and empty strings may not always be distinguished when queries are mapped
to some databases. Application developers should therefore not rely on the
semantics of query comparisons involving the empty string and <code class="literal">NULL
</code> value.
</p>
</div>
<div class="section" id="jpa_langref_equality"><div class="titlepage"><div><div><h3 class="title">2.12.&nbsp;
JPQL Equality and Comparison Semantics
</h3></div></div></div>
<p>
Only the values of <code class="literal">like</code> types are permitted to be compared. A type is <code class="literal">like</code>
another type if they correspond to the same Java language type, or if one is a
primitive Java language type and the other is the wrappered Java class type
equivalent (e.g., <code class="literal">int</code> and <code class="literal">Integer</code> are like types in this sense). There is one
exception to this rule: it is valid to compare numeric values for which the
rules of numeric promotion apply. Conditional expressions attempting to compare
non-like type values are disallowed except for this numeric case.
</p>
<p>
Note that the
arithmetic operators and comparison operators are permitted to be applied to
state-fields and input parameters of the wrappered Java class equivalents to the
primitive numeric Java types.
</p>
<p>
Two entities of the same abstract schema type are
equal if and only if they have the same primary key value.
</p>
<p>
Equality/inequality comparisons over enums are supported.
</p>
<p>
Comparisons over instances of embeddable class or map entry types are not supported.
</p>
</div>
<div class="section" id="jpa_langref_bnf"><div class="titlepage"><div><div><h3 class="title">2.13.&nbsp;
JPQL BNF
</h3></div></div></div>
<p>
The following is the BNF for the Java Persistence query language, from section
4.14 of the JSR 317 specification.
</p>
<div class="itemizedlist"><p>
select_item ::= select_expression [[AS] result_variable]
</p><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
QL_statement ::= select_statement | update_statement | delete_statement
</p>
</li><li class="listitem">
<p>
select_statement ::= select_clause from_clause [where_clause] [groupby_clause]
[having_clause] [orderby_clause]
</p>
</li><li class="listitem">
<p>
update_statement ::= update_clause [where_clause]
</p>
</li><li class="listitem">
<p>
delete_statement ::= delete_clause [where_clause]
</p>
</li><li class="listitem">
<p>
from_clause ::= <code class="literal">FROM</code> identification_variable_declaration {,
{identification_variable_declaration | collection_member_declaration}}*
</p>
</li><li class="listitem">
<p>
identification_variable_declaration ::= range_variable_declaration { join |
fetch_join }*
</p>
</li><li class="listitem">
<p>
range_variable_declaration ::= entity_name [ <code class="literal">AS</code> ]
identification_variable
</p>
</li><li class="listitem">
<p>
join ::= join_spec join_association_path_expression [ <code class="literal">AS</code> ]
identification_variable
</p>
</li><li class="listitem">
<p>
fetch_join ::= join_spec <code class="literal">FETCH</code>
join_association_path_expression
</p>
</li><li class="listitem">
<p>
join_spec ::= [ <code class="literal">LEFT</code> [ <code class="literal">OUTER</code> ]| <code class="literal">
INNER</code> ] <code class="literal">JOIN</code>
</p>
</li><li class="listitem">
<p>
join_association_path_expression ::= join_collection_valued_path_expression |
join_single_valued_path_expression
</p>
</li><li class="listitem">
<p>
join_collection_valued_path_expression ::=
identification_variable.{single_valued_embeddable_object_field.}*collection_valued_field
</p>
</li><li class="listitem">
<p>
join_single_valued_path_expression ::=
identification_variable.{single_valued_embeddable_object_field.}*single_valued_object_field
</p>
</li><li class="listitem">
<p>
collection_member_declaration ::= <code class="literal">IN</code>
(join_collection_valued_path_expression) [ <code class="literal">AS</code> ]
identification_variable
</p>
</li><li class="listitem">
<p>
qualified_identification_variable ::=
KEY(identification_variable) |
VALUE(identification_variable) |
ENTRY(identification_variable)
</p>
</li><li class="listitem">
<p>
single_valued_path_expression ::=
qualified_identification_variable |
state_field_path_expression |
single_valued_object_path_expression
</p>
</li><li class="listitem">
<p>
general_identification_variable ::=
identification_variable |
KEY(identification_variable) |
VALUE(identification_variable)
</p>
</li><li class="listitem">
<p>
state_field_path_expression ::=
general_identification_variable.{single_valued_object_field.}*state_field
</p>
</li><li class="listitem">
<p>
single_valued_object_path_expression ::=
general_identification_variable.{single_valued_object_field.}*
single_valued_object_field
</p>
</li><li class="listitem">
<p>
collection_valued_path_expression ::=
general_identification_variable.{single_valued_object_field.}*collection_valued_field
</p>
</li><li class="listitem">
<p>
update_clause ::= <code class="literal">UPDATE</code> entity_name [[ <code class="literal">AS
</code> ] identification_variable] <code class="literal">SET</code> update_item {,
update_item}*
</p>
</li><li class="listitem">
<p>
update_item ::= [identification_variable.]{state_field |
single_valued_object_field}= new_value
</p>
</li><li class="listitem">
<p>
new_value ::= scalar_expression |
simple_entity_expression | <code class="literal">NULL
</code>
</p>
</li><li class="listitem">
<p>
delete_clause ::= <code class="literal">DELETE</code><code class="literal">FROM</code>
entity_name [[ <code class="literal">AS</code> ] identification_variable]
</p>
</li><li class="listitem">
<p>
select_clause ::= <code class="literal">SELECT</code> [ <code class="literal">DISTINCT</code> ]
select_item {, select_item}*
</p>
</li><li class="listitem">
</li><li class="listitem">
<p>
select_expression ::= single_valued_path_expression |
scalar_expression |
aggregate_expression |
identification_variable | <code class="literal">OBJECT</code> (identification_variable)|
constructor_expression
</p>
</li><li class="listitem">
<p>
constructor_expression ::= <code class="literal">NEW</code> constructor_name(
constructor_item {, constructor_item}*)
</p>
</li><li class="listitem">
<p>
constructor_item ::= single_valued_path_expression |
scalar_expression |
aggregate_expression |
identification_variable
</p>
</li><li class="listitem">
<p>
aggregate_expression ::= { <code class="literal">AVG</code> | <code class="literal">MAX</code> |
<code class="literal">MIN</code> | <code class="literal">SUM</code> }([ <code class="literal">DISTINCT</code>
] state_field_path_expression) | <code class="literal">COUNT</code> ([ <code class="literal">DISTINCT
</code> ] identification_variable | state_field_path_expression |
single_valued_object_path_expression)
</p>
</li><li class="listitem">
<p>
where_clause ::= <code class="literal">WHERE</code> conditional_expression
</p>
</li><li class="listitem">
<p>
groupby_clause ::= <code class="literal">GROUP</code><code class="literal">BY</code> groupby_item {,
groupby_item}*
</p>
</li><li class="listitem">
<p>
groupby_item ::= single_valued_path_expression | identification_variable
</p>
</li><li class="listitem">
<p>
having_clause ::= <code class="literal">HAVING</code> conditional_expression
</p>
</li><li class="listitem">
<p>
orderby_clause ::= <code class="literal">ORDER</code><code class="literal">BY</code> orderby_item {,
orderby_item}*
</p>
</li><li class="listitem">
<p>
orderby_item ::= state_field_path_expression | result_variable [ <code class="literal">ASC</code> |
<code class="literal">DESC</code> ]
</p>
</li><li class="listitem">
<p>
subquery ::= simple_select_clause subquery_from_clause [where_clause]
[groupby_clause] [having_clause]
</p>
</li><li class="listitem">
<p>
subquery_from_clause ::= <code class="literal">FROM</code>
subselect_identification_variable_declaration {,
subselect_identification_variable_declaration |
collection_member_declaration}*
</p>
</li><li class="listitem">
<p>
subselect_identification_variable_declaration ::=
identification_variable_declaration | derived_path_expression [ <code class="literal">AS
</code> ] identification_variable | derived_collection_member_declaration
</p>
</li><li class="listitem">
<p>
derived_path_expression ::=
superquery_identification_variable.{single_valued_object_field.}*collection_valued_field |
superquery_identification_variable.{single_valued_object_field.}*single_valued_object_field
</p>
</li><li class="listitem">
<p>
derived_collection_member_declaration ::=
IN superquery_identification_variable.{single_valued_object_field.}*collection_valued_field
</p>
</li><li class="listitem">
<p>
simple_select_clause ::= <code class="literal">SELECT</code> [ <code class="literal">DISTINCT</code>
] simple_select_expression
</p>
</li><li class="listitem">
<p>
simple_select_expression ::= single_valued_path_expression |
scalar_expression | aggregate_expression | identification_variable
</p>
</li><li class="listitem">
<p>
scalar_expression ::=
simple_arithmetic_expression |
string_primary |
enum_primary |
datetime_primary |
boolean_primary |
case_expression |
entity_type_expression
</p>
</li><li class="listitem">
<p>
conditional_expression ::= conditional_term | conditional_expression <code class="literal">
OR</code> conditional_term
</p>
</li><li class="listitem">
<p>
conditional_term ::= conditional_factor | conditional_term <code class="literal">AND
</code> conditional_factor
</p>
</li><li class="listitem">
<p>
conditional_factor ::= [ <code class="literal">NOT</code> ] conditional_primary
</p>
</li><li class="listitem">
<p>
conditional_primary ::= simple_cond_expression |(conditional_expression)
</p>
</li><li class="listitem">
<p>
simple_cond_expression ::= comparison_expression | between_expression |
like_expression | in_expression | null_comparison_expression |
empty_collection_comparison_expression | collection_member_expression |
exists_expression
</p>
</li><li class="listitem">
<p>
between_expression ::= arithmetic_expression [ <code class="literal">NOT</code> ]
<code class="literal">BETWEEN</code> arithmetic_expression <code class="literal">AND</code>
arithmetic_expression | string_expression [ <code class="literal">NOT</code> ] <code class="literal">
BETWEEN</code> string_expression <code class="literal">AND</code> string_expression |
datetime_expression [ <code class="literal">NOT</code> ] <code class="literal">BETWEEN</code>
datetime_expression <code class="literal">AND</code> datetime_expression
</p>
</li><li class="listitem">
<p>
in_expression ::= {state_field_path_expression | type_discriminator} [ <code class="literal">NOT</code> ]
<code class="literal">IN</code> {( in_item {, in_item}*) | (subquery) | collection_valued_input_parameter }
</p>
</li><li class="listitem">
<p>
in_item ::= literal | single_valued_input_parameter
</p>
</li><li class="listitem">
<p>
like_expression ::= string_expression [ <code class="literal">NOT</code> ] <code class="literal">LIKE
</code> pattern_value [ <code class="literal">ESCAPE</code> escape_character]
</p>
</li><li class="listitem">
<p>
null_comparison_expression ::= {single_valued_path_expression | input_parameter}
<code class="literal">IS</code> [ <code class="literal">NOT</code> ] <code class="literal">NULL</code>
</p>
</li><li class="listitem">
<p>
empty_collection_comparison_expression ::= collection_valued_path_expression
<code class="literal">IS</code> [ <code class="literal">NOT</code> ] <code class="literal">EMPTY</code>
</p>
</li><li class="listitem">
<p>
collection_member_expression ::= entity_expression [ <code class="literal">NOT</code> ]
<code class="literal">MEMBER</code> [ <code class="literal">OF</code> ]
collection_valued_path_expression
</p>
</li><li class="listitem">
<p>
entity_or_value_expression ::=
single_valued_object_path_expression |
state_field_path_expression |
simple_entity_or_value_expression
</p>
</li><li class="listitem">
<p>
simple_entity_or_value_expression ::=
identification_variable |
input_parameter |
literal
</p>
</li><li class="listitem">
<p>
exists_expression ::= [ <code class="literal">NOT</code> ] <code class="literal">EXISTS</code>
(subquery)
</p>
</li><li class="listitem">
<p>
all_or_any_expression ::= { <code class="literal">ALL</code> | <code class="literal">ANY</code> |
<code class="literal">SOME</code> }(subquery)
</p>
</li><li class="listitem">
<p>
comparison_expression ::=
string_expressioncomparison_operator{string_expression|all_or_any_expression}|
boolean_expression {=|&lt;&gt;} {boolean_expression | all_or_any_expression} |
enum_expression {=|&lt;&gt;} {enum_expression | all_or_any_expression} |
datetime_expression comparison_operator {datetime_expression |
all_or_any_expression} | entity_expression {= |&lt;&gt; } {entity_expression |
all_or_any_expression} | arithmetic_expression comparison_operator
{arithmetic_expression | all_or_any_expression} |
entity_type_expression { =|&lt;&gt;&gt;} entity_type_expression}
</p>
</li><li class="listitem">
<p>
comparison_operator ::== |&gt; |&gt;= |&lt; |&lt;= |&lt;&gt;
</p>
</li><li class="listitem">
<p>
arithmetic_expression ::= simple_arithmetic_expression |(subquery)
</p>
</li><li class="listitem">
<p>
simple_arithmetic_expression ::= arithmetic_term | simple_arithmetic_expression
{+ |- } arithmetic_term
</p>
</li><li class="listitem">
<p>
arithmetic_term ::= arithmetic_factor | arithmetic_term {* |/ }
arithmetic_factor
</p>
</li><li class="listitem">
<p>
arithmetic_factor ::= [{+ |-}] arithmetic_primary
</p>
</li><li class="listitem">
<p>
arithmetic_primary ::= state_field_path_expression | numeric_literal |
(simple_arithmetic_expression) | input_parameter | functions_returning_numerics
| aggregate_expression |
case_expression
</p>
</li><li class="listitem">
<p>
string_expression ::= string_primary |(subquery)
</p>
</li><li class="listitem">
<p>
string_primary ::= state_field_path_expression | string_literal |
input_parameter | functions_returning_strings | aggregate_expression |
case_expression
</p>
</li><li class="listitem">
<p>
datetime_expression ::= datetime_primary |(subquery)
</p>
</li><li class="listitem">
<p>
datetime_primary ::= state_field_path_expression | input_parameter |
functions_returning_datetime | aggregate_expression |
case_expression |
date_time_timestamp_literal
</p>
</li><li class="listitem">
<p>
boolean_expression ::= boolean_primary |(subquery)
</p>
</li><li class="listitem">
<p>
boolean_primary ::= state_field_path_expression | boolean_literal |
input_parameter |
case_expression
</p>
</li><li class="listitem">
<p>
enum_expression ::= enum_primary |(subquery)
</p>
</li><li class="listitem">
<p>
enum_primary ::= state_field_path_expression | enum_literal | input_parameter |
case_expression
</p>
</li><li class="listitem">
<p>
entity_expression ::= single_valued_object_path_expression |
simple_entity_expression
</p>
</li><li class="listitem">
<p>
simple_entity_expression ::= identification_variable | input_parameter
</p>
</li><li class="listitem">
<p>
entity_type_expression ::=
type_discriminator |
entity_type_literal |
input_parameter
</p>
</li><li class="listitem">
<p>
type_discriminator ::=
<code class="literal">TYPE</code>(identification_variable |
single_valued_object_path_expression |
input_parameter)
</p>
</li><li class="listitem">
<p>
functions_returning_numerics ::= <code class="literal">LENGTH</code> (string_primary)|
<code class="literal">LOCATE</code> (string_primary,string_primary [,
simple_arithmetic_expression]) | <code class="literal">ABS</code>
(simple_arithmetic_expression) | <code class="literal">SQRT</code>
(simple_arithmetic_expression) | <code class="literal">MOD</code>
(simple_arithmetic_expression, simple_arithmetic_expression) | <code class="literal">SIZE
</code> (collection_valued_path_expression) |
<code class="literal">INDEX</code>(identification_variable)
</p>
</li><li class="listitem">
<p>
functions_returning_datetime ::= <code class="literal">CURRENT_DATE</code> | <code class="literal">
CURRENT_TIME</code> | <code class="literal">CURRENT_TIMESTAMP</code>
</p>
</li><li class="listitem">
<p>
functions_returning_strings ::= <code class="literal">CONCAT</code> (string_primary,
string_primary) | <code class="literal">SUBSTRING</code> (string_primary,
simple_arithmetic_expression[,simple_arithmetic_expression])| <code class="literal">TRIM
</code> ([[trim_specification] [trim_character] <code class="literal">FROM</code> ]
string_primary) | <code class="literal">LOWER</code> (string_primary) | <code class="literal">UPPER
</code> (string_primary)
</p>
</li><li class="listitem">
<p>
trim_specification ::= <code class="literal">LEADING</code> | <code class="literal">TRAILING</code>
| <code class="literal">BOTH</code>
</p>
</li><li class="listitem">
<p>
case_expression ::=
general_case_expression |
simple_case_expression |
coalesce_expression |
nullif_expression
</p>
</li><li class="listitem">
<p>
general_case_expression::=
<code class="literal">CASE</code> when_clause {when_clause}* <code class="literal">ELSE</code> scalar_expression <code class="literal">END</code>
</p>
</li><li class="listitem">
<p>
when_clause::= <code class="literal">WHEN</code> conditional_expression <code class="literal">THEN</code> scalar_expression
</p>
</li><li class="listitem">
<p>
simple_case_expression::=
<code class="literal">CASE</code> case_operand simple_when_clause {simple_when_clause}*
<code class="literal">ELSE</code> scalar_expression
<code class="literal">END</code>
</p>
</li><li class="listitem">
<p>
case_operand::= state_field_path_expression | type_discriminator
</p>
</li><li class="listitem">
<p>
simple_when_clause::= <code class="literal">WHEN</code> scalar_expression <code class="literal">THEN</code> scalar_expression
</p>
</li><li class="listitem">
<p>
coalesce_expression::= <code class="literal">COALESCE</code>(scalar_expression {, scalar_expression}+)
</p>
</li><li class="listitem">
<p>
nullif_expression::= <code class="literal">NULLIF</code>(scalar_expression, scalar_expression)
</p>
</li></ul></div>
</div>
</div>
</div>
<div class="chapter" id="jpa_overview_criteria"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;11.&nbsp;
JPA Criteria
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#d5e5247">1. Constructing a CriteriaQuery</a></span></dt><dt><span class="section"><a href="#d5e5264">2. Executing a CriteriaQuery</a></span></dt><dt><span class="section"><a href="#d5e5271">3. Extension to Criteria API</a></span></dt><dt><span class="section"><a href="#d5e5275">4. Generation of Canonical MetaModel classes</a></span></dt></dl></div>
<a class="indexterm" name="d5e5238"></a>
<a class="indexterm" name="d5e5241"></a>
<p>
JPA 2.0 specification introduces a new API to define queries dynamically
via construction of an object-based
<code class="classname">javax.persistence.CriteriaQuery</code> instance, rather
than string-based approach used in JPQL (Java Persistence Query Language).
This dynamic query definition capability, referred as Criteria API, is
based on the abstract persistent schema of the entities, their embedded
objects and their relationships. The syntax is designed to construct a
<span class="emphasis"><em>Query Tree</em></span> whose nodes represent the semantic query
elements such as projections, conditional predicates of WHERE clause or
GROUP BY elements etc.
</p>
<div class="section" id="d5e5247"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;Constructing a CriteriaQuery</h2></div></div></div>
<p>
The CriteriaBuilder interface is the factory for CriteriaQuery. A
CriteriaBuilder is obtained from either an EntityManagerFactory or
an EntityManager as follows:
</p><pre class="programlisting">
EntityManager em = ... ;
CriteriaBuilder queryBuilder = em.getCriteriaBuilder();
CriteriaQuery qdef = queryBuilder.createQuery();
</pre><p>
The first step in constructing a query definition is specification of
query roots. Query roots specify the domain objects on which the query
is evaluated. Query root is an instance of the Root&lt;T&gt; interface. A
query root is added to a CriteriaQuery by
<code class="methodname">addRoot(Class c)</code> method.
</p><pre class="programlisting">
Root&lt;Customer&gt; customer = qdef.from(Customer.class);
</pre><p>
A query domain can be further refined by joining to other domain objects.
For example, for the above query definition to operate over customers
and their orders, use <code class="methodname">join(String attribute)</code>:
</p><pre class="programlisting">
Root&lt;Order&gt; order = customer.join(customer.get(Customer_.orders));
</pre><p>
where Customer_.orders represent a field of canonical metamodel class for Customer.
These canonical metamodel classes are generated during compilation by processing
the persistent annotation in the source code of Customer.java.
</p>
<p>
The condition of a query definition is set via
<code class="methodname">where(Predicate p)</code> where the argument
designates a conditional predicate. Conditional predicates are often
composed of one or more comparisons between the attribute values of
the domain objects and some variable. For example, to select the
Customer whose name is <span class="emphasis"><em>"John Doe"</em></span> and has
orders that are not yet delivered, you can build the predicate and set
it to the query definition as:
</p><pre class="programlisting">
qdef.where(customer.get(Customer_.name).equal("John Doe")
.and(order.get(Order_.status).equal(OrderStatus.DELIVERED).not()));
</pre><p>
The <code class="methodname">select()</code> method defines the result of the
query. If left unspecified, the select projection is assumed to be the
root domain object. However, you can specify the selected projections
explicitly as a list:
</p><pre class="programlisting">
qdef.select(customer.get(Customer_.name), order.get(Order_.status));
</pre><p>
</p>
<p>
An attribute of a domain object can also be specified by navigating via
<code class="methodname">get(String attr)</code>. The attribute
<span class="emphasis"><em>should</em></span> refer
to a valid persistent property of the receiving domain object, however
no such validation is enforced during the construction of the query
definition. All validation is deferred until the query is actually executed.
On the other hand, using canonical metamodel for path navigate enforces
compile type checking.
</p>
</div>
<div class="section" id="d5e5264"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;Executing a CriteriaQuery</h2></div></div></div>
<p>
A CriteriaQuery is executed in a similar fashion to a string-based JPQL
query via the EntityManager and Query interfaces.
</p><pre class="programlisting">
EntityManager em = ...
Query query = em.createQuery(qdef);
List result = query.getResultList();
</pre><p>
</p>
<p>
A query definition can use named parameters, and the parameter values are
set as usual in the Query instance.
</p>
<p>
<a class="ulink" href="http://www.ibm.com/developerworks/java/library/j-typesafejpa/" target="_top">A developerworks article</a>
explains details and further usage of Criteria API and its OpenJPA extensions.
</p>
</div>
<div class="section" id="d5e5271"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;Extension to Criteria API</h2></div></div></div>
<p>
Criteria API has provided an alternative means to string-based JPQL to
execute a query. However, JPA 2.0 specification has not explicitly specified
any equivalence between a dynamically constructed CriteriaQuery and
a JPQL string. OpenJPA provides a mechanism to convert a CriteriaQuery to
an equivalent JPQL query string via the extended OpenJPACriteriaQuery API.
</p><pre class="programlisting">
public interface OpenJPACriteriaQuery extends CriteriaQuery {
/**
* Gets equivalent JPQL String for the given CriteriaQuery.
*/
public String toCQL();
}
</pre><p>
</p>
</div>
<div class="section" id="d5e5275"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;Generation of Canonical MetaModel classes</h2></div></div></div>
<p>
Annotation processing tool generates source code for a metamodel class given
the annotated source code of persistent entity.
This tool is invoked during compilation for JDK6 compiler if OpenJPA and JPA
libraries are specified in the compiler <code class="code">-classpath</code> option <span class="emphasis"><em>and</em></span>
Annotation processor option <code class="code">-Aopenjpa.metamodel=true</code> is specified.
</p><pre class="programlisting">
$ javac -classpath path/to/openjpa-all.jar -Aopenjpa.metamodel=true mypackage/MyEntity.java
</pre><p>
will generate source code for canonical meta-model class <code class="code">mypackage.MyEntity_</code>.
The source code is generated relative to the directory specified in <code class="code">-s</code> option
of <code class="code">javac</code> compiler and defaulted to the current directory.
</p>
<p>
The Annotation Processor recognizes the following options specified in the command-line with <code class="code">-A</code>
(none of them are mandatory).
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
-Aopenjpa.log=TRACE|INFO|WARN|ERROR : The logging level. Default is <code class="code">WARN</code>.
</p>
</li><li class="listitem">
<p>
-Aopenjpa.source=&lt;n&gt; : where &lt;n&gt; denotes the integral number for Java source
version of the generated code. Default is <code class="code">6</code>.
</p>
</li><li class="listitem">
<p>
-Aopenjpa.naming=class name : fully-qualified name of a class implementing
<code class="code">org.apache.openjpa.meta.MetaDataFactory</code> that determines
the name of a meta-class given the name of the original persistent Java entity class. Defaults to
<code class="code">org.apache.openjpa.persistence.PersistenceMetaDataFactory</code> which appends an underscore character
(<code class="code">_</code>) to the original Java class name.
</p>
</li><li class="listitem">
<p>
-Aopenjpa.header=&lt;url&gt; : A url whose content will appear as comment header to the generated file(s).
Recognizes special value <code class="code">ASL</code> for Apache Source License header as comment.
By default, adds an OpenJPA proprietary text as comment block.
</p>
</li></ul></div><p>
</p>
</div>
</div>
<div class="chapter" id="jpa_overview_sqlquery"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;12.&nbsp;
SQL Queries
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_sqlquery_create">1.
Creating SQL Queries
</a></span></dt><dt><span class="section"><a href="#jpa_overview_sqlquery_obj">2.
Retrieving Persistent Objects with SQL
</a></span></dt></dl></div>
<a class="indexterm" name="d5e5304"></a>
<a class="indexterm" name="d5e5307"></a>
<a class="indexterm" name="d5e5311"></a>
<a class="indexterm" name="d5e5315"></a>
<p>
JPQL is a powerful query language, but there are times when it is not enough.
Maybe you're migrating a JDBC application to JPA on a strict deadline, and you
don't have time to translate your existing SQL selects to JPQL. Or maybe a
certain query requires database-specific SQL your JPA implementation doesn't
support. Or maybe your DBA has spent hours crafting the perfect select statement
for a query in your application's critical path. Whatever the reason, SQL
queries can remain an essential part of an application.
</p>
<p>
You are probably familiar with executing SQL queries by obtaining a <code class="classname">
java.sql.Connection</code>, using the JDBC APIs to create a <code class="classname">
Statement</code>, and executing that <code class="classname">Statement</code> to
obtain a <code class="classname">ResultSet</code>. And of course, you are free to
continue using this low-level approach to SQL execution in your JPA
applications. However, JPA also supports executing SQL queries through the
<code class="classname">javax.persistence.Query</code> interface introduced in
<a class="xref" href="#jpa_overview_query" title="Chapter&nbsp;10.&nbsp; JPA Query">Chapter&nbsp;10, <i>
JPA Query
</i></a>. Using a JPA SQL query, you can
retrieve either persistent objects or projections of column values. The
following sections detail each use.
</p>
<div class="section" id="jpa_overview_sqlquery_create"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Creating SQL Queries
</h2></div></div></div>
<a class="indexterm" name="d5e5329"></a>
<p>
The <code class="classname">EntityManager</code> has two factory methods suitable for
creating SQL queries:
</p>
<pre class="programlisting">
public Query createNativeQuery(String sqlString, Class resultClass);
public Query createNativeQuery(String sqlString, String resultSetMapping);
</pre>
<p>
The first method is used to create a new <code class="classname">Query</code> instance
that will return instances of the specified class.
</p>
<p>
The second method uses a <code class="literal">SqlResultSetMapping</code> to determine the
type of object or objects to return. The example below shows these methods in
action.
</p>
<div class="example" id="jpa_overview_sqlquery_createex"><p class="title"><b>Example&nbsp;12.1.&nbsp;
Creating a SQL Query
</b></p><div class="example-contents">
<pre class="programlisting">
EntityManager em = ...;
Query query = em.createNativeQuery("SELECT * FROM MAG", Magazine.class);
processMagazines(query.getResultList());
</pre>
</div></div><br class="example-break">
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
<a class="indexterm" name="d5e5344"></a>
<a class="indexterm" name="d5e5347"></a>
In addition to SELECT statements, OpenJPA supports stored procedure invocations
as SQL queries. OpenJPA will assume any SQL that does not begin with the
<code class="literal">SELECT</code> keyword (ignoring case) is a stored procedure call,
and invoke it as such at the JDBC level.
</p>
</div>
</div>
<div class="section" id="jpa_overview_sqlquery_obj"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Retrieving Persistent Objects with SQL
</h2></div></div></div>
<a class="indexterm" name="d5e5354"></a>
<a class="indexterm" name="d5e5357"></a>
<p>
When you give a SQL <code class="classname">Query</code> a candidate class, it will
return persistent instances of that class. At a minimum, your SQL must select
the class' primary key columns, discriminator column (if mapped), and version
column (also if mapped). The JPA runtime uses the values of the primary key
columns to construct each result object's identity, and possibly to match it
with a persistent object already in the <code class="classname">EntityManager</code>'s
cache. When an object is not already cached, the implementation creates a new
object to represent the current result row. It might use the discriminator
column value to make sure it constructs an object of the correct subclass.
Finally, the query records available version column data for use in optimistic
concurrency checking, should you later change the result object and flush it
back to the database.
</p>
<p>
Aside from the primary key, discriminator, and version columns, any columns you
select are used to populate the persistent fields of each result object. JPA
implementations will compete on how effectively they map your selected data to
your persistent instance fields.
</p>
<p>
Let's make the discussion above concrete with an example. It uses the following
simple mapping between a class and the database:
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="213"><tr><td><img src="img/sqlquery-model.png"></td></tr></table></div>
<div class="example" id="jpa_overview_sqlquery_objex"><p class="title"><b>Example&nbsp;12.2.&nbsp;
Retrieving Persistent Objects
</b></p><div class="example-contents">
<pre class="programlisting">
Query query = em.createNativeQuery("SELECT ISBN, TITLE, PRICE, "
+ "VERS FROM MAG WHERE PRICE &gt; 5 AND PRICE &lt; 10", Magazine.class);
List&lt;Magazine&gt; results = (List&lt;Magazine&gt;) query.getResultList();
for (Magazine mag : results)
processMagazine(mag);
</pre>
</div></div><br class="example-break">
<p>
The query above works as advertised, but isn't very flexible. Let's update it to
take in parameters for the minimum and maximum price, so we can reuse it to find
magazines in any price range:
</p>
<div class="example" id="jpa_overview_sqlquery_obj_paramex"><p class="title"><b>Example&nbsp;12.3.&nbsp;
SQL Query Parameters
</b></p><div class="example-contents">
<pre class="programlisting">
Query query = em.createNativeQuery("SELECT ISBN, TITLE, PRICE, "
+ "VERS FROM MAG WHERE PRICE &gt; ?1 AND PRICE &lt; ?2", Magazine.class);
query.setParameter(1, 5d);
query.setParameter(2, 10d);
List&lt;Magazine&gt; results = (List&lt;Magazine&gt;) query.getResultList();
for (Magazine mag : results)
processMagazine(mag);
</pre>
</div></div><br class="example-break">
<p>
<a class="indexterm" name="d5e5377"></a>
<a class="indexterm" name="d5e5380"></a>
Like JDBC prepared statements, SQL queries represent parameters with question
marks, but are followed by an integer to represent its index.
</p>
</div>
</div>
<div class="chapter" id="jpa_overview_mapping"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;13.&nbsp;
Mapping Metadata
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_table">1.
Table
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_unq">2.
Unique Constraints
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_column">3.
Column
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_id">4.
Identity Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence">5.
Generators
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_sequence_seqgen">5.1.
Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_tablegen">5.2.
Table Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_genex">5.3.
Example
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher">6.
Inheritance
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_single">6.1.
Single Table
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_adv">6.1.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_disadv">6.1.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined">6.2.
Joined
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_adv">6.2.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_disadv">6.2.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc">6.3.
Table Per Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_adv">6.3.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_disadv">6.3.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_together">6.4.
Putting it All Together
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_discrim">7.
Discriminator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_field">8.
Field Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_basic">8.1.
Basic Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_lob">8.1.1.
LOBs
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_enum">8.1.2.
Enumerated
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_temporal">8.1.3.
Temporal Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_basic_example">8.1.4.
The Updated Mappings
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_secondary">8.2.
Secondary Tables
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_embed">8.3.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_rel">8.4.
Direct Relations
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_assoccoll">8.5.
Join Table
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_bidi">8.6.
Bidirectional Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_map">8.7.
Map Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_full">9.
The Complete Mappings
</a></span></dt></dl></div>
<a class="indexterm" name="d5e5386"></a>
<a class="indexterm" name="d5e5388"></a>
<a class="indexterm" name="d5e5392"></a>
<a class="indexterm" name="d5e5396"></a>
<a class="indexterm" name="d5e5399"></a>
<p>
<span class="emphasis"><em>Object-relational mapping</em></span> is the process of mapping
entities to relational database tables. In JPA, you perform
object/relational mapping through <span class="emphasis"><em>mapping metadata</em></span>.
Mapping metadata uses annotations to describe how to link your object model to
your relational model.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA offers tools to automate mapping and schema creation. See
<a class="xref" href="#ref_guide_mapping" title="Chapter&nbsp;7.&nbsp; Mapping">Chapter&nbsp;7, <i>
Mapping
</i></a> in the Reference Guide.
</p>
</div>
<p>
Throughout this chapter, we will draw on the object model introduced in
<a class="xref" href="#jpa_overview_meta" title="Chapter&nbsp;5.&nbsp; Metadata">Chapter&nbsp;5, <i>
Metadata
</i></a>. We present that model again below.
As we discuss various aspects of mapping metadata, we will zoom in on specific
areas of the model and show how we map the object layer to the relational layer.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="369"><tr><td><img src="img/jpa-meta-model.png"></td></tr></table></div>
<p>
All mapping metadata is optional. Where no explicit mapping metadata is given,
JPA uses the defaults defined by the specification. As we present
each mapping throughout this chapter, we also describe the defaults that apply
when the mapping is absent.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Mapping metadata is used primarily with schema generation. This metadata should not
be relied upon for validation prior to communicating with the database.
For example using the @Column(nullable=false) annotation does not do up front validation
that the value in the entity is correct.
</p>
</div>
<div class="section" id="jpa_overview_mapping_table"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Table
</h2></div></div></div>
<a class="indexterm" name="d5e5419"></a>
<p>
The <code class="classname">Table</code> annotation specifies the table for an entity
class. If you omit the <code class="classname">Table</code> annotation, base entity
classes default to a table with their unqualified class name. The default table
of an entity subclass depends on the inheritance strategy, as you will see in
<a class="xref" href="#jpa_overview_mapping_inher" title="6.&nbsp; Inheritance">Section&nbsp;6, &#8220;
Inheritance
&#8221;</a>.
</p>
<p>
<code class="classname">Table</code>s have the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the table. Defaults to the
unqualified entity class name.
</p>
</li><li class="listitem">
<p>
<code class="literal">String schema</code>: The table's schema. If you do not name a
schema, JPA uses the default schema for the database connection.
</p>
</li><li class="listitem">
<p>
<code class="literal">String catalog</code>: The table's catalog. If you do not name a
catalog, JPA uses the default catalog for the database connection.
</p>
</li><li class="listitem">
<p>
<code class="literal">UniqueConstraint[] uniqueConstraints</code>: An array of unique
constraints to place on the table. We cover unique constraints below. Defaults
to an empty array.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">table</code>. It has the following
attributes, which correspond to the annotation properties above:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">schema</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">catalog</code>
</p>
</li></ul></div>
<p>
The <code class="literal">table</code> element also accepts nested <code class="literal">
unique-constraint</code> elements representing unique constraints. We will
detail unique constraints shortly.
</p>
<p>
Sometimes, some of the fields in a class are mapped to secondary tables. In that
case, use the class' <code class="classname">Table</code> annotation to name what you
consider the class' primary table. Later, we will see how to map certain fields
to other tables.
</p>
<p>
The example below maps classes to tables to separate schemas. The
<code class="literal">CONTRACT</code>, <code class="literal">SUB</code>, and <code class="literal">LINE_ITEM
</code> tables are in the <code class="literal">CNTRCT</code> schema; all other tables
are in the default schema.
</p>
<div class="example" id="jpa_overview_mapping_classex"><p class="title"><b>Example&nbsp;13.1.&nbsp;
Mapping Classes
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
@Table(name="MAG")
public class Magazine {
...
public static class MagazineId {
...
}
}
@Entity
@Table(name="ART")
public class Article {
...
}
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
...
}
@Entity
@Table(name="AUTH")
public class Author {
...
}
@Embeddable
public class Address {
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
...
}
@Entity
@Table(schema="CNTRCT")
public class Contract
extends Document {
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
public class Subscription {
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
...
}
}
@Entity(name="Lifetime")
public class LifetimeSubscription
extends Subscription {
...
}
@Entity(name="Trial")
public class TrialSubscription
extends Subscription {
...
}
</pre>
<p>
The same mapping information expressed in XML:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"&gt;
&lt;mapped-superclass class="org.mag.subscribe.Document"&gt;
...
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;id-class="org.mag.Magazine.MagazineId"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;table schema="CNTRCT"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Subscription"&gt;
&lt;table name="SUB" schema="CNTRCT"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription" name="Lifetime"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.TrialSubscription" name="Trial"&gt;
...
&lt;/entity&gt;
&lt;embeddable class="org.mag.pub.Address"&gt;
...
&lt;/embeddable&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_mapping_unq"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Unique Constraints
</h2></div></div></div>
<a class="indexterm" name="d5e5471"></a>
<a class="indexterm" name="d5e5475"></a>
<p>
Unique constraints ensure that the data in a column or combination of columns is
unique for each row. A table's primary key, for example, functions as an
implicit unique constraint. In JPA, you represent other unique
constraints with an array of <code class="classname"> UniqueConstraint</code>
annotations within the table annotation. The unique constraints you define are
used during table creation to generate the proper database constraints, and may
also be used at runtime to order <code class="literal">INSERT</code>, <code class="literal">UPDATE
</code>, and <code class="literal">DELETE</code> statements. For example, suppose there
is a unique constraint on the columns of field <code class="literal">F</code>. In the
same transaction, you remove an object <code class="literal">A</code> and persist a new
object <code class="literal">B</code>, both with the same <code class="literal">F</code> value. The
JPA runtime must ensure that the SQL deleting <code class="literal">A</code>
is sent to the database before the SQL inserting <code class="literal">B</code> to avoid a
unique constraint violation.
</p>
<p>
<code class="classname">UniqueConstraint</code> has these properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the constraint. OpenJPA will choose
a name if you do not provide one, or will create an anonymous constraint.
</p>
</li><li class="listitem">
<p>
<code class="literal">String[] columnNames</code>: The names of the columns the
constraint spans.
</p>
</li></ul></div>
<p>
In XML, unique constraints are represented by nesting <code class="literal">
unique-constraint</code> elements within the <code class="literal"> table</code>
element. Each <code class="literal">unique-constraint</code> element in turn nests
<code class="literal">column-name</code> text elements to enumerate the constraint's
columns.
</p>
<div class="example" id="jpa_overview_mapping_unq_attrex"><p class="title"><b>Example&nbsp;13.2.&nbsp;
Defining a Unique Constraint
</b></p><div class="example-contents">
<p>
The following defines a unique constraint on the <code class="literal"> TITLE</code>
column of the <code class="literal">ART</code> table:
</p>
<pre class="programlisting">
@Entity
@Table(name="ART", uniqueConstraints=@UniqueConstraint(name="TITLE_CNSTR", columnNames="TITLE"))
public class Article {
...
}
</pre>
<p>
The same metadata expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"&gt;
&lt;unique-constraint&gt;
&lt;name&gt;TITLE_CNSTR&lt;/name&gt;
&lt;column-name&gt;TITLE&lt;/column-name&gt;
&lt;/unique-constraint&gt;
&lt;/table&gt;
...
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_mapping_column"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Column
</h2></div></div></div>
<a class="indexterm" name="d5e5512"></a>
<a class="indexterm" name="d5e5515"></a>
<p>
In the previous section, we saw that a <code class="classname">UniqueConstraint</code>
uses an array of column names. Field mappings, however, use full-fledged
<code class="classname">Column</code> annotations. Column annotations have the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e5525"></a>
<code class="literal">String name</code>: The column name. Defaults to the field name.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5532"></a>
<code class="literal">String columnDefinition</code>: The database-specific column type
name. This property is only used by vendors that support creating tables from
your mapping metadata. During table creation, the vendor will use the value of
the <code class="literal">columnDefinition</code> as the declared column type. If no
<code class="literal">columnDefinition</code> is given, the vendor will choose an
appropriate default based on the field type combined with the column's length,
precision, and scale.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5541"></a>
<code class="literal">int length</code>: The column length. This property is typically
only used during table creation, though some vendors might use it to validate
data before flushing. <code class="literal">CHAR</code> and <code class="literal">VARCHAR</code>
columns typically default to a length of 255; other column types use the
database default.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5550"></a>
<code class="literal">int precision</code>: The precision of a numeric column. This
property is often used in conjunction with <code class="literal">scale</code> to form the
proper column type name during table creation.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5558"></a>
<code class="literal">int scale</code>: The number of decimal digits a numeric column can
hold. This property is often used in conjunction with <code class="literal">precision
</code> to form the proper column type name during table creation.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5566"></a>
<code class="literal">boolean nullable</code>: Whether the column can store null values.
Vendors may use this property both for table creation and at runtime; however,
it is never required. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5574"></a>
<code class="literal">boolean insertable</code>: By setting this property to <code class="literal">
false</code>, you can omit the column from SQL <code class="literal">INSERT</code>
statements. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5584"></a>
<code class="literal">boolean updatable</code>: By setting this property to <code class="literal">
false</code>, you can omit the column from SQL <code class="literal">UPDATE</code>
statements. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5594"></a>
<code class="literal">String table</code>: Sometimes you will need to map fields to
tables other than the primary table. This property allows you specify that the
column resides in a secondary table. We will see how to map fields to secondary
tables later in the chapter.
</p>
</li></ul></div>
<p>
The equivalent XML element is <code class="literal">column</code>. This element has
attributes that are exactly equivalent to the <code class="classname"> Column</code>
annotation's properties described above:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">column-definition</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">length</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">precision</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">scale</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">insertable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">updatable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">table</code>
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_mapping_id"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Identity Mapping
</h2></div></div></div>
<a class="indexterm" name="d5e5629"></a>
<a class="indexterm" name="d5e5631"></a>
<a class="indexterm" name="d5e5634"></a>
<p>
With our new knowledge of columns, we can map the identity fields of our
entities. The diagram below now includes primary key columns for our model's
tables. The primary key column for <code class="classname">Author</code> uses
nonstandard type <code class="literal"> INTEGER64</code>, and the <code class="literal">Magazine.isbn
</code> field is mapped to a <code class="literal">VARCHAR(9)</code> column instead of
a <code class="literal">VARCHAR(255)</code> column, which is the default for string
fields. We do not need to point out either one of these oddities to the JPA
implementation for runtime use. If, however, we want to use the JPA
implementation to create our tables for us, it needs to know about
any desired non-default column types. Therefore, the example following the
diagram includes this data in its encoding of our mappings.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="341"><tr><td><img src="img/jpa-mapping-identity.png"></td></tr></table></div>
<p>
Note that many of our identity fields do not need to specify column information,
because they use the default column name and type.
</p>
<div class="example" id="jpa_overview_mapping_identityex"><p class="title"><b>Example&nbsp;13.3.&nbsp;
Identity Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
@Table(name="MAG")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
...
public static class MagazineId {
...
}
}
@Entity
@Table(name="ART", uniqueConstraints=@Unique(columnNames="TITLE"))
public class Article {
@Id private long id;
...
}
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
@Column(name="CID")
@Id private long id;
...
}
@Entity
@Table(name="AUTH")
public class Author {
@Column(name="AID", columnDefinition="INTEGER64")
@Id private long id;
...
}
@Embeddable
public class Address {
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
...
}
@Entity
@Table(schema="CNTRCT")
public class Contract
extends Document {
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
public class Subscription {
@Id private long id;
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
...
}
}
@Entity(name="Lifetime")
public class LifetimeSubscription
extends Subscription {
...
}
@Entity(name="Trial")
public class TrialSubscription
extends Subscription {
...
}
</pre>
<p>
The same metadata for <code class="literal">Magazine</code> and <code class="literal">Company</code>
expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.Magazine"&gt;
&lt;id-class class="org.mag.Magazine.Magazine.MagazineId"/&gt;
&lt;table name="MAG"/&gt;
&lt;attributes&gt;
&lt;id name="isbn"&gt;
&lt;column length="9"/&gt;
&lt;/id&gt;
&lt;id name="title"/&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="CID"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_mapping_sequence"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Generators
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_sequence_seqgen">5.1.
Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_tablegen">5.2.
Table Generator
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_sequence_genex">5.3.
Example
</a></span></dt></dl></div>
<a class="indexterm" name="d5e5656"></a>
<a class="indexterm" name="d5e5659"></a>
<p>
One aspect of identity mapping not covered in the previous section is JPA's
ability to automatically assign a value to your numeric identity fields using
<span class="emphasis"><em>generators</em></span>. We discussed the available generator types in
<a class="xref" href="#jpa_overview_meta_id" title="2.3.&nbsp; Id">Section&nbsp;2.3, &#8220;
Id
&#8221;</a>. Now we show you how to define
named generators.
</p>
<div class="section" id="jpa_overview_mapping_sequence_seqgen"><div class="titlepage"><div><div><h3 class="title">5.1.&nbsp;
Sequence Generator
</h3></div></div></div>
<a class="indexterm" name="d5e5669"></a>
<a class="indexterm" name="d5e5672"></a>
<p>
Most databases allow you to create native sequences. These are database
structures that generate increasing numeric values. The <code class="classname">
SequenceGenerator</code> annotation represents a named database sequence.
You can place the annotation on any package, entity class, persistent field
declaration (if your entity uses field access), or getter method for a
persistent property (if your entity uses property access). <code class="classname">
SequenceGenerator</code> has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e5680"></a>
<code class="literal">String name</code>: The generator name. This property is required.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5686"></a>
<code class="literal">String sequenceName</code>: The name of the database sequence. If
you do not specify the database sequence, your vendor will choose an appropriate
default.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5692"></a>
<code class="literal">int initialValue</code>: The initial sequence value.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5698"></a>
<code class="literal">int allocationSize</code>: The number of values to allocate in
memory for each trip to the database. Allocating values in memory allows the JPA
runtime to avoid accessing the database for every sequence request.
This number also specifies the amount that the sequence value is incremented
each time the sequence is accessed. Defaults to 50.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5704"></a>
<code class="literal">String schema</code>: The sequence's schema. If you do not name a
schema, JPA uses the default schema for the database connection.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA allows you to use one of OpenJPA's built-in generator
implementations in the <code class="literal">sequenceName</code> property. You can also
set the <code class="literal">sequenceName</code> to <code class="literal">system</code> to use the
system sequence defined by the <a class="link" href="#openjpa.Sequence" title="5.67.&nbsp; openjpa.Sequence"><code class="literal">
openjpa.Sequence</code></a> configuration property. See the Reference
Guide's <a class="xref" href="#ref_guide_sequence" title="6.&nbsp; Generators">Section&nbsp;6, &#8220;
Generators
&#8221;</a> for details.
</p>
</div>
<p>
The XML element for a sequence generator is <code class="literal">sequence-generator
</code>. Its attributes mirror the above annotation's properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">sequence-name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">initial-value</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">allocation-size</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">schema</code>
</p>
</li></ul></div>
<p>
To use a sequence generator, set your <code class="classname">GeneratedValue</code>
annotation's <code class="literal">strategy</code> property to <code class="literal">
GenerationType.SEQUENCE</code>, and its <code class="literal">generator</code> property
to the sequence generator's declared name. Or equivalently, set your <code class="literal">
generated-value</code> XML element's <code class="literal">strategy</code> attribute to
<code class="literal">SEQUENCE</code> and its <code class="literal">generator</code> attribute to
the generator name.
</p>
</div>
<div class="section" id="jpa_overview_mapping_sequence_tablegen"><div class="titlepage"><div><div><h3 class="title">5.2.&nbsp;
Table Generator
</h3></div></div></div>
<a class="indexterm" name="d5e5745"></a>
<a class="indexterm" name="d5e5748"></a>
<p>
A <code class="classname">TableGenerator</code> refers to a database table used to store
increasing sequence values for one or more entities. As with <code class="classname">
SequenceGenerator</code>, you can place the <code class="classname">TableGenerator
</code> annotation on any package, entity class, persistent field
declaration (if your entity uses field access), or getter method for a
persistent property (if your entity uses property access). <code class="classname">
TableGenerator</code> has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e5758"></a>
<code class="literal">String name</code>: The generator name. This property is required.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5764"></a>
<code class="literal">String table</code>: The name of the generator table. If left
unspecified, your vendor will choose a default table.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5770"></a>
<code class="literal">String schema</code>: The named table's schema.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5776"></a>
<code class="literal">String catalog</code>: The named table's catalog.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5782"></a>
<code class="literal">String pkColumnName</code>: The name of the primary key column in
the generator table. If unspecified, your implementation will choose a default.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5788"></a>
<code class="literal">String valueColumnName</code>: The name of the column that holds
the sequence value. If unspecified, your implementation will choose a default.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5794"></a>
<code class="literal">String pkColumnValue</code>: The primary key column value of the
row in the generator table holding this sequence value. You can use the same
generator table for multiple logical sequences by supplying different <code class="literal">
pkColumnValue</code> s. If you do not specify a value, the implementation
will supply a default.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5801"></a>
<code class="literal">int initialValue</code>: The value of the generator's first issued
number.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e5807"></a>
<code class="literal">int allocationSize</code>: The number of values to allocate in
memory for each trip to the database. Allocating values in memory allows the JPA
runtime to avoid accessing the database for every sequence request.
This number also specifies the amount that the sequence value is incremented
each time the generator table is updated. Defaults to 50.
</p>
</li></ul></div>
<p>
The XML equivalent is the <code class="literal">table-generator</code> element. This
element's attributes correspond exactly to the above annotation's properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">table</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">schema</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">catalog</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">pk-column-name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">value-column-name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">pk-column-value</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">initial-value</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">allocation-size</code>
</p>
</li></ul></div>
<p>
To use a table generator, set your <code class="classname">GeneratedValue</code>
annotation's <code class="literal">strategy</code> property to <code class="literal">
GenerationType.TABLE</code>, and its <code class="literal">generator</code> property to
the table generator's declared name. Or equivalently, set your <code class="literal">
generated-value</code> XML element's <code class="literal">strategy</code> attribute to
<code class="literal">TABLE</code> and its <code class="literal">generator</code> attribute to the
generator name.
</p>
</div>
<div class="section" id="jpa_overview_mapping_sequence_genex"><div class="titlepage"><div><div><h3 class="title">5.3.&nbsp;
Example
</h3></div></div></div>
<p>
Let's take advantage of generators in our entity model. Here are our updated
mappings.
</p>
<div class="example" id="jpa_overview_mapping_sequenceex"><p class="title"><b>Example&nbsp;13.4.&nbsp;
Generator Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
@Table(name="MAG")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
...
public static class MagazineId {
...
}
}
@Entity
@Table(name="ART", uniqueConstraints=@Unique(columnNames="TITLE"))
@SequenceGenerator(name="ArticleSeq", sequenceName="ART_SEQ")
public class Article {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ArticleSeq")
private long id;
...
}
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
@Column(name="CID")
@Id private long id;
...
}
@Entity
@Table(name="AUTH")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="AuthorGen")
@TableGenerator(name="AuthorGen", table="AUTH_GEN", pkColumnName="PK",
valueColumnName="AID")
@Column(name="AID", columnDefinition="INTEGER64")
private long id;
...
}
@Embeddable
public class Address {
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
@Id
@GeneratedValue(generate=GenerationType.IDENTITY)
private long id;
...
}
@Entity
@Table(schema="CNTRCT")
public class Contract
extends Document {
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
public class Subscription {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
...
}
}
@Entity(name="Lifetime")
public class LifetimeSubscription
extends Subscription {
...
}
@Entity(name="Trial")
public class TrialSubscription
extends Subscription {
...
}
</pre>
<p>
The same metadata for <code class="literal">Article</code> and <code class="literal">Author</code>
expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"&gt;
&lt;unique-constraint&gt;
&lt;column-name&gt;TITLE&lt;/column-name&gt;
&lt;/unique-constraint&gt;
&lt;/table&gt;
&lt;sequence-generator name="ArticleSeq" sequence-name="ART_SEQ"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="SEQUENCE" generator="ArticleSeq"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="AID" column-definition="INTEGER64"/&gt;
&lt;generated-value strategy="TABLE" generator="AuthorGen"/&gt;
&lt;table-generator name="AuthorGen" table="AUTH_GEN"
pk-column-name="PK" value-column-name="AID"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="jpa_overview_mapping_inher"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
Inheritance
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_inher_single">6.1.
Single Table
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_adv">6.1.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_disadv">6.1.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined">6.2.
Joined
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_adv">6.2.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_disadv">6.2.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc">6.3.
Table Per Class
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_adv">6.3.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_disadv">6.3.2.
Disadvantages
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_inher_together">6.4.
Putting it All Together
</a></span></dt></dl></div>
<a class="indexterm" name="d5e5862"></a>
<a class="indexterm" name="d5e5866"></a>
<a class="indexterm" name="d5e5869"></a>
<a class="indexterm" name="d5e5873"></a>
<p>
In the 1990's programmers coined the term <span class="emphasis"><em>impedance mismatch
</em></span> to describe the difficulties in bridging the object and relational
worlds. Perhaps no feature of object modeling highlights the impedance mismatch
better than inheritance. There is no natural, efficient way to represent an
inheritance relationship in a relational database.
</p>
<p>
<a class="indexterm" name="d5e5878"></a>
Luckily, JPA gives you a choice of inheritance strategies, making
the best of a bad situation. The base entity class defines the inheritance
strategy for the hierarchy with the <code class="classname">Inheritance</code>
annotation. <code class="classname">Inheritance</code> has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">InheritanceType strategy</code>: Enum value declaring the
inheritance strategy for the hierarchy. Defaults to <code class="literal">
InheritanceType.SINGLE_TABLE</code>. We detail each of the available
strategies below.
</p>
</li></ul></div>
<p>
The corresponding XML element is <code class="literal">inheritance</code>, which has a
single attribute:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">strategy</code>: One of <code class="literal">SINGLE_TABLE</code>, <code class="literal">
JOINED</code>, or <code class="literal">TABLE_PER_CLASS</code>.
</p>
</li></ul></div>
<p>
The following sections describe JPA's standard inheritance strategies.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA allows you to vary your inheritance strategy for each class, rather than
forcing a single strategy per inheritance hierarchy. See
<a class="xref" href="#ref_guide_mapping_jpa" title="7.&nbsp; Additional JPA Mappings">Section&nbsp;7, &#8220;
Additional JPA Mappings
&#8221;</a> in the Reference Guide for
details.
</p>
</div>
<div class="section" id="jpa_overview_mapping_inher_single"><div class="titlepage"><div><div><h3 class="title">6.1.&nbsp;
Single Table
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_adv">6.1.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_single_disadv">6.1.2.
Disadvantages
</a></span></dt></dl></div>
<a class="indexterm" name="d5e5904"></a>
<a class="indexterm" name="d5e5908"></a>
<p>
The <code class="literal">InheritanceType.SINGLE_TABLE</code> strategy maps all classes in
the hierarchy to the base class' table.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="177"><tr><td><img src="img/inher-superclass-table.png"></td></tr></table></div>
<p>
In our model, <code class="classname">Subscription</code> is mapped to the <code class="literal">
CNTRCT.SUB</code> table. <code class="classname"> LifetimeSubscription</code>, which
extends <code class="classname"> Subscription</code>, adds its field data to this table
as well.
</p>
<div class="example" id="jpa_overview_mapping_inher_singleex"><p class="title"><b>Example&nbsp;13.5.&nbsp;
Single Table Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
@Table(name="SUB", schema="CNTRCT")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Subscription {
...
}
@Entity(name="Lifetime")
public class LifetimeSubscription
extends Subscription {
...
}
</pre>
<p>
The same metadata expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.subcribe.Subscription"&gt;
&lt;table name="SUB" schema="CNTRCT"/&gt;
&lt;inheritance strategy="SINGLE_TABLE"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription"&gt;
...
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
<p>
Single table inheritance is the default strategy. Thus, we could omit the
<code class="literal">@Inheritance</code> annotation in the example above and get the same
result.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
<a class="indexterm" name="d5e5930"></a>
<a class="indexterm" name="d5e5933"></a>
Mapping subclass state to the superclass table is often called <span class="emphasis"><em>flat
</em></span> inheritance mapping.
</p>
</div>
<div class="section" id="jpa_overview_mapping_inher_single_adv"><div class="titlepage"><div><div><h4 class="title">6.1.1.&nbsp;
Advantages
</h4></div></div></div>
<a class="indexterm" name="d5e5939"></a>
<p>
Single table inheritance mapping is the fastest of all inheritance models, since
it never requires a join to retrieve a persistent instance from the database.
Similarly, persisting or updating a persistent instance requires only a single
<code class="literal">INSERT</code> or <code class="literal">UPDATE</code> statement. Finally,
relations to any class within a single table inheritance hierarchy are just as
efficient as relations to a base class.
</p>
</div>
<div class="section" id="jpa_overview_mapping_inher_single_disadv"><div class="titlepage"><div><div><h4 class="title">6.1.2.&nbsp;
Disadvantages
</h4></div></div></div>
<a class="indexterm" name="d5e5948"></a>
<p>
The larger the inheritance model gets, the "wider" the mapped table gets, in
that for every field in the entire inheritance hierarchy, a column must exist in
the mapped table. This may have undesirable consequence on the database size,
since a wide or deep inheritance hierarchy will result in tables with many
mostly-empty columns.
</p>
</div>
</div>
<div class="section" id="jpa_overview_mapping_inher_joined"><div class="titlepage"><div><div><h3 class="title">6.2.&nbsp;
Joined
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_adv">6.2.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_joined_disadv">6.2.2.
Disadvantages
</a></span></dt></dl></div>
<a class="indexterm" name="d5e5955"></a>
<a class="indexterm" name="d5e5959"></a>
<p>
The <code class="literal">InheritanceType.JOINED</code> strategy uses a different table
for each class in the hierarchy. Each table only includes state declared in its
class. Thus to load a subclass instance, the JPA implementation must
read from the subclass table as well as the table of each ancestor class, up to
the base entity class.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
<a class="indexterm" name="d5e5966"></a>
<a class="indexterm" name="d5e5969"></a>
Using joined subclass tables is also called <span class="emphasis"><em>vertical</em></span>
inheritance mapping.
</p>
</div>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="171"><tr><td><img src="img/jpa-inher-joined.png"></td></tr></table></div>
<p>
<code class="classname">PrimaryKeyJoinColumn</code> annotations tell the JPA
implementation how to join each subclass table record to the corresponding
record in its direct superclass table. In our model, the <code class="literal">LINE_ITEM.ID
</code> column joins to the <code class="literal">CONTRACT.ID</code> column. The
<code class="classname">PrimaryKeyJoinColumn</code> annotation has the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the subclass table column. When
there is a single identity field, defaults to that field's column name.
</p>
</li><li class="listitem">
<p>
<code class="literal">String referencedColumnName</code>: The name of the superclass
table column this subclass table column joins to. When there is a single
identity field, defaults to that field's column name.
</p>
</li><li class="listitem">
<p>
<code class="literal">String columnDefinition</code>: This property has the same meaning
as the <code class="literal">columnDefinition</code> property on the <code class="classname">Column
</code> annotation, described in
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a>.
</p>
</li></ul></div>
<p>
The XML equivalent is the <code class="literal">primary-key-join-column</code> element.
Its attributes mirror the annotation properties described above:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">referenced-column-name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">column-definition</code>
</p>
</li></ul></div>
<p>
The example below shows how we use <code class="literal">InheritanceTable.JOINED</code>
and a primary key join column to map our sample model according to the diagram
above. Note that a primary key join column is not strictly needed, because there
is only one identity column, and the subclass table column has the same name as
the superclass table column. In this situation, the defaults suffice. However,
we include the primary key join column for illustrative purposes.
</p>
<div class="example" id="jpa_overview_mapping_inher_joinedex"><p class="title"><b>Example&nbsp;13.6.&nbsp;
Joined Subclass Tables
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
@Table(schema="CNTRCT")
@Inheritance(strategy=InheritanceType.JOINED)
public class Contract
extends Document {
...
}
public class Subscription {
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
@PrimaryKeyJoinColumn(name="ID", referencedColumnName="ID")
public static class LineItem
extends Contract {
...
}
}
</pre>
<p>
The same metadata expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;table schema="CNTRCT"/&gt;
&lt;inheritance strategy="JOINED"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
&lt;primary-key-join-column name="ID" referenced-column-name="PK"/&gt;
...
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
<p>
When there are multiple identity columns, you must define multiple <code class="classname">
PrimaryKeyJoinColumn</code>s using the aptly-named <code class="classname">
PrimaryKeyJoinColumns</code> annotation. This annotation's value is an
array of <code class="classname"> PrimaryKeyJoinColumn</code> s. We could rewrite
<code class="classname">LineItem</code>'s mapping as:
</p>
<pre class="programlisting">
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
@PrimaryKeyJoinColumns({
@PrimaryKeyJoinColumn(name="ID", referencedColumnName="ID")
})
public static class LineItem
extends Contract {
...
}
</pre>
<p>
In XML, simply list as many <code class="literal"> primary-key-join-column</code> elements
as necessary.
</p>
<div class="section" id="jpa_overview_mapping_inher_joined_adv"><div class="titlepage"><div><div><h4 class="title">6.2.1.&nbsp;
Advantages
</h4></div></div></div>
<a class="indexterm" name="d5e6023"></a>
<p>
The joined strategy has the following advantages:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
<a class="indexterm" name="d5e6031"></a>
Using joined subclass tables results in the most <span class="emphasis"><em>normalized</em></span>
database schema, meaning the schema with the least spurious or redundant data.
</p>
</li><li class="listitem">
<p>
As more subclasses are added to the data model over time, the only schema
modification that needs to be made is the addition of corresponding subclass
tables in the database (rather than having to change the structure of existing
tables).
</p>
</li><li class="listitem">
<p>
Relations to a base class using this strategy can be loaded through standard
joins and can use standard foreign keys, as opposed to the machinations required
to load polymorphic relations to table-per-class base types, described below.
</p>
</li></ol></div>
</div>
<div class="section" id="jpa_overview_mapping_inher_joined_disadv"><div class="titlepage"><div><div><h4 class="title">6.2.2.&nbsp;
Disadvantages
</h4></div></div></div>
<a class="indexterm" name="d5e6040"></a>
<p>
Aside from certain uses of the table-per-class strategy described below, the
joined strategy is often the slowest of the inheritance models. Retrieving any
subclass requires one or more database joins, and storing subclasses requires
multiple <code class="literal">INSERT</code> or <code class="literal">UPDATE</code> statements. This
is only the case when persistence operations are performed on subclasses; if
most operations are performed on the least-derived persistent superclass, then
this mapping is very fast.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
When executing a select against a hierarchy that uses joined subclass table
inheritance, you must consider how to load subclass state.
<a class="xref" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">Section&nbsp;8, &#8220;
Eager Fetching
&#8221;</a> in the Reference Guide
describes OpenJPA's options for efficient data loading.
</p>
</div>
</div>
</div>
<div class="section" id="jpa_overview_mapping_inher_tpc"><div class="titlepage"><div><div><h3 class="title">6.3.&nbsp;
Table Per Class
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_adv">6.3.1.
Advantages
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_inher_tpc_disadv">6.3.2.
Disadvantages
</a></span></dt></dl></div>
<a class="indexterm" name="d5e6052"></a>
<a class="indexterm" name="d5e6056"></a>
<p>
Like the <code class="literal">JOINED</code> strategy, the <code class="literal">
InheritanceType.TABLE_PER_CLASS</code> strategy uses a different table for
each class in the hierarchy. Unlike the <code class="literal">JOINED</code> strategy,
however, each table includes all state for an instance of the corresponding
class. Thus to load a subclass instance, the JPA implementation must
only read from the subclass table; it does not need to join to superclass
tables.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="189"><tr><td><img src="img/inher-tpc.png"></td></tr></table></div>
<p>
Suppose that our sample model's <code class="classname">Magazine</code> class has a
subclass <code class="classname">Tabloid</code>. The classes are mapped using the
table-per-class strategy, as in the diagram above. In a table-per-class mapping,
<code class="classname"> Magazine</code>'s table <code class="literal">MAG</code> contains all
state declared in the base <code class="classname">Magazine</code> class. <code class="classname">
Tabloid</code> maps to a separate table, <code class="literal"> TABLOID</code>. This
table contains not only the state declared in the <code class="classname">Tabloid</code>
subclass, but all the base class state from <code class="classname">Magazine</code> as
well. Thus the <code class="literal">TABLOID</code> table would contain columns for
<code class="literal">isbn</code>, <code class="literal">title</code>, and other <code class="classname">
Magazine</code> fields. These columns would default to the names used in
<code class="classname">Magazine</code>'s mapping metadata.
<a class="xref" href="#jpa_overview_mapping_embed" title="8.3.&nbsp; Embedded Mapping">Section&nbsp;8.3, &#8220;
Embedded Mapping
&#8221;</a> will show you how to use
<code class="literal">AttributeOverride</code>s and <code class="literal">AssociationOverride</code>
s to override superclass field mappings.
</p>
<div class="example" id="jpa_overview_mapping_inher_tpcex"><p class="title"><b>Example&nbsp;13.7.&nbsp;
Table Per Class Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
@Table(name="MAG")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Magazine {
...
}
@Entity
@Table(name="TABLOID")
public class Tabloid
extends Magazine {
...
}
</pre>
<p>
And the same classes in XML:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;inheritance strategy="TABLE_PER_CLASS"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.Tabloid"&gt;
&lt;table name="TABLOID"/&gt;
...
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
<div class="section" id="jpa_overview_mapping_inher_tpc_adv"><div class="titlepage"><div><div><h4 class="title">6.3.1.&nbsp;
Advantages
</h4></div></div></div>
<a class="indexterm" name="d5e6091"></a>
<p>
The table-per-class strategy is very efficient when operating on instances of a
known class. Under these conditions, the strategy never requires joining to
superclass or subclass tables. Reads, joins, inserts, updates, and deletes are
all efficient in the absence of polymorphic behavior. Also, as in the joined
strategy, adding additional classes to the hierarchy does not require modifying
existing class tables.
</p>
</div>
<div class="section" id="jpa_overview_mapping_inher_tpc_disadv"><div class="titlepage"><div><div><h4 class="title">6.3.2.&nbsp;
Disadvantages
</h4></div></div></div>
<a class="indexterm" name="d5e6098"></a>
<p>
Polymorphic relations to non-leaf classes in a table-per-class hierarchy have
many limitations. When the concrete subclass is not known, the related object
could be in any of the subclass tables, making joins through the relation
impossible. This ambiguity also affects identity lookups and queries; these
operations require multiple SQL <code class="literal">SELECT</code>s (one for each
possible subclass), or a complex <code class="literal">UNION</code>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
<a class="xref" href="#ref_guide_mapping_limits_tpc" title="8.1.&nbsp; Table Per Class">Section&nbsp;8.1, &#8220;
Table Per Class
&#8221;</a> in the Reference Guide
describes the limitations OpenJPA places on table-per-class mapping.
</p>
</div>
</div>
</div>
<div class="section" id="jpa_overview_mapping_inher_together"><div class="titlepage"><div><div><h3 class="title">6.4.&nbsp;
Putting it All Together
</h3></div></div></div>
<p>
Now that we have covered JPA's inheritance strategies, we can update our mapping
document with inheritance information. Here is the complete model:
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="341"><tr><td><img src="img/jpa-inher-all.png"></td></tr></table></div>
<p>
And here is the corresponding mapping metadata:
</p>
<div class="example" id="jpa_overview_mapping_inher_togetherex"><p class="title"><b>Example&nbsp;13.8.&nbsp;
Inheritance Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
@Table(name="MAG")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
...
public static class MagazineId {
...
}
}
@Entity
@Table(name="ART", uniqueConstraints=@Unique(columnNames="TITLE"))
@SequenceGenerator(name="ArticleSeq", sequenceName="ART_SEQ")
public class Article {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ArticleSeq")
private long id;
...
}
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
@Column(name="CID")
@Id private long id;
...
}
@Entity
@Table(name="AUTH")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="AuthorGen")
@TableGenerator(name="AuthorGen", table="AUTH_GEN", pkColumnName="PK",
valueColumnName="AID")
@Column(name="AID", columnDefinition="INTEGER64")
private long id;
...
}
@Embeddable
public class Address {
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
...
}
@Entity
@Table(schema="CNTRCT")
@Inheritance(strategy=InheritanceType.JOINED)
public class Contract
extends Document {
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Subscription {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
@PrimaryKeyJoinColumn(name="ID", referencedColumnName="ID")
public static class LineItem
extends Contract {
...
}
}
@Entity(name="Lifetime")
public class LifetimeSubscription
extends Subscription {
...
}
@Entity(name="Trial")
public class TrialSubscription
extends Subscription {
...
}
</pre>
<p>
The same metadata expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"&gt;
&lt;mapped-superclass class="org.mag.subscribe.Document"&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;id-class="org.mag.Magazine.MagazineId"/&gt;
&lt;attributes&gt;
&lt;id name="isbn"&gt;
&lt;column length="9"/&gt;
&lt;/id&gt;
&lt;id name="title"/&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"&gt;
&lt;unique-constraint&gt;
&lt;column-name&gt;TITLE&lt;/column-name&gt;
&lt;/unique-constraint&gt;
&lt;/table&gt;
&lt;sequence-generator name="ArticleSeq" sequence-name="ART_SEQ"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="SEQUENCE" generator="ArticleSeq"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="CID"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="AID" column-definition="INTEGER64"/&gt;
&lt;generated-value strategy="TABLE" generator="AuthorGen"/&gt;
&lt;table-generator name="AuthorGen" table="AUTH_GEN"
pk-column-name="PK" value-column-name="AID"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;table schema="CNTRCT"/&gt;
&lt;inheritance strategy="JOINED"/&gt;
&lt;attributes&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Subscription"&gt;
&lt;table name="SUB" schema="CNTRCT"/&gt;
&lt;inheritance strategy="SINGLE_TABLE"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
&lt;primary-key-join-column name="ID" referenced-column-name="PK"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription" name="Lifetime"&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.TrialSubscription" name="Trial"&gt;
...
&lt;/entity&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="jpa_overview_mapping_discrim"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
Discriminator
</h2></div></div></div>
<a class="indexterm" name="d5e6122"></a>
<a class="indexterm" name="d5e6124"></a>
<a class="indexterm" name="d5e6128"></a>
<p>
The <a class="link" href="#jpa_overview_mapping_inher_single" title="6.1.&nbsp; Single Table">single table</a>
inheritance strategy results in a single table containing records for two or
more different classes in an inheritance hierarchy. Similarly, using the
<a class="link" href="#jpa_overview_mapping_inher_joined" title="6.2.&nbsp; Joined"> joined</a> strategy
results in the superclass table holding records for superclass instances as well
as for the superclass state of subclass instances. When selecting data, JPA
needs a way to differentiate a row representing an object of one class from a
row representing an object of another. That is the job of the <span class="emphasis"><em>
discriminator</em></span> column.
</p>
<p>
The discriminator column is always in the table of the base entity. It holds a
different value for records of each class, allowing the JPA runtime
to determine what class of object each row represents.
</p>
<p>
The <code class="classname">DiscriminatorColumn</code> annotation represents a
discriminator column. It has these properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The column name. Defaults to <code class="literal">DTYPE
</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">length</code>: For string discriminator values, the length of the
column. Defaults to 31.
</p>
</li><li class="listitem">
<p>
<code class="literal">String columnDefinition</code>: This property has the same meaning
as the <code class="literal">columnDefinition</code> property on the <code class="classname">Column
</code> annotation, described in
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">DiscriminatorType discriminatorType</code>: Enum value declaring
the discriminator strategy of the hierarchy.
</p>
</li></ul></div>
<p>
The corresponding XML element is <code class="literal"> discriminator-column</code>. Its
attributes mirror the annotation properties above:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">length</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">column-definition</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">discriminator-type</code>: One of <code class="literal">STRING</code>,
<code class="literal">CHAR</code>, or <code class="literal">INTEGER</code>.
</p>
</li></ul></div>
<p>
The <code class="classname">DiscriminatorValue</code> annotation specifies the
discriminator value for each class. Though this annotation's value is always a
string, the implementation will parse it according to the <code class="classname">
DiscriminatorColumn</code>'s <code class="literal">discriminatorType</code> property
above. The type defaults to <code class="literal">DiscriminatorType.STRING</code>, but
may be <code class="literal"> DiscriminatorType.CHAR</code> or <code class="literal">
DiscriminatorType.INTEGER</code>. If you do not specify a <code class="classname">
DiscriminatorValue</code>, the provider will choose an appropriate
default.
</p>
<p>
The corresponding XML element is <code class="literal">discriminator-value</code>. The
text within this element is parsed as the discriminator value.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA assumes your model employs a discriminator column if any of the
following are true:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
The base entity explicitly declares an inheritance type of <code class="literal">
SINGLE_TABLE</code>.
</p>
</li><li class="listitem">
<p>
The base entity sets a discriminator value.
</p>
</li><li class="listitem">
<p>
The base entity declares a discriminator column.
</p>
</li></ol></div>
<p>
Only <code class="literal">SINGLE_TABLE</code> inheritance hierarchies require a
discriminator column and values. <code class="literal"> JOINED</code> hierarchies can use
a discriminator to make some operations more efficient, but do not require one.
<code class="literal">TABLE_PER_CLASS</code> hierarchies have no use for a discriminator.
</p>
<p>
OpenJPA defines additional discriminator strategies; see
<a class="xref" href="#ref_guide_mapping_jpa" title="7.&nbsp; Additional JPA Mappings">Section&nbsp;7, &#8220;
Additional JPA Mappings
&#8221;</a> in the Reference Guide for
details. OpenJPA also supports final entity classes. OpenJPA does not use a
discriminator on final classes.
</p>
</div>
<p>
We can now translate our newfound knowledge of JPA discriminators into concrete
JPA mappings. We first extend our diagram with discriminator columns:
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="341"><tr><td><img src="img/jpa-discrim-all.png"></td></tr></table></div>
<p>
Next, we present the updated mapping document. Notice that in this version, we
have removed explicit inheritance annotations when the defaults sufficed. Also,
notice that entities using the default <code class="literal">DTYPE</code> discriminator
column mapping do not need an explicit <code class="classname">DiscriminatorColumn
</code> annotation.
</p>
<div class="example" id="jpa_overview_mapping_discrimex"><p class="title"><b>Example&nbsp;13.9.&nbsp;
Discriminator Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
@Table(name="MAG")
@DiscriminatorValue("Mag")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
...
public static class MagazineId {
...
}
}
@Entity
@Table(name="ART", uniqueConstraints=@Unique(columnNames="TITLE"))
@SequenceGenerator(name="ArticleSeq", sequenceName="ART_SEQ")
public class Article {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ArticleSeq")
private long id;
...
}
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
@Column(name="CID")
@Id private long id;
...
}
@Entity
@Table(name="AUTH")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="AuthorGen")
@TableGenerator(name="AuthorGen", table="AUTH_GEN", pkColumnName="PK",
valueColumnName="AID")
@Column(name="AID", columnDefinition="INTEGER64")
private long id;
...
}
@Embeddable
public class Address {
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
...
}
@Entity
@Table(schema="CNTRCT")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="CTYPE")
public class Contract
extends Document {
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
@DiscriminatorColumn(name="KIND", discriminatorType=DiscriminatorType.INTEGER)
@DiscriminatorValue("1")
public class Subscription {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
...
}
}
@Entity(name="Lifetime")
@DiscriminatorValue("2")
public class LifetimeSubscription
extends Subscription {
...
}
@Entity(name="Trial")
@DiscriminatorValue("3")
public class TrialSubscription
extends Subscription {
...
}
</pre>
<p>
The same metadata expressed in XML:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"&gt;
&lt;mapped-superclass class="org.mag.subscribe.Document"&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;id-class="org.mag.Magazine.MagazineId"/&gt;
&lt;discriminator-value&gt;Mag&lt;/discriminator-value&gt;
&lt;attributes&gt;
&lt;id name="isbn"&gt;
&lt;column length="9"/&gt;
&lt;/id&gt;
&lt;id name="title"/&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"&gt;
&lt;unique-constraint&gt;
&lt;column-name&gt;TITLE&lt;/column-name&gt;
&lt;/unique-constraint&gt;
&lt;/table&gt;
&lt;sequence-generator name="ArticleSeq" sequence-name="ART_SEQ"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="SEQUENCE" generator="ArticleSeq"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="CID"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="AID" column-definition="INTEGER64"/&gt;
&lt;generated-value strategy="TABLE" generator="AuthorGen"/&gt;
&lt;table-generator name="AuthorGen" table="AUTH_GEN"
pk-column-name="PK" value-column-name="AID"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;table schema="CNTRCT"/&gt;
&lt;inheritance strategy="JOINED"/&gt;
&lt;discriminator-column name="CTYPE"/&gt;
&lt;attributes&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Subscription"&gt;
&lt;table name="SUB" schema="CNTRCT"/&gt;
&lt;inheritance strategy="SINGLE_TABLE"/&gt;
&lt;discriminator-value&gt;1&lt;/discriminator-value&gt;
&lt;discriminator-column name="KIND" discriminator-type="INTEGER"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
&lt;primary-key-join-column name="ID" referenced-column-name="PK"/&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription" name="Lifetime"&gt;
&lt;discriminator-value&gt;2&lt;/discriminator-value&gt;
...
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.TrialSubscription" name="Trial"&gt;
&lt;discriminator-value&gt;3&lt;/discriminator-value&gt;
...
&lt;/entity&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_mapping_field"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;
Field Mapping
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_basic">8.1.
Basic Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_overview_mapping_lob">8.1.1.
LOBs
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_enum">8.1.2.
Enumerated
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_temporal">8.1.3.
Temporal Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_basic_example">8.1.4.
The Updated Mappings
</a></span></dt></dl></dd><dt><span class="section"><a href="#jpa_overview_mapping_secondary">8.2.
Secondary Tables
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_embed">8.3.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_rel">8.4.
Direct Relations
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_assoccoll">8.5.
Join Table
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_bidi">8.6.
Bidirectional Mapping
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_map">8.7.
Map Mapping
</a></span></dt></dl></div>
<a class="indexterm" name="d5e6214"></a>
<a class="indexterm" name="d5e6218"></a>
<p>
The following sections enumerate the myriad of field mappings JPA
supports. JPA augments the persistence metadata covered in
<a class="xref" href="#jpa_overview_meta" title="Chapter&nbsp;5.&nbsp; Metadata">Chapter&nbsp;5, <i>
Metadata
</i></a> with many new object-relational
annotations. As we explore the library of standard mappings, we introduce each
of these enhancements in context.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA supports many additional field types, and allows you to create custom
mappings for unsupported field types or database schemas. See the Reference
Guide's <a class="xref" href="#ref_guide_mapping" title="Chapter&nbsp;7.&nbsp; Mapping">Chapter&nbsp;7, <i>
Mapping
</i></a> for complete coverage of
OpenJPA's mapping capabilities.
</p>
</div>
<div class="section" id="jpa_overview_mapping_basic"><div class="titlepage"><div><div><h3 class="title">8.1.&nbsp;
Basic Mapping
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_overview_mapping_lob">8.1.1.
LOBs
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_enum">8.1.2.
Enumerated
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_temporal">8.1.3.
Temporal Types
</a></span></dt><dt><span class="section"><a href="#jpa_overview_mapping_basic_example">8.1.4.
The Updated Mappings
</a></span></dt></dl></div>
<a class="indexterm" name="d5e6228"></a>
<a class="indexterm" name="d5e6232"></a>
<p>
A <span class="emphasis"><em>basic</em></span> field mapping stores the field value directly into
a database column. The following field metadata types use basic mapping. These
types were defined in <a class="xref" href="#jpa_overview_meta_field" title="2.&nbsp; Field and Property Metadata">Section&nbsp;2, &#8220;
Field and Property Metadata
&#8221;</a>.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="link" href="#jpa_overview_meta_id" title="2.3.&nbsp; Id"><code class="classname">Id</code></a> fields.
</p>
</li><li class="listitem">
<p>
<a class="link" href="#jpa_overview_meta_version" title="2.6.&nbsp; Version"><code class="classname"> Version</code></a>
fields.
</p>
</li><li class="listitem">
<p>
<a class="link" href="#jpa_overview_meta_basic" title="2.7.&nbsp; Basic"><code class="classname">Basic</code></a>
fields.
</p>
</li></ul></div>
<p>
In fact, you have already seen examples of basic field mappings in this chapter
- the mapping of all identity fields in
<a class="xref" href="#jpa_overview_mapping_identityex" title="Example&nbsp;13.3.&nbsp; Identity Mapping">Example&nbsp;13.3, &#8220;
Identity Mapping
&#8221;</a>. As you saw in that
section, to write a basic field mapping you use the <code class="classname">Column
</code> annotation to describe the column the field value is stored in. We
discussed the <code class="classname">Column</code> annotation in
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a>. Recall that the name of
the column defaults to the field name, and the type of the column defaults to an
appropriate type for the field type. These defaults allow you to sometimes omit
the annotation altogether.
</p>
<div class="section" id="jpa_overview_mapping_lob"><div class="titlepage"><div><div><h4 class="title">8.1.1.&nbsp;
LOBs
</h4></div></div></div>
<a class="indexterm" name="d5e6258"></a>
<a class="indexterm" name="d5e6260"></a>
<a class="indexterm" name="d5e6263"></a>
<p>
Adding the <code class="classname">Lob</code> marker annotation to a basic field signals
that the data is to be stored as a LOB (Large OBject). If the field holds string
or character data, it will map to a <code class="literal">CLOB</code> (Character Large
OBject) database column. If the field holds any other data type, it will be
stored as binary data in a <code class="literal">BLOB</code> (Binary Large OBject) column.
The implementation will serialize the Java value if needed.
</p>
<p>
The equivalent XML element is <code class="literal">lob</code>, which has no children or
attributes.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA also supports LOB streaming. See <a class="xref" href="#ref_guide_streamsupport" title="7.11.&nbsp; LOB Streaming">Section&nbsp;7.11, &#8220;
LOB Streaming
&#8221;</a> in
the Reference Guide for details.
</p>
</div>
</div>
<div class="section" id="jpa_overview_mapping_enum"><div class="titlepage"><div><div><h4 class="title">8.1.2.&nbsp;
Enumerated
</h4></div></div></div>
<a class="indexterm" name="d5e6277"></a>
<a class="indexterm" name="d5e6279"></a>
<a class="indexterm" name="d5e6282"></a>
<p>
You can apply the <code class="classname">Enumerated</code> annotation to your
<code class="classname">Enum</code> fields to control how they map to the database. The
<code class="classname">Enumerated</code> annotation's value one of the following
constants from the <code class="classname">EnumType</code> enum:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">EnumType.ORDINAL</code>: The default. The persistence
implementation places the ordinal value of the enum in a numeric column. This is
an efficient mapping, but may break if you rearrange the Java enum declaration.
</p>
</li><li class="listitem">
<p>
<code class="literal">EnumType.STRING</code>: Store the name of the enum value rather
than the ordinal. This mapping uses a <code class="literal">VARCHAR</code> column rather
than a numeric one.
</p>
</li></ul></div>
<p>
The <code class="classname">Enumerated</code> annotation is optional. Any un-annotated
enumeration field defaults to <code class="literal">ORDINAL</code> mapping.
</p>
<p>
The corresponding XML element is <code class="literal">enumerated</code>. Its embedded
text must be one of <code class="literal">STRING</code> or <code class="literal">ORIDINAL</code>.
</p>
</div>
<div class="section" id="jpa_overview_mapping_temporal"><div class="titlepage"><div><div><h4 class="title">8.1.3.&nbsp;
Temporal Types
</h4></div></div></div>
<a class="indexterm" name="d5e6307"></a>
<a class="indexterm" name="d5e6310"></a>
<p>
The <code class="classname">Temporal</code> annotation determines how the implementation
handles your basic <code class="classname"> java.util.Date</code> and <code class="classname">
java.util.Calendar</code> fields at the JDBC level. The <code class="classname">
Temporal</code> annotation's value is a constant from the <code class="classname">
TemporalType</code> enum. Available values are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">TemporalType.TIMESTAMP</code>: The default. Use JDBC's timestamp
APIs to manipulate the column data.
</p>
</li><li class="listitem">
<p>
<code class="literal">TemporalType.DATE</code>: Use JDBC's SQL date APIs to manipulate
the column data.
</p>
</li><li class="listitem">
<p>
<code class="literal">TemporalType.TIME</code>: Use JDBC's time APIs to manipulate the
column data.
</p>
</li></ul></div>
<p>
If the <code class="classname">Temporal</code> annotation is omitted, the implementation
will treat the data as a timestamp.
</p>
<p>
The corresponding XML element is <code class="literal">temporal</code>, whose text value
must be one of: <code class="literal">TIME</code>, <code class="literal">DATE</code>, or <code class="literal">
TIMESTAMP</code>.
</p>
</div>
<div class="section" id="jpa_overview_mapping_basic_example"><div class="titlepage"><div><div><h4 class="title">8.1.4.&nbsp;
The Updated Mappings
</h4></div></div></div>
<p>
Below we present an updated diagram of our model and its associated database
schema, followed by the corresponding mapping metadata. Note that the mapping
metadata relies on defaults where possible. Also note that as a mapped
superclass, <code class="classname">Document</code> can define mappings that will
automatically transfer to its subclass' tables. In
<a class="xref" href="#jpa_overview_mapping_embed" title="8.3.&nbsp; Embedded Mapping">Section&nbsp;8.3, &#8220;
Embedded Mapping
&#8221;</a>, you will see how a subclass
can override its mapped superclass' mappings.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="387"><tr><td><img src="img/jpa-basic-field.png"></td></tr></table></div>
<div class="example" id="jpa_overview_mapping_basicex"><p class="title"><b>Example&nbsp;13.10.&nbsp;
Basic Field Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
@Table(name="MAG")
@DiscriminatorValue("Mag")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
@Column(name="VERS")
@Version private int version;
private String name;
private double price;
@Column(name="COPIES")
private int copiesSold;
...
public static class MagazineId {
...
}
}
@Entity
@Table(name="ART", uniqueConstraints=@Unique(columnNames="TITLE"))
@SequenceGenerator(name="ArticleSeq", sequenceName="ART_SEQ")
public class Article {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ArticleSeq")
private long id;
@Column(name="VERS")
@Version private int version;
private String title;
private byte[] content;
...
}
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
@Column(name="CID")
@Id private long id;
@Column(name="VERS")
@Version private int version;
private String name;
@Column(name="REV")
private double revenue;
...
}
@Entity
@Table(name="AUTH")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="AuthorGen")
@TableGenerator(name="AuthorGen", table="AUTH_GEN", pkColumnName="PK",
valueColumnName="AID")
@Column(name="AID", columnDefinition="INTEGER64")
private long id;
@Column(name="VERS")
@Version private int version;
@Column(name="FNAME")
private String firstName;
@Column(name="LNAME")
private String lastName;
...
}
@Embeddable
public class Address {
...
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="VERS")
@Version private int version;
...
}
@Entity
@Table(schema="CNTRCT")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="CTYPE")
public class Contract
extends Document {
@Lob
private String terms;
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
@DiscriminatorColumn(name="KIND", discriminatorType=DiscriminatorType.INTEGER)
@DiscriminatorValue("1")
public class Subscription {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="VERS")
@Version private int version;
@Column(name="START")
private Date startDate;
@Column(name="PAY")
private double payment;
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
@Column(name="COMM")
private String comments;
private double price;
private long num;
...
}
}
@Entity(name="Lifetime")
@DiscriminatorValue("2")
public class LifetimeSubscription
extends Subscription {
@Basic(fetch=FetchType.LAZY)
@Column(name="ELITE")
private boolean getEliteClub() { ... }
public void setEliteClub(boolean elite) { ... }
...
}
@Entity(name="Trial")
@DiscriminatorValue("3")
public class TrialSubscription
extends Subscription {
@Column(name="END")
public Date getEndDate() { ... }
public void setEndDate(Date end) { ... }
...
}
</pre>
<p>
The same metadata expressed in XML:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"&gt;
&lt;mapped-superclass class="org.mag.subscribe.Document"&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
...
&lt;/attributes&gt;
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;id-class="org.mag.Magazine.MagazineId"/&gt;
&lt;discriminator-value&gt;Mag&lt;/discriminator-value&gt;
&lt;attributes&gt;
&lt;id name="isbn"&gt;
&lt;column length="9"/&gt;
&lt;/id&gt;
&lt;id name="title"/&gt;
&lt;basic name="name"/&gt;
&lt;basic name="price"/&gt;
&lt;basic name="copiesSold"&gt;
&lt;column name="COPIES"/&gt;
&lt;/basic&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"&gt;
&lt;unique-constraint&gt;
&lt;column-name&gt;TITLE&lt;/column-name&gt;
&lt;/unique-constraint&gt;
&lt;/table&gt;
&lt;sequence-generator name="ArticleSeq", sequenceName="ART_SEQ"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="SEQUENCE" generator="ArticleSeq"/&gt;
&lt;/id&gt;
&lt;basic name="title"/&gt;
&lt;basic name="content"/&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="CID"/&gt;
&lt;/id&gt;
&lt;basic name="name"/&gt;
&lt;basic name="revenue"&gt;
&lt;column name="REV"/&gt;
&lt;/basic&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="AID" column-definition="INTEGER64"/&gt;
&lt;generated-value strategy="TABLE" generator="AuthorGen"/&gt;
&lt;table-generator name="AuthorGen" table="AUTH_GEN"
pk-column-name="PK" value-column-name="AID"/&gt;
&lt;/id&gt;
&lt;basic name="firstName"&gt;
&lt;column name="FNAME"/&gt;
&lt;/basic&gt;
&lt;basic name="lastName"&gt;
&lt;column name="LNAME"/&gt;
&lt;/basic&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;table schema="CNTRCT"/&gt;
&lt;inheritance strategy="JOINED"/&gt;
&lt;discriminator-column name="CTYPE"/&gt;
&lt;attributes&gt;
&lt;basic name="terms"&gt;
&lt;lob/&gt;
&lt;/basic&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Subscription"&gt;
&lt;table name="SUB" schema="CNTRCT"/&gt;
&lt;inheritance strategy="SINGLE_TABLE"/&gt;
&lt;discriminator-value&gt;1&lt;/discriminator-value&gt;
&lt;discriminator-column name="KIND" discriminator-type="INTEGER"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
&lt;basic name="payment"&gt;
&lt;column name="PAY"/&gt;
&lt;/basic&gt;
&lt;basic name="startDate"&gt;
&lt;column name="START"/&gt;
&lt;/basic&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
&lt;primary-key-join-column name="ID" referenced-column-name="PK"/&gt;
&lt;attributes&gt;
&lt;basic name="comments"&gt;
&lt;column name="COMM"/&gt;
&lt;/basic&gt;
&lt;basic name="price"/&gt;
&lt;basic name="num"/&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription" name="Lifetime"&gt;
&lt;discriminator-value&gt;2&lt;/discriminator-value&gt;
&lt;attributes&gt;
&lt;basic name="eliteClub" fetch="LAZY"&gt;
&lt;column name="ELITE"/&gt;
&lt;/basic&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.TrialSubscription" name="Trial"&gt;
&lt;discriminator-value&gt;3&lt;/discriminator-value&gt;
&lt;attributes&gt;
&lt;basic name="endDate"&gt;
&lt;column name="END"/&gt;
&lt;/basic&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="jpa_overview_mapping_secondary"><div class="titlepage"><div><div><h3 class="title">8.2.&nbsp;
Secondary Tables
</h3></div></div></div>
<a class="indexterm" name="d5e6351"></a>
<a class="indexterm" name="d5e6355"></a>
<p>
Sometimes a logical record is spread over multiple database tables. JPA
calls a class' declared table the <span class="emphasis"><em>primary</em></span>
table, and calls other tables that make up a logical record <span class="emphasis"><em>secondary
</em></span> tables. You can map any persistent field to a secondary table. Just
write the standard field mapping, then perform these two additional steps:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
Set the <code class="literal">table</code> attribute of each of the field's columns or
join columns to the name of the secondary table.
</p>
</li><li class="listitem">
<p>
Define the secondary table on the entity class declaration.
</p>
</li></ol></div>
<p>
You define secondary tables with the <code class="classname">SecondaryTable</code>
annotation. This annotation has all the properties of the <code class="classname">Table
</code> annotation covered in <a class="xref" href="#jpa_overview_mapping_table" title="1.&nbsp; Table">Section&nbsp;1, &#8220;
Table
&#8221;</a>
, plus a <code class="literal"> pkJoinColumns</code> property.
</p>
<p>
The <code class="literal">pkJoinColumns</code> property is an array of <code class="classname">
PrimaryKeyJoinColumn</code>s dictating how to join secondary table records
to their owning primary table records. Each <code class="classname">PrimaryKeyJoinColumn
</code> joins a secondary table column to a primary key column in the
primary table. See <a class="xref" href="#jpa_overview_mapping_inher_joined" title="6.2.&nbsp; Joined">Section&nbsp;6.2, &#8220;
Joined
&#8221;</a>
above for coverage of <code class="classname">PrimaryKeyJoinColumn</code>'s properties.
</p>
<p>
The corresponding XML element is <code class="literal">secondary-table</code>. This
element has all the attributes of the <code class="literal">table</code> element, but also
accepts nested <code class="literal">primary-key-join-column</code> elements.
</p>
<p>
In the following example, we move the <code class="literal">Article.content</code> field
we mapped in <a class="xref" href="#jpa_overview_mapping_basic" title="8.1.&nbsp; Basic Mapping">Section&nbsp;8.1, &#8220;
Basic Mapping
&#8221;</a> into a joined
secondary table, like so:
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="189"><tr><td><img src="img/secondary-table.png"></td></tr></table></div>
<div class="example" id="jpa_overview_mapping_secondaryex"><p class="title"><b>Example&nbsp;13.11.&nbsp;
Secondary Table Field Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@Table(name="ART")
@SecondaryTable(name="ART_DATA",
pkJoinColumns=@PrimaryKeyJoinColumn(name="ART_ID", referencedColumnName="ID"))
public class Article {
@Id private long id;
@Column(table="ART_DATA")
private byte[] content;
...
}
</pre>
<p>
And in XML:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"/&gt;
&lt;secondary-table name="ART_DATA"&gt;
&lt;primary-key-join-column name="ART_ID" referenced-column-name="ID"/&gt;
&lt;/secondary-table&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
&lt;basic name="content"&gt;
&lt;column table="ART_DATA"/&gt;
&lt;/basic&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_mapping_embed"><div class="titlepage"><div><div><h3 class="title">8.3.&nbsp;
Embedded Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e6395"></a>
<a class="indexterm" name="d5e6399"></a>
<p>
<a class="xref" href="#jpa_overview_meta" title="Chapter&nbsp;5.&nbsp; Metadata">Chapter&nbsp;5, <i>
Metadata
</i></a> describes JPA's concept of <span class="emphasis"><em>
embeddable</em></span> objects. The field values of embedded objects are stored
as part of the owning record, rather than as a separate database record. Thus,
instead of mapping a relation to an embeddable object as a foreign key, you map
all the fields of the embeddable instance to columns in the owning field's
table.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="309"><tr><td><img src="img/jpa-embedded.png"></td></tr></table></div>
<p>
JPA defaults the embedded column names and descriptions to those of
the embeddable class' field mappings. The <code class="classname"> AttributeOverride
</code> annotation overrides a basic embedded mapping. This annotation has
the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the embedded class' field being
mapped to this class' table.
</p>
</li><li class="listitem">
<p>
<code class="literal">Column column</code>: The column defining the mapping of the
embedded class' field to this class' table.
</p>
</li></ul></div>
<p>
The corresponding XML element is <code class="literal"> attribute-override</code>. It has
a single <code class="literal">name</code> attribute to name the field being overridden,
and a single <code class="literal">column</code> child element.
</p>
<p>
To declare multiple overrides, use the <code class="classname">AttributeOverrides</code>
annotation, whose value is an array of <code class="classname">AttributeOverride</code>
s. In XML, simply list multiple <code class="literal">attribute-override</code> elements
in succession.
</p>
<p>
To override a many to one or one to one relationship, use the <code class="classname">
AssociationOverride</code> annotation in place of <code class="classname">
AttributeOverride</code>. <code class="classname"> AssociationOverride</code> has
the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the embedded class' field being
mapped to this class' table.
</p>
</li><li class="listitem">
<p>
<code class="literal">JoinColumn[] joinColumns</code>: The foreign key columns joining to
the related record.
</p>
</li></ul></div>
<p>
The corresponding XML element is <code class="literal"> association-override</code>. It
has a single <code class="literal">name</code> attribute to name the field being
overridden, and one or more <code class="literal">join-column</code> child elements.
</p>
<p>
To declare multiple relation overrides, use the <code class="classname"> AssociationOverrides
</code> annotation, whose value is an array of <code class="classname">
AssociationOverride</code> s. In XML, simply list multiple <code class="literal">
association-override</code> elements in succession.
</p>
<div class="example" id="jpa_overview_mapping_embedex"><p class="title"><b>Example&nbsp;13.12.&nbsp;
Embedded Field Mapping
</b></p><div class="example-contents">
<p>
In this example, <code class="classname">Company</code> overrides the default mapping of
<code class="literal">Address.street</code> and <code class="literal">Address.city</code>. All
other embedded mappings are taken from the <code class="classname">Address</code>
embeddable class.
</p>
<pre class="programlisting">
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
@Embedded
@AttributeOverrides({
@AttributeOverride(name="street", column=@Column(name="STRT")),
@AttributeOverride(name="city", column=@Column(name="ACITY"))
})
private Address address;
...
}
@Entity
@Table(name="AUTH")
public class Author {
// use all defaults from Address class mappings
private Address address;
...
}
@Embeddable
public class Address {
private String street;
private String city;
@Column(columnDefinition="CHAR(2)")
private String state;
private String zip;
}
</pre>
<p>
The same metadata expressed in XML:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
&lt;attributes&gt;
...
&lt;embedded name="address"&gt;
&lt;attribute-override name="street"&gt;
&lt;column name="STRT"/&gt;
&lt;/attribute-override&gt;
&lt;attribute-override name="city"&gt;
&lt;column name="ACITY"/&gt;
&lt;/attribute-override&gt;
&lt;/embedded&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
&lt;attributes&gt;
&lt;embedded name="address"&gt;
&lt;!-- use all defaults from Address --&gt;
&lt;/embedded&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;embeddable class="org.mag.pub.Address"&gt;
&lt;attributes&gt;
&lt;basic name="street"/&gt;
&lt;basic name="city"/&gt;
&lt;basic name="state"&gt;
&lt;column column-definition="CHAR(2)"/&gt;
&lt;/basic&gt;
&lt;basic name="zip"/&gt;
&lt;/attributes&gt;
&lt;/embeddable&gt;
</pre>
</div></div><br class="example-break">
<p>
You can also use attribute overrides on an entity class to override mappings
defined by its mapped superclass or table-per-class superclass. The example
below re-maps the <code class="literal">Document.version</code> field to the <code class="classname">
Contract</code> table's <code class="literal">CVERSION</code> column.
</p>
<div class="example" id="jpa_overview_mapping_joined_overex"><p class="title"><b>Example&nbsp;13.13.&nbsp;
Mapping Mapped Superclass Field
</b></p><div class="example-contents">
<pre class="programlisting">
@MappedSuperclass
public abstract class Document {
@Column(name="VERS")
@Version private int version;
...
}
@Entity
@Table(schema="CNTRCT")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="CTYPE")
@AttributeOverride(name="version", column=@Column(name="CVERSION"))
public class Contract
extends Document {
...
}
</pre>
<p>
The same metadata expressed in XML form:
</p>
<pre class="programlisting">
&lt;mapped-superclass class="org.mag.subcribe.Document"&gt;
&lt;attributes&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"&gt;
&lt;/version&gt;
...
&lt;/attributes&gt;
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;table schema="CNTRCT"/&gt;
&lt;inheritance strategy="JOINED"/&gt;
&lt;discriminator-column name="CTYPE"/&gt;
&lt;attribute-override name="version"&gt;
&lt;column name="CVERSION"/&gt;
&lt;/attribute-override&gt;
&lt;attributes&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_mapping_rel"><div class="titlepage"><div><div><h3 class="title">8.4.&nbsp;
Direct Relations
</h3></div></div></div>
<a class="indexterm" name="d5e6465"></a>
<a class="indexterm" name="d5e6469"></a>
<a class="indexterm" name="d5e6472"></a>
<a class="indexterm" name="d5e6475"></a>
<p>
A direct relation is a non-embedded persistent field that holds a reference to
another entity. <a class="link" href="#jpa_overview_meta_manytoone" title="2.9.&nbsp; Many To One">many to one</a>
and <a class="link" href="#jpa_overview_meta_onetoone" title="2.11.&nbsp; One To One">one to one</a> metadata field
types are mapped as direct relations. Our model has three direct relations:
<code class="classname">Magazine</code>'s <code class="literal">publisher</code> field is a direct
relation to a <code class="classname">Company</code>, <code class="classname">Magazine</code>'s
<code class="literal">coverArticle</code> field is a direct relation to <code class="classname">
Article</code>, and the <code class="literal">LineItem.magazine</code> field is a
direct relation to a <code class="classname">Magazine</code>. Direct relations are
represented in the database by foreign key columns:
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="249"><tr><td><img src="img/jpa-direct-relation.png"></td></tr></table></div>
<p>
You typically map a direct relation with <code class="classname">JoinColumn</code>
annotations describing how the local foreign key columns join to the primary key
columns of the related record. The <code class="classname">JoinColumn</code> annotation
exposes the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the foreign key column. Defaults to
the relation field name, plus an underscore, plus the name of the referenced
primary key column.
</p>
</li><li class="listitem">
<p>
<code class="literal">String referencedColumnName</code>: The name of the primary key
column being joined to. If there is only one identity field in the related
entity class, the join column name defaults to the name of the identity field's
column.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean unique</code>: Whether this column is guaranteed to hold
unique values for all rows. Defaults to false.
</p>
</li></ul></div>
<p>
<code class="classname">JoinColumn</code> also has the same <code class="literal"> nullable</code>
, <code class="literal">insertable</code>, <code class="literal"> updatable</code>, <code class="literal">
columnDefinition</code>, and <code class="literal">table</code> properties as the
<code class="classname"> Column</code> annotation. See
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a> for details on these
properties.
</p>
<p>
The <code class="literal">join-column</code> element represents a join column in XML. Its
attributes mirror the above annotation's properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">referenced-column-name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">unique</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">nullable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">insertable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">updatable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">column-definition</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">table</code>
</p>
</li></ul></div>
<p>
When there are multiple columns involved in the join, as when a <code class="classname">
LineItem</code> references a <code class="classname">Magazine</code> in our model,
the <code class="classname">JoinColumns</code> annotation allows you to specify an array
of <code class="classname">JoinColumn</code> values. In XML, simply list multiple
<code class="literal">join-column</code> elements.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA supports many non-standard joins. See
<a class="xref" href="#ref_guide_mapping_notes_nonstdjoins" title="6.&nbsp; Non-Standard Joins">Section&nbsp;6, &#8220;
Non-Standard Joins
&#8221;</a> in the Reference
Guide for details.
</p>
</div>
<div class="example" id="jpa_overview_mapping_relex"><p class="title"><b>Example&nbsp;13.14.&nbsp;
Direct Relation Field Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Table(name="AUTH")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
@OneToOne
@JoinColumn(name="COVER_ID" referencedColumnName="ID")
private Article coverArticle;
@ManyToOne
@JoinColumn(name="PUB_ID" referencedColumnName="CID")
private Company publisher;
...
}
@Table(name="ART")
public class Article {
@Id private long id;
...
}
package org.mag.pub;
@Table(name="COMP")
public class Company {
@Column(name="CID")
@Id private long id;
...
}
package org.mag.subscribe;
public class Subscription {
...
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
@ManyToOne
@JoinColumns({
@JoinColumn(name="MAG_ISBN" referencedColumnName="ISBN"),
@JoinColumn(name="MAG_TITLE" referencedColumnName="TITLE")
})
private Magazine magazine;
...
}
}
</pre>
<p>
The same metadata expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;id-class="org.mag.Magazine.MagazineId"/&gt;
&lt;attributes&gt;
&lt;id name="isbn"&gt;
&lt;column length="9"/&gt;
&lt;/id&gt;
&lt;id name="title"/&gt;
&lt;one-to-one name="coverArticle"&gt;
&lt;join-column name="COVER_ID" referenced-column-name="ID"/&gt;
&lt;/one-to-one&gt;
&lt;many-to-one name="publisher"&gt;
&lt;join-column name="PUB_IC" referenced-column-name="CID"/&gt;
&lt;/many-to-one&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"/&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="CID"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
&lt;primary-key-join-column name="ID" referenced-column-name="PK"/&gt;
&lt;attributes&gt;
&lt;many-to-one name="magazine"&gt;
&lt;join-column name="MAG_ISBN" referenced-column-name="ISBN"/&gt;
&lt;join-column name="MAG_TITLE" referenced-column-name="TITLE"/&gt;
&lt;/many-to-one&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
<p>
When the entities in a one to one relation join on shared primary key values
rather than separate foreign key columns, use the <code class="classname">
PrimaryKeyJoinColumn(s)</code> annotation or <code class="literal">
primary-key-join-column</code> elements in place of <code class="classname">JoinColumn(s)
</code> / <code class="literal"> join-column</code> elements.
</p>
</div>
<div class="section" id="jpa_overview_mapping_assoccoll"><div class="titlepage"><div><div><h3 class="title">8.5.&nbsp;
Join Table
</h3></div></div></div>
<a class="indexterm" name="d5e6562"></a>
<a class="indexterm" name="d5e6566"></a>
<a class="indexterm" name="d5e6569"></a>
<a class="indexterm" name="d5e6571"></a>
<a class="indexterm" name="d5e6574"></a>
<p>
A <span class="emphasis"><em>join table</em></span> consists of two foreign keys. Each row of a
join table associates two objects together. JPA uses join tables to
represent collections of entity objects: one foreign key refers back to the
collection's owner, and the other refers to a collection element.
</p>
<p>
<a class="link" href="#jpa_overview_meta_onetomany" title="2.10.&nbsp; One To Many">one to many</a> and
<a class="link" href="#jpa_overview_meta_manytomany" title="2.12.&nbsp; Many To Many">many to many</a> metadata field
types can map to join tables. Several fields in our model use join table
mappings, including <code class="literal">Magazine.articles</code> and <code class="literal">
Article.authors</code>.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="261"><tr><td><img src="img/jpa-assoc-table.png"></td></tr></table></div>
<p>
You define join tables with the <code class="classname">JoinTable</code> annotation.
This annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: Table name. If not given, the name of the table
defaults to the name of the owning entity's table, plus an underscore, plus the
name of the related entity's table.
</p>
</li><li class="listitem">
<p>
<code class="literal">String catalog</code>: Table catalog.
</p>
</li><li class="listitem">
<p>
<code class="literal">String schema</code>: Table schema.
</p>
</li><li class="listitem">
<p>
<code class="literal">JoinColumn[] joinColumns</code>: Array of <code class="classname">JoinColumn
</code> showing how to associate join table records with the owning row in
the primary table. This property mirrors the <code class="literal">pkJoinColumns</code>
property of the <code class="classname"> SecondaryTable</code> annotation in
functionality. See <a class="xref" href="#jpa_overview_mapping_secondary" title="8.2.&nbsp; Secondary Tables">Section&nbsp;8.2, &#8220;
Secondary Tables
&#8221;</a> to
refresh your memory on secondary tables.
</p>
<p>
If this is a bidirectional relation (see
<a class="xref" href="#jpa_overview_meta_mappedby" title="2.10.1.&nbsp; Bidirectional Relations">Section&nbsp;2.10.1, &#8220;
Bidirectional Relations
&#8221;</a> ), the name of a join column
defaults to the inverse field name, plus an underscore, plus the referenced
primary key column name. Otherwise, the join column name defaults to the field's
owning entity name, plus an underscore, plus the referenced primary key column
name.
</p>
</li><li class="listitem">
<p>
<code class="literal">JoinColumn[] inverseJoinColumns</code>: Array of <code class="classname">
JoinColumns</code> showing how to associate join table records with the
records that form the elements of the collection. These join columns are used
just like the join columns for direct relations, and they have the same naming
defaults. Read <a class="xref" href="#jpa_overview_mapping_rel" title="8.4.&nbsp; Direct Relations">Section&nbsp;8.4, &#8220;
Direct Relations
&#8221;</a> for a review of
direct relation mapping.
</p>
</li></ul></div>
<p>
<code class="literal">join-table</code> is the corresponding XML element. It has the same
attributes as the <code class="literal">table</code> element, but includes the ability to
nest <code class="literal">join-column</code> and <code class="literal">inverse-join-column</code>
elements as children. We have seen <code class="literal">join-column</code> elements
already; <code class="literal">inverse-join-column</code> elements have the same
attributes.
</p>
<p>
Here are the join table mappings for the diagram above.
</p>
<div class="example" id="jpa_overview_mapping_assoccollex"><p class="title"><b>Example&nbsp;13.15.&nbsp;
Join Table Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@Table(name="MAG")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
@OneToMany(...)
@OrderBy
@JoinTable(name="MAG_ARTS",
joinColumns={
@JoinColumn(name="MAG_ISBN", referencedColumnName="ISBN"),
@JoinColumn(name="MAG_TITLE", referencedColumnName="TITLE")
},
inverseJoinColumns=@JoinColumn(name="ART_ID", referencedColumnName="ID"))
private Collection&lt;Article&gt; articles;
...
}
@Entity
@Table(name="ART")
public class Article {
@Id private long id;
@ManyToMany(cascade=CascadeType.PERSIST)
@OrderBy("lastName, firstName")
@JoinTable(name="ART_AUTHS",
joinColumns=@JoinColumn(name="ART_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="AUTH_ID", referencedColumnName="AID"))
private Collection&lt;Author&gt; authors;
...
}
package org.mag.pub;
@Entity
@Table(name="AUTH")
public class Author {
@Column(name="AID", columnDefinition="INTEGER64")
@Id private long id;
...
}
</pre>
<p>
The same metadata expressed in XML:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;attributes&gt;
&lt;id name="isbn"&gt;
&lt;column length="9"/&gt;
&lt;/id&gt;
&lt;id name="title"/&gt;
&lt;one-to-many name="articles"&gt;
&lt;order-by/&gt;
&lt;join-table name="MAG_ARTS"&gt;
&lt;join-column name="MAG_ISBN" referenced-column-name="ISBN"/&gt;
&lt;join-column name="MAG_TITLE" referenced-column-name="TITLE"/&gt;
&lt;inverse-join-column name="ART_ID" referenced-column-name="ID"/&gt;
&lt;/join-table&gt;
&lt;/one-to-many&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"/&gt;
&lt;attributes&gt;
&lt;id name="id"/&gt;
&lt;many-to-many name="authors"&gt;
&lt;order-by&gt;lastName, firstName&lt;/order-by&gt;
&lt;join-table name="ART_AUTHS"&gt;
&lt;join-column name="ART_ID" referenced-column-name="ID"/&gt;
&lt;inverse-join-column name="AUTH_ID" referenced-column-name="AID"/&gt;
&lt;/join-table&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;/cascade&gt;
&lt;/many-to-many&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="AID" column-definition="INTEGER64"/&gt;
&lt;/id&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="jpa_overview_mapping_bidi"><div class="titlepage"><div><div><h3 class="title">8.6.&nbsp;
Bidirectional Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e6628"></a>
<p>
<a class="xref" href="#jpa_overview_meta_mappedby" title="2.10.1.&nbsp; Bidirectional Relations">Section&nbsp;2.10.1, &#8220;
Bidirectional Relations
&#8221;</a> introduced bidirectional
relations. To map a bidirectional relation, you map one field normally using the
annotations we have covered throughout this chapter. Then you use the <code class="literal">
mappedBy</code> property of the other field's metadata annotation or the
corresponding <code class="literal">mapped-by</code> XML attribute to refer to the mapped
field. Look for this pattern in these bidirectional relations as you peruse the
complete mappings below:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Magazine.publisher</code> and <code class="literal">Company.mags</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">Article.authors</code> and <code class="literal">Author.articles</code>.
</p>
</li></ul></div>
</div>
<div class="section" id="jpa_overview_mapping_map"><div class="titlepage"><div><div><h3 class="title">8.7.&nbsp;
Map Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e6646"></a>
<a class="indexterm" name="d5e6649"></a>
<p>
All map fields in JPA are modeled on either one to many or many to
many associations. The map key is always derived from an associated entity's
field. Thus map fields use the same mappings as any one to many or many to many
fields, namely dedicated <a class="link" href="#jpa_overview_mapping_assoccoll" title="8.5.&nbsp; Join Table">join
tables</a> or <a class="link" href="#jpa_overview_mapping_bidi" title="8.6.&nbsp; Bidirectional Mapping">bidirectional
relations</a>. The only additions are the <code class="classname">MapKey</code>
annotation and <code class="literal">map-key</code> element to declare the key field. We
covered these additions in <a class="xref" href="#jpa_overview_meta_mapkey" title="2.14.&nbsp; Map Key">Section&nbsp;2.14, &#8220;
Map Key
&#8221;</a>.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="255"><tr><td><img src="img/jpa-map.png"></td></tr></table></div>
<p>
The example below maps <code class="classname">Subscription</code>'s map of <code class="classname">
LineItem</code>s to the <code class="literal">SUB_ITEMS</code> join table. The key
for each map entry is the <code class="classname"> LineItem</code>'s <code class="literal">num
</code> field value.
</p>
<div class="example" id="jpa_overview_mapping_mapex"><p class="title"><b>Example&nbsp;13.16.&nbsp;
Join Table Map Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag.subscribe;
@Entity
@Table(name="SUB", schema="CNTRCT")
public class Subscription {
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@MapKey(name="num")
@JoinTable(name="SUB_ITEMS", schema="CNTRCT",
joinColumns=@JoinColumn(name="SUB_ID"),
inverseJoinColumns=@JoinColumn(name="ITEM_ID"))
private Map&lt;Long,LineItem&gt; items;
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
private long num;
...
}
}
</pre>
<p>
The same metadata expressed in XML:
</p>
<pre class="programlisting">
&lt;entity class="org.mag.subscribe.Subscription"&gt;
&lt;table name="SUB" schema="CNTRCT"/&gt;
&lt;attributes&gt;
...
&lt;one-to-many name="items"&gt;
&lt;map-key name="num"&gt;
&lt;join-table name="SUB_ITEMS" schema="CNTRCT"&gt;
&lt;join-column name="SUB_ID"/&gt;
&lt;inverse-join-column name="ITEM_ID"/&gt;
&lt;/join-table&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
&lt;attributes&gt;
...
&lt;basic name="num"/&gt;
...
&lt;/attributes&gt;
&lt;/entity&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="jpa_overview_mapping_full"><div class="titlepage"><div><div><h2 class="title" style="clear: both">9.&nbsp;
The Complete Mappings
</h2></div></div></div>
<p>
We began this chapter with the goal of mapping the following object model:
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="369"><tr><td><img src="img/jpa-meta-model.png"></td></tr></table></div>
<p>
That goal has now been met. In the course of explaining JPA's object-relational
mapping metadata, we slowly built the requisite schema and mappings for the
complete model. First, the database schema:
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="326"><tr><td><img src="img/jpa-data-model.png"></td></tr></table></div>
<p>
And finally, the complete entity mappings. We have trimmed the mappings to take
advantage of JPA defaults where possible.
</p>
<div class="example" id="jpa_overview_mapping_fullex"><p class="title"><b>Example&nbsp;13.17.&nbsp;
Full Entity Mappings
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag;
@Entity
@IdClass(Magazine.MagazineId.class)
@Table(name="MAG")
@DiscriminatorValue("Mag")
public class Magazine {
@Column(length=9)
@Id private String isbn;
@Id private String title;
@Column(name="VERS")
@Version private int version;
private String name;
private double price;
@Column(name="COPIES")
private int copiesSold;
@OneToOne(fetch=FetchType.LAZY,
cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@JoinColumn(name="COVER_ID")
private Article coverArticle;
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@OrderBy
@JoinTable(name="MAG_ARTS",
joinColumns={
@JoinColumn(name="MAG_ISBN", referencedColumnName="ISBN"),
@JoinColumn(name="MAG_TITLE", referencedColumnName="TITLE")
},
inverseJoinColumns=@JoinColumn(name="ART_ID"))
private Collection&lt;Article&gt; articles;
@ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST)
@JoinColumn(name="PUB_ID")
private Company publisher;
@Transient private byte[] data;
...
public static class MagazineId {
...
}
}
@Entity
@Table(name="ART", uniqueConstraints=@Unique(columnNames="TITLE"))
@SequenceGenerator(name="ArticleSeq", sequenceName="ART_SEQ")
public class Article {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ArticleSeq")
private long id;
@Column(name="VERS")
@Version private int version;
private String title;
private byte[] content;
@ManyToMany(cascade=CascadeType.PERSIST)
@OrderBy("lastName, firstName")
@JoinTable(name="ART_AUTHS",
joinColumns=@JoinColumn(name="ART_ID"),
inverseJoinColumns=@JoinColumn(name="AUTH_ID"))
private Collection&lt;Author&gt; authors;
...
}
package org.mag.pub;
@Entity
@Table(name="COMP")
public class Company {
@Column(name="CID")
@Id private long id;
@Column(name="VERS")
@Version private int version;
private String name;
@Column(name="REV")
private double revenue;
@Embedded
@AttributeOverrides({
@AttributeOverride(name="street", column=@Column(name="STRT")),
@AttributeOverride(name="city", column=@Column(name="ACITY"))
})
private Address address;
@OneToMany(mappedBy="publisher", cascade=CascadeType.PERSIST)
private Collection&lt;Magazine&gt; mags;
@OneToMany(cascade=CascadeType.PERSIST,CascadeType.REMOVE)
@JoinTable(name="COMP_SUBS",
joinColumns=@JoinColumn(name="COMP_ID"),
inverseJoinColumns=@JoinColumn(name="SUB_ID"))
private Collection&lt;Subscription&gt; subscriptions;
...
}
@Entity
@Table(name="AUTH")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="AuthorGen")
@TableGenerator(name="AuthorGen", tableName="AUTH_GEN", pkColumnName="PK",
valueColumnName="AID")
@Column(name="AID", columnDefinition="INTEGER64")
private long id;
@Column(name="VERS")
@Version private int version;
@Column(name="FNAME")
private String firstName;
@Column(name="LNAME")
private String lastName;
private Address address;
@ManyToMany(mappedBy="authors", cascade=CascadeType.PERSIST)
private Collection&lt;Article&gt; arts;
...
}
@Embeddable
public class Address {
private String street;
private String city;
@Column(columnDefinition="CHAR(2)")
private String state;
private String zip;
}
package org.mag.subscribe;
@MappedSuperclass
public abstract class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="VERS")
@Version private int version;
...
}
@Entity
@Table(schema="CNTRCT")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="CTYPE")
public class Contract
extends Document {
@Lob
private String terms;
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
@DiscriminatorColumn(name="KIND", discriminatorType=DiscriminatorType.INTEGER)
@DiscriminatorValue("1")
public class Subscription {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="VERS")
@Version private int version;
@Column(name="START")
private Date startDate;
@Column(name="PAY")
private double payment;
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@MapKey(name="num")
@JoinTable(name="SUB_ITEMS", schema="CNTRCT",
joinColumns=@JoinColumn(name="SUB_ID"),
inverseJoinColumns=@JoinColumn(name="ITEM_ID"))
private Map&lt;Long,LineItem&gt; items;
...
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public static class LineItem
extends Contract {
@Column(name="COMM")
private String comments;
private double price;
private long num;
@ManyToOne
@JoinColumns({
@JoinColumn(name="MAG_ISBN", referencedColumnName="ISBN"),
@JoinColumn(name="MAG_TITLE", referencedColumnName="TITLE")
})
private Magazine magazine;
...
}
}
@Entity(name="Lifetime")
@DiscriminatorValue("2")
public class LifetimeSubscription
extends Subscription {
@Basic(fetch=FetchType.LAZY)
@Column(name="ELITE")
private boolean getEliteClub() { ... }
public void setEliteClub(boolean elite) { ... }
...
}
@Entity(name="Trial")
@DiscriminatorValue("3")
public class TrialSubscription
extends Subscription {
@Column(name="END")
public Date getEndDate() { ... }
public void setEndDate(Date end) { ... }
...
}
</pre>
<p>
The same metadata expressed in XML form:
</p>
<pre class="programlisting">
&lt;entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"&gt;
&lt;mapped-superclass class="org.mag.subscribe.Document"&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
&lt;/attributes&gt;
&lt;/mapped-superclass&gt;
&lt;entity class="org.mag.Magazine"&gt;
&lt;table name="MAG"/&gt;
&lt;id-class="org.mag.Magazine.MagazineId"/&gt;
&lt;discriminator-value&gt;Mag&lt;/discriminator-value&gt;
&lt;attributes&gt;
&lt;id name="isbn"&gt;
&lt;column length="9"/&gt;
&lt;/id&gt;
&lt;id name="title"/&gt;
&lt;basic name="name"/&gt;
&lt;basic name="price"/&gt;
&lt;basic name="copiesSold"&gt;
&lt;column name="COPIES"/&gt;
&lt;/basic&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
&lt;many-to-one name="publisher" fetch="LAZY"&gt;
&lt;join-column name="PUB_ID"/&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;/cascade&gt;
&lt;/many-to-one&gt;
&lt;one-to-many name="articles"&gt;
&lt;order-by/&gt;
&lt;join-table name="MAG_ARTS"&gt;
&lt;join-column name="MAG_ISBN" referenced-column-name="ISBN"/&gt;
&lt;join-column name="MAG_TITLE" referenced-column-name="TITLE"/&gt;
&lt;inverse-join-column name="ART_ID"/&gt;
&lt;/join-table&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;one-to-one name="coverArticle" fetch="LAZY"&gt;
&lt;join-column name="COVER_ID"/&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-one&gt;
&lt;transient name="data"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.Article"&gt;
&lt;table name="ART"&gt;
&lt;unique-constraint&gt;
&lt;column-name&gt;TITLE&lt;/column-name&gt;
&lt;/unique-constraint&gt;
&lt;/table&gt;
&lt;sequence-generator name="ArticleSeq", sequenceName="ART_SEQ"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="SEQUENCE" generator="ArticleSeq"/&gt;
&lt;/id&gt;
&lt;basic name="title"/&gt;
&lt;basic name="content"/&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
&lt;many-to-many name="articles"&gt;
&lt;order-by&gt;lastName, firstName&lt;/order-by&gt;
&lt;join-table name="ART_AUTHS"&gt;
&lt;join-column name="ART_ID" referenced-column-name="ID"/&gt;
&lt;inverse-join-column name="AUTH_ID" referenced-column-name="AID"/&gt;
&lt;/join-table&gt;
&lt;/many-to-many&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Company"&gt;
&lt;table name="COMP"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="CID"/&gt;
&lt;/id&gt;
&lt;basic name="name"/&gt;
&lt;basic name="revenue"&gt;
&lt;column name="REV"/&gt;
&lt;/basic&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
&lt;one-to-many name="mags" mapped-by="publisher"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;one-to-many name="subscriptions"&gt;
&lt;join-table name="COMP_SUBS"&gt;
&lt;join-column name="COMP_ID"/&gt;
&lt;inverse-join-column name="SUB_ID"/&gt;
&lt;/join-table&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;embedded name="address"&gt;
&lt;attribute-override name="street"&gt;
&lt;column name="STRT"/&gt;
&lt;/attribute-override&gt;
&lt;attribute-override name="city"&gt;
&lt;column name="ACITY"/&gt;
&lt;/attribute-override&gt;
&lt;/embedded&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.pub.Author"&gt;
&lt;table name="AUTH"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;column name="AID" column-definition="INTEGER64"/&gt;
&lt;generated-value strategy="TABLE" generator="AuthorGen"/&gt;
&lt;table-generator name="AuthorGen" table="AUTH_GEN"
pk-column-name="PK" value-column-name="AID"/&gt;
&lt;/id&gt;
&lt;basic name="firstName"&gt;
&lt;column name="FNAME"/&gt;
&lt;/basic&gt;
&lt;basic name="lastName"&gt;
&lt;column name="LNAME"/&gt;
&lt;/basic&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
&lt;many-to-many name="arts" mapped-by="authors"&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;/cascade&gt;
&lt;/many-to-many&gt;
&lt;embedded name="address"/&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Contract"&gt;
&lt;table schema="CNTRCT"/&gt;
&lt;inheritance strategy="JOINED"/&gt;
&lt;discriminator-column name="CTYPE"/&gt;
&lt;attributes&gt;
&lt;basic name="terms"&gt;
&lt;lob/&gt;
&lt;/basic&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subcribe.Subscription"&gt;
&lt;table name="SUB" schema="CNTRCT"/&gt;
&lt;inheritance strategy="SINGLE_TABLE"/&gt;
&lt;discriminator-value&gt;1&lt;/discriminator-value&gt;
&lt;discriminator-column name="KIND" discriminator-type="INTEGER"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;generated-value strategy="IDENTITY"/&gt;
&lt;/id&gt;
&lt;basic name="payment"&gt;
&lt;column name="PAY"/&gt;
&lt;/basic&gt;
&lt;basic name="startDate"&gt;
&lt;column name="START"/&gt;
&lt;/basic&gt;
&lt;version name="version"&gt;
&lt;column name="VERS"/&gt;
&lt;/version&gt;
&lt;one-to-many name="items"&gt;
&lt;map-key name="num"&gt;
&lt;join-table name="SUB_ITEMS" schema="CNTRCT"&gt;
&lt;join-column name="SUB_ID"/&gt;
&lt;inverse-join-column name="ITEM_ID"/&gt;
&lt;/join-table&gt;
&lt;cascade&gt;
&lt;cascade-persist/&gt;
&lt;cascade-remove/&gt;
&lt;/cascade&gt;
&lt;/one-to-many&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.Subscription.LineItem"&gt;
&lt;table name="LINE_ITEM" schema="CNTRCT"/&gt;
&lt;attributes&gt;
&lt;basic name="comments"&gt;
&lt;column name="COMM"/&gt;
&lt;/basic&gt;
&lt;basic name="price"/&gt;
&lt;basic name="num"/&gt;
&lt;many-to-one name="magazine"&gt;
&lt;join-column name="MAG_ISBN" referenced-column-name="ISBN"/&gt;
&lt;join-column name="MAG_TITLE" referenced-column-name="TITLE"/&gt;
&lt;/many-to-one&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.LifetimeSubscription" name="Lifetime"&gt;
&lt;discriminator-value&gt;2&lt;/discriminator-value&gt;
&lt;attributes&gt;
&lt;basic name="eliteClub" fetch="LAZY"&gt;
&lt;column name="ELITE"/&gt;
&lt;/basic&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;entity class="org.mag.subscribe.TrialSubscription" name="Trial"&gt;
&lt;discriminator-value&gt;3&lt;/discriminator-value&gt;
&lt;attributes&gt;
&lt;basic name="endDate"&gt;
&lt;column name="END"/&gt;
&lt;/basic&gt;
&lt;/attributes&gt;
&lt;/entity&gt;
&lt;embeddable class="org.mag.pub.Address"&gt;
&lt;attributes&gt;
&lt;basic name="street"/&gt;
&lt;basic name="city"/&gt;
&lt;basic name="state"&gt;
&lt;column column-definition="CHAR(2)"/&gt;
&lt;/basic&gt;
&lt;basic name="zip"/&gt;
&lt;/attributes&gt;
&lt;/embeddable&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="chapter" id="jpa_overview_conclusion"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;14.&nbsp;
Conclusion
</h2></div></div></div>
<p>
This concludes our overview of the JPA specification.
The <a class="link" href="#ref_guide_intro" title="Chapter&nbsp;1.&nbsp; Introduction">OpenJPA Reference Guide</a>
contains detailed documentation on all aspects of the OpenJPA implementation
and core development tools.
</p>
</div>
</div>
<div class="part" id="ref_guide"><div class="titlepage"><div><div><h1 class="title">Part&nbsp;3.&nbsp;Reference Guide</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="chapter"><a href="#ref_guide_intro">1.
Introduction
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_intro_audience">1.
Intended Audience
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_conf">2.
Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_conf_intro">1.
Introduction
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_specify">2.
Runtime Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_devtools">3.
Command Line Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_conf_devtools_format">3.1.
Code Formatting
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_conf_plugins">4.
Plugin Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_openjpa">5.
OpenJPA Properties
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa.AutoClear">5.1.
openjpa.AutoClear
</a></span></dt><dt><span class="section"><a href="#openjpa.AutoDetach">5.2.
openjpa.AutoDetach
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerFactory">5.3.
openjpa.BrokerFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerImpl">5.4.
openjpa.BrokerImpl
</a></span></dt><dt><span class="section"><a href="#openjpa.Callbacks">5.5. openjpa.Callbacks</a></span></dt><dt><span class="section"><a href="#openjpa.ClassResolver">5.6.
openjpa.ClassResolver
</a></span></dt><dt><span class="section"><a href="#openjpa.Compatibility">5.7.
openjpa.Compatibility
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionDriverName">5.8.
openjpa.ConnectionDriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2DriverName">5.9.
openjpa.Connection2DriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory">5.10.
openjpa.ConnectionFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2">5.11.
openjpa.ConnectionFactory2
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryName">5.12.
openjpa.ConnectionFactoryName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Name">5.13.
openjpa.ConnectionFactory2Name
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryMode">5.14.
openjpa.ConnectionFactoryMode
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryProperties">5.15.
openjpa.ConnectionFactoryProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Properties">5.16.
openjpa.ConnectionFactory2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionPassword">5.17.
openjpa.ConnectionPassword
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Password">5.18.
openjpa.Connection2Password
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionProperties">5.19.
openjpa.ConnectionProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Properties">5.20.
openjpa.Connection2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionURL">5.21.
openjpa.ConnectionURL
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2URL">5.22.
openjpa.Connection2URL
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionUserName">5.23.
openjpa.ConnectionUserName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2UserName">5.24.
openjpa.Connection2UserName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionRetainMode">5.25.
openjpa.ConnectionRetainMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCache">5.26.
openjpa.DataCache
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheManager">5.27.
openjpa.DataCacheManager
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheMode">5.28.
openjpa.DataCacheMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheTimeout">5.29.
openjpa.DataCacheTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.DetachState">5.30.
openjpa.DetachState
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicDataStructs">5.31.
openjpa.DynamicDataStructs
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicEnhancementAgent">5.32. openjpa.DynamicEnhancementAgent</a></span></dt><dt><span class="section"><a href="#openjpa.FetchBatchSize">5.33.
openjpa.FetchBatchSize
</a></span></dt><dt><span class="section"><a href="#openjpa.EncryptionProvider">5.34.
openjpa.EncryptionProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.FetchGroups">5.35.
openjpa.FetchGroups
</a></span></dt><dt><span class="section"><a href="#openjpa.FlushBeforeQueries">5.36.
openjpa.FlushBeforeQueries
</a></span></dt><dt><span class="section"><a href="#openjpa.IgnoreChanges">5.37.
openjpa.IgnoreChanges
</a></span></dt><dt><span class="section"><a href="#openjpa.Id">5.38. openjpa.Id</a></span></dt><dt><span class="section"><a href="#openjpa.InitializeEagerly">5.39.
openjpa.InitializeEagerly
</a></span></dt><dt><span class="section"><a href="#openjpa.Instrumentation">5.40.
openjpa.Instrumentation
</a></span></dt><dt><span class="section"><a href="#openjpa.InverseManager">5.41.
openjpa.InverseManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockManager">5.42.
openjpa.LockManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockTimeout">5.43.
openjpa.LockTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.Log">5.44.
openjpa.Log
</a></span></dt><dt><span class="section"><a href="#openjpa.ManagedRuntime">5.45.
openjpa.ManagedRuntime
</a></span></dt><dt><span class="section"><a href="#openjpa.Mapping">5.46.
openjpa.Mapping
</a></span></dt><dt><span class="section"><a href="#openjpa.MaxFetchDepth">5.47.
openjpa.MaxFetchDepth
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataFactory">5.48.
openjpa.MetaDataFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataRepository">5.49.
openjpa.MetaDataRepository
</a></span></dt><dt><span class="section"><a href="#openjpa.Multithreaded">5.50.
openjpa.Multithreaded
</a></span></dt><dt><span class="section"><a href="#openjpa.Optimistic">5.51.
openjpa.Optimistic
</a></span></dt><dt><span class="section"><a href="#openjpa.OptimizeIdCopy">5.52.
openjpa.OptimizeIdCopy
</a></span></dt><dt><span class="section"><a href="#openjpa.OrphanedKeyAction">5.53.
openjpa.OrphanedKeyAction
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalRead">5.54.
openjpa.NontransactionalRead
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalWrite">5.55.
openjpa.NontransactionalWrite
</a></span></dt><dt><span class="section"><a href="#openjpa.ProxyManager">5.56.
openjpa.ProxyManager
</a></span></dt><dt><span class="section"><a href="#openjpa.PostLoadOnMerge">5.57.
openjpa.PostLoadOnMerge
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCache">5.58.
openjpa.QueryCache
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCompilationCache">5.59.
openjpa.QueryCompilationCache
</a></span></dt><dt><span class="section"><a href="#openjpa.ReadLockLevel">5.60.
openjpa.ReadLockLevel
</a></span></dt><dt><span class="section"><a href="#openjpa.RemoteCommitProvider">5.61.
openjpa.RemoteCommitProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.RestoreState">5.62.
openjpa.RestoreState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetainState">5.63.
openjpa.RetainState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetryClassRegistration">5.64.
openjpa.RetryClassRegistration
</a></span></dt><dt><span class="section"><a href="#openjpa.RuntimeUnenhancedClasses">5.65. openjpa.RuntimeUnenhancedClasses</a></span></dt><dt><span class="section"><a href="#openjpa.SavepointManager">5.66.
openjpa.SavepointManager
</a></span></dt><dt><span class="section"><a href="#openjpa.Sequence">5.67.
openjpa.Sequence
</a></span></dt><dt><span class="section"><a href="#openjpa.Specification">5.68.
openjpa.Specification
</a></span></dt><dt><span class="section"><a href="#openjpa.TransactionMode">5.69.
openjpa.TransactionMode
</a></span></dt><dt><span class="section"><a href="#openjpa.UseTCCLinSelectNew">5.70.
openjpa.UseTCCLinSelectNew
</a></span></dt><dt><span class="section"><a href="#openjpa.WriteLockLevel">5.71.
openjpa.WriteLockLevel
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_conf_jdbc">6.
OpenJPA JDBC Properties
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa.jdbc.ConnectionDecorators">6.1.
openjpa.jdbc.ConnectionDecorators
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DBDictionary">6.2.
openjpa.jdbc.DBDictionary
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DriverDataSource">6.3.
openjpa.jdbc.DriverDataSource
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.EagerFetchMode">6.4.
openjpa.jdbc.EagerFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.FetchDirection">6.5.
openjpa.jdbc.FetchDirection
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.JDBCListeners">6.6.
openjpa.jdbc.JDBCListeners
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.LRSSize">6.7.
openjpa.jdbc.LRSSize
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingDefaults">6.8.
openjpa.jdbc.MappingDefaults
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingFactory">6.9.
openjpa.jdbc.MappingFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.QuerySQLCache">6.10.
openjpa.jdbc.QuerySQLCache
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.ResultSetType">6.11.
openjpa.jdbc.ResultSetType
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schema">6.12.
openjpa.jdbc.Schema
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SchemaFactory">6.13.
openjpa.jdbc.SchemaFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schemas">6.14.
openjpa.jdbc.Schemas
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SQLFactory">6.15.
openjpa.jdbc.SQLFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SubclassFetchMode">6.16.
openjpa.jdbc.SubclassFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SynchronizeMappings">6.17.
openjpa.jdbc.SynchronizeMappings
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.TransactionIsolation">6.18.
openjpa.jdbc.TransactionIsolation
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.UpdateManager">6.19.
openjpa.jdbc.UpdateManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_spec_compatibility">6.20. Compatibility with Specification</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_logging">3.
Logging and Auditing
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_logging_channels">1.
Logging Channels
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_openjpa">2.
OpenJPA Logging
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_noop">3.
Disabling Logging
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_log4j">4.
Log4J
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_commons">5.
Apache Commons Logging
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_logging_jdk14">5.1.
JDK java.util.logging
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_logging_slf4j">6.
SLF4J
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_custom">7.
Custom Log
</a></span></dt><dt><span class="section"><a href="#ref_guide_audit">8. OpenJPA Audit</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e9423">8.1. Configuration</a></span></dt><dt><span class="section"><a href="#d5e9445">8.2. Developing custom auditing</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_dbsetup">4.
JDBC
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_builtin">1.
Using the OpenJPA DataSource
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_auto">1.1.
Optional Connection Pooling
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_config">1.2.
Configuring the OpenJPA DataSource
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbcp">1.3.
Configuring Apache Commons DBCP
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_thirdparty">2.
Using a Third-Party DataSource
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_thirdparty_enlist">2.1.
Managed and XA DataSources
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSatRuntime">2.2. Setting the DataSource at runtime</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSPerEM">2.2.1. Using different DataSources for each EntityManager</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSBenefits">2.2.1.1. Benefits</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSLimitations">2.2.1.2. Limitations</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSError">2.2.1.3. Error handling</a></span></dt></dl></dd></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_sqlconn">3.
Runtime Access to DataSource
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport">4.
Database Support
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_dbdictprops">4.1.
DBDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_firebird">4.2.
FirebirdDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_mysql">4.3.
MySQLDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_oracle">4.4.
OracleDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_sybase">4.5.
SybaseDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_db2">4.6.
DB2 Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_delim_id">4.7.
Delimited Identifiers Support
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_isolation">5.
Setting the Transaction Isolation
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_sql92">6.
Setting the SQL Join Syntax
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_multidb">7.
Accessing Multiple Databases
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_retain">8.
Configuring the Use of JDBC Connections
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_stmtbatch">9.
Statement Batching
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_lrs">10.
Large Result Sets
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_def">11.
Default Schema
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_info">12.
Schema Reflection
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_schema_info_list">12.1.
Schemas List
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_info_factory">12.2.
Schema Factory
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_schema_schematool">13.
Schema Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_xml">14.
XML Schema Format
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_pc">5.
Persistent Classes
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_pcclasses">1.
Persistent Class List
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance">2.
Enhancement
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_enhance_build">2.1.
Enhancing at Build Time
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime_container">2.2.
Enhancing JPA Entities on Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime">2.3.
Enhancing at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_dynamic">2.4.
Enhancing Dynamically at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_unenhanced_types">2.5.
Omitting the OpenJPA enhancer
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_interfaces">3. Managed Interfaces</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid">4.
Object Identity
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_oid_datastore">4.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_entitypk">4.2.
Entities as Identity Fields
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_application">4.3.
Application Identity Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_pkgen_autoinc">4.4.
Autoassign / Identity Strategy Caveats
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_inverses">5.
Managed Inverses
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos">6.
Persistent Fields
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_scos_restore">6.1.
Restoring State
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_order">6.2.
Typing and Ordering
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_calendar_timezone">6.3.
Calendar Fields and TimeZones
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy">6.4.
Proxies
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_smart">6.4.1.
Smart Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_lrs">6.4.2.
Large Result Set Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_custom">6.4.3.
Custom Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_serial">6.4.4.
Serialization
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_extern">6.5.
Externalization
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_extern_values">6.5.1.
External Values
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_fetch">7.
Fetch Groups
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_fetch_custom">7.1.
Custom Fetch Groups
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_conf">7.2.
Custom Fetch Group Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_single_field">7.3.
Per-field Fetch Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_impl">7.4.
Implementation Notes
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_perfpack_eager">8.
Eager Fetching
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_perfpack_eager_conf">8.1.
Configuring Eager Fetching
</a></span></dt><dt><span class="section"><a href="#ref_guide_perfpack_eager_consider">8.2.
Eager Fetching Considerations and Limitations
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_meta">6.
Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_factory">1.
Metadata Factory
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_repository">2. Metadata Repository</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa">3.
Additional JPA Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_jpa_datastoreid">3.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_version">3.2.
Surrogate Version
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent">3.3.
Persistent Field Values
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_coll">3.4. Persistent Collection Fields</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_map">3.5. Persistent Map Fields</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_ext">4.
Metadata Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_class">4.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#fetch-groups">4.1.1.
Fetch Groups
</a></span></dt><dt><span class="section"><a href="#data-cache">4.1.2.
Data Cache
</a></span></dt><dt><span class="section"><a href="#detached-state-field">4.1.3.
Detached State
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_field">4.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#dependent">4.2.1.
Dependent
</a></span></dt><dt><span class="section"><a href="#load-fetch-group">4.2.2.
Load Fetch Group
</a></span></dt><dt><span class="section"><a href="#lrs">4.2.3.
LRS
</a></span></dt><dt><span class="section"><a href="#inverse-logical">4.2.4.
Inverse-Logical
</a></span></dt><dt><span class="section"><a href="#read-only">4.2.5.
Read-Only
</a></span></dt><dt><span class="section"><a href="#type">4.2.6.
Type
</a></span></dt><dt><span class="section"><a href="#externalizer">4.2.7.
Externalizer
</a></span></dt><dt><span class="section"><a href="#factory">4.2.8.
Factory
</a></span></dt><dt><span class="section"><a href="#external-values">4.2.9.
External Values
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_example">4.3.
Example
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_xml">4.4.
XML extensions
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_mapping">7.
Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_mappingtool">1.
Forward Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_mappingtool_examples">1.1.
Using the Mapping Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_ddl_examples">1.2.
Generating DDL SQL
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_synch">1.3.
Runtime Forward Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_reverse">2.
Reverse Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_reverse_custom">2.1.
Customizing Reverse Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_middle">3.
Meet-in-the-Middle Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_defaults">4.
Mapping Defaults
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_factory">5.
Mapping Factory
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_notes_nonstdjoins">6.
Non-Standard Joins
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa">7.
Additional JPA Mappings
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_datastoreid">7.1.
Datastore Identity Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_version">7.2.
Surrogate Version Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_columns">7.3.
Multi-Column Mappings
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fieldjoin">7.4.
Join Column Attribute Targets
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_embed">7.5.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll">7.6.
Collections
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_table">7.6.1.
Container Table
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_joincols">7.6.2.
Element Join Columns
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_order">7.6.3.
Order Column
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_onemany">7.7.
One-Sided One-Many Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map">7.8.
Maps
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keycols">7.8.1. Key Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keyjoincols">7.8.2. Key Join Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_embedkey">7.8.3. Key Embedded Mapping</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_ex">7.8.4. Examples</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_constraints">7.9.
Indexes and Constraints
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_index">7.9.1.
Indexes
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fk">7.9.2.
Foreign Keys
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_unique">7.9.3.
Unique Constraints
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_xmlmapping">7.10.
XML Column Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_streamsupport">7.11.
LOB Streaming
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_limits">8.
Mapping Limitations
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_limits_tpc">8.1.
Table Per Class
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_ext">9.
Mapping Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_ext_cls">9.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#subclass-fetch-mode">9.1.1.
Subclass Fetch Mode
</a></span></dt><dt><span class="section"><a href="#class-strategy">9.1.2.
Strategy
</a></span></dt><dt><span class="section"><a href="#discriminator-strategy">9.1.3.
Discriminator Strategy
</a></span></dt><dt><span class="section"><a href="#version-strategy">9.1.4.
Version Strategy
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_ext_field">9.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#eager-fetch-mode">9.2.1.
Eager Fetch Mode
</a></span></dt><dt><span class="section"><a href="#nonpolymorphic">9.2.2.
Nonpolymorphic
</a></span></dt><dt><span class="section"><a href="#class-criteria">9.2.3.
Class Criteria
</a></span></dt><dt><span class="section"><a href="#strategy">9.2.4.
Strategy
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_custom">10.
Custom Mappings
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_custom_class">10.1.
Custom Class Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_versdiscrim">10.2.
Custom Discriminator and Version Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field">10.3.
Custom Field Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_custom_vhandler">10.3.1.
Value Handlers
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_fieldstrat">10.3.2.
Field Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field_conf">10.3.3.
Configuration
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_orphan">11.
Orphaned Keys
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_deploy">8.
Deployment
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_deploy_factory">1.
Factory Deployment
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_deploy_factory_standalone">1.1.
Standalone Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_deploy_inject">1.2.
EntityManager Injection
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_enterprise_trans">2.
Integrating with the Transaction Manager
</a></span></dt><dt><span class="section"><a href="#ref_guide_enterprise_xa">3.
XA Transactions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_enterprise_xa_req">3.1.
Using OpenJPA with XA Transactions
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_runtime">9.
Runtime Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_arch">1.
Architecture
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_broker_finalization">1.1.
Broker Finalization
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_broker_extension">1.2.
Broker Customization and Eviction
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_runtime_jpa">2.
JPA Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_emfactory">2.1.
OpenJPAEntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_em">2.2.
OpenJPAEntityManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquery">2.3.
OpenJPAQuery
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaextent">2.4.
Extent
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpacache">2.5.
StoreCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquerycache">2.6.
QueryResultCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpafetch">2.7.
FetchPlan
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpaentitytransaction">2.8.
OpenJPAEntityTransaction
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpapersistence">2.9.
OpenJPAPersistence
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_locking">3.
Object Locking
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_locking_default">3.1.
Configuring Default Locking
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_runtime">3.2.
Configuring Lock Levels at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_apis">3.3.
Object Locking APIs
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_lockmgr">3.4.
Lock Manager
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_rules">3.5.
Rules for Locking Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_issues">3.6.
Known Issues and Limitations
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_savepoints">4.
Savepoints
</a></span></dt><dd><dl><dt><span class="section"><a href="#reg_guide_savepoints_using">4.1.
Using Savepoints
</a></span></dt><dt><span class="section"><a href="#ref_guide_savepoints_conf">4.2.
Configuring Savepoints
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_enterprise_methodql">5.
MethodQL
</a></span></dt><dt><span class="section"><a href="#ref_guide_sequence">6.
Generators
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_sequence_runtime">6.1.
Runtime Access
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_runtime_pm_event">7.
Transaction Events
</a></span></dt><dt><span class="section"><a href="#ref_guide_enterprise_abstractstore">8.
Non-Relational Stores
</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_caching">10.
Caching
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache">1.
Data Cache
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache_conf">1.1.
Data Cache Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_data_cache">1.1.1.
openjpa.DataCache Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_shared_cache_mode_integration">1.1.2.
Integration with JPA standard shared cache mode
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_distribution">1.1.3. Distributing instances across cache partitions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_use">1.2.
Data Cache Usage
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache_use_JPA">1.2.1. Using the JPA standard Cache interface</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_use_openJPA">1.2.2. Using the OpenJPA StoreCache extensions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_statistics">1.3.
Cache Statistics
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_query">1.4.
Query Cache
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_extension">1.5.
Cache Extension
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_notes">1.6.
Important Notes
</a></span></dt><dt><span class="section"><a href="#datastore_cache_issues">1.7.
Known Issues and Limitations
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_querycomp">2.
Query Compilation Cache
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_querysql">3. Prepared SQL Cache</a></span></dt></dl></dd><dt><span class="chapter"><a href="#ref_guide_encryption">11.
Encryption Provider
</a></span></dt><dt><span class="chapter"><a href="#ref_guide_remote">12.
Remote and Offline Operation
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach">1.
Detach and Attach
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach_behavior">1.1.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_attach_behavior">1.2.
Attach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_graph">1.3.
Defining the Detached Object Graph
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach_state">1.3.1.
Detached State
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_field">1.3.2.
Detached State Field
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_event">2.
Remote Event Notification Framework
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_event_conf">2.1.
Remote Commit Provider Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_event_conf_jms">2.1.1.
JMS
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_tcp">2.1.2.
TCP
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_common">2.1.3.
Common Properties
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_event_customization">2.2.
Customization
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_slice">13.
Slice: Distributed Persistence
</a></span></dt><dd><dl><dt><span class="section"><a href="#slice_overview">1. Overview</a></span></dt><dt><span class="section"><a href="#features_and_limitations">2. Salient Features</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e16891">2.1. Transparency</a></span></dt><dt><span class="section"><a href="#d5e16897">2.2. Scaling</a></span></dt><dt><span class="section"><a href="#d5e16903">2.3. Distributed Query</a></span></dt><dt><span class="section"><a href="#d5e16926">2.4. Data Distribution</a></span></dt><dt><span class="section"><a href="#d5e16945">2.5. Data Replication</a></span></dt><dt><span class="section"><a href="#d5e16954">2.6. Heterogeneous Database</a></span></dt><dt><span class="section"><a href="#d5e16957">2.7. Distributed Transaction</a></span></dt><dt><span class="section"><a href="#collocation_constraint">2.8. Collocation Constraint</a></span></dt></dl></dd><dt><span class="section"><a href="#slice_configuration">3. Usage</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e16974">3.1. How to activate Slice Runtime?</a></span></dt><dt><span class="section"><a href="#d5e16978">3.2. How to configure each database slice?</a></span></dt><dt><span class="section"><a href="#distribution_policy">3.3. Implement DistributionPolicy interface</a></span></dt><dt><span class="section"><a href="#replication_policy">3.4. Implement ReplicationPolicy interface</a></span></dt></dl></dd><dt><span class="section"><a href="#d5e17032">4. Configuration Properties</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e17037">4.1. Global Properties</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e17039">4.1.1. openjpa.slice.DistributionPolicy</a></span></dt><dt><span class="section"><a href="#d5e17045">4.1.2. openjpa.slice.Lenient</a></span></dt><dt><span class="section"><a href="#d5e17052">4.1.3. openjpa.slice.Master</a></span></dt><dt><span class="section"><a href="#d5e17060">4.1.4. openjpa.slice.Names</a></span></dt><dt><span class="section"><a href="#d5e17068">4.1.5. openjpa.slice.ThreadingPolicy</a></span></dt><dt><span class="section"><a href="#d5e17094">4.1.6. openjpa.slice.TransactionPolicy</a></span></dt></dl></dd><dt><span class="section"><a href="#d5e17112">4.2. Per-Slice Properties</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_integration">14.
Third Party Integration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_ant">1.
Apache Ant
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_conf">1.1.
Common Ant Configuration Options
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_enhance">1.2.
Enhancer Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_appidtool">1.3.
Application Identity Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_mappingtool">1.4.
Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_revmappingtool">1.5.
Reverse Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_schematool">1.6.
Schema Tool Ant Task
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_integration_dbcp">2.
Apache Commons DBCP
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_dbcp_conf">2.1.
Apache Commons DBCP Configuration Options
</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#ref_guide_optimization">15.
Optimization Guidelines
</a></span></dt><dt><span class="chapter"><a href="#ref_guide_instrumentation">16.
Instrumentation
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_instrumentation_config">1.
Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_instrumentation_config_jmx">1.1.
JMX Platform MBean Enablement
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_instrumentation_custom">2.
Custom Providers and Instruments
</a></span></dt></dl></dd></dl></div>
<div class="chapter" id="ref_guide_intro"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;1.&nbsp;
Introduction
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_intro_audience">1.
Intended Audience
</a></span></dt></dl></div>
<p>
OpenJPA is a JDBC-based implementation of the JPA standard.
This document is a reference for the configuration and use of OpenJPA.
</p>
<div class="section" id="ref_guide_intro_audience"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Intended Audience
</h2></div></div></div>
<p>
This document is intended for OpenJPA developers. It
assumes strong knowledge of Java, familiarity with the eXtensible Markup
Language (XML), and an understanding of JPA. If you are not familiar with JPA,
please read the <a class="link" href="#jpa_overview_intro" title="Chapter&nbsp;1.&nbsp; Introduction">JPA Overview</a> before
proceeding.
</p>
<p>
Certain sections of this guide cover advanced topics such as custom
object-relational mapping, enterprise integration, and using OpenJPA with
third-party tools. These sections assume prior experience with the relevant
subject.
</p>
</div>
</div>
<div class="chapter" id="ref_guide_conf"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;2.&nbsp;
Configuration
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_conf_intro">1.
Introduction
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_specify">2.
Runtime Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_devtools">3.
Command Line Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_conf_devtools_format">3.1.
Code Formatting
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_conf_plugins">4.
Plugin Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_conf_openjpa">5.
OpenJPA Properties
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa.AutoClear">5.1.
openjpa.AutoClear
</a></span></dt><dt><span class="section"><a href="#openjpa.AutoDetach">5.2.
openjpa.AutoDetach
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerFactory">5.3.
openjpa.BrokerFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerImpl">5.4.
openjpa.BrokerImpl
</a></span></dt><dt><span class="section"><a href="#openjpa.Callbacks">5.5. openjpa.Callbacks</a></span></dt><dt><span class="section"><a href="#openjpa.ClassResolver">5.6.
openjpa.ClassResolver
</a></span></dt><dt><span class="section"><a href="#openjpa.Compatibility">5.7.
openjpa.Compatibility
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionDriverName">5.8.
openjpa.ConnectionDriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2DriverName">5.9.
openjpa.Connection2DriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory">5.10.
openjpa.ConnectionFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2">5.11.
openjpa.ConnectionFactory2
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryName">5.12.
openjpa.ConnectionFactoryName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Name">5.13.
openjpa.ConnectionFactory2Name
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryMode">5.14.
openjpa.ConnectionFactoryMode
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryProperties">5.15.
openjpa.ConnectionFactoryProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Properties">5.16.
openjpa.ConnectionFactory2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionPassword">5.17.
openjpa.ConnectionPassword
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Password">5.18.
openjpa.Connection2Password
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionProperties">5.19.
openjpa.ConnectionProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Properties">5.20.
openjpa.Connection2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionURL">5.21.
openjpa.ConnectionURL
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2URL">5.22.
openjpa.Connection2URL
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionUserName">5.23.
openjpa.ConnectionUserName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2UserName">5.24.
openjpa.Connection2UserName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionRetainMode">5.25.
openjpa.ConnectionRetainMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCache">5.26.
openjpa.DataCache
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheManager">5.27.
openjpa.DataCacheManager
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheMode">5.28.
openjpa.DataCacheMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheTimeout">5.29.
openjpa.DataCacheTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.DetachState">5.30.
openjpa.DetachState
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicDataStructs">5.31.
openjpa.DynamicDataStructs
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicEnhancementAgent">5.32. openjpa.DynamicEnhancementAgent</a></span></dt><dt><span class="section"><a href="#openjpa.FetchBatchSize">5.33.
openjpa.FetchBatchSize
</a></span></dt><dt><span class="section"><a href="#openjpa.EncryptionProvider">5.34.
openjpa.EncryptionProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.FetchGroups">5.35.
openjpa.FetchGroups
</a></span></dt><dt><span class="section"><a href="#openjpa.FlushBeforeQueries">5.36.
openjpa.FlushBeforeQueries
</a></span></dt><dt><span class="section"><a href="#openjpa.IgnoreChanges">5.37.
openjpa.IgnoreChanges
</a></span></dt><dt><span class="section"><a href="#openjpa.Id">5.38. openjpa.Id</a></span></dt><dt><span class="section"><a href="#openjpa.InitializeEagerly">5.39.
openjpa.InitializeEagerly
</a></span></dt><dt><span class="section"><a href="#openjpa.Instrumentation">5.40.
openjpa.Instrumentation
</a></span></dt><dt><span class="section"><a href="#openjpa.InverseManager">5.41.
openjpa.InverseManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockManager">5.42.
openjpa.LockManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockTimeout">5.43.
openjpa.LockTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.Log">5.44.
openjpa.Log
</a></span></dt><dt><span class="section"><a href="#openjpa.ManagedRuntime">5.45.
openjpa.ManagedRuntime
</a></span></dt><dt><span class="section"><a href="#openjpa.Mapping">5.46.
openjpa.Mapping
</a></span></dt><dt><span class="section"><a href="#openjpa.MaxFetchDepth">5.47.
openjpa.MaxFetchDepth
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataFactory">5.48.
openjpa.MetaDataFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataRepository">5.49.
openjpa.MetaDataRepository
</a></span></dt><dt><span class="section"><a href="#openjpa.Multithreaded">5.50.
openjpa.Multithreaded
</a></span></dt><dt><span class="section"><a href="#openjpa.Optimistic">5.51.
openjpa.Optimistic
</a></span></dt><dt><span class="section"><a href="#openjpa.OptimizeIdCopy">5.52.
openjpa.OptimizeIdCopy
</a></span></dt><dt><span class="section"><a href="#openjpa.OrphanedKeyAction">5.53.
openjpa.OrphanedKeyAction
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalRead">5.54.
openjpa.NontransactionalRead
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalWrite">5.55.
openjpa.NontransactionalWrite
</a></span></dt><dt><span class="section"><a href="#openjpa.ProxyManager">5.56.
openjpa.ProxyManager
</a></span></dt><dt><span class="section"><a href="#openjpa.PostLoadOnMerge">5.57.
openjpa.PostLoadOnMerge
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCache">5.58.
openjpa.QueryCache
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCompilationCache">5.59.
openjpa.QueryCompilationCache
</a></span></dt><dt><span class="section"><a href="#openjpa.ReadLockLevel">5.60.
openjpa.ReadLockLevel
</a></span></dt><dt><span class="section"><a href="#openjpa.RemoteCommitProvider">5.61.
openjpa.RemoteCommitProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.RestoreState">5.62.
openjpa.RestoreState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetainState">5.63.
openjpa.RetainState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetryClassRegistration">5.64.
openjpa.RetryClassRegistration
</a></span></dt><dt><span class="section"><a href="#openjpa.RuntimeUnenhancedClasses">5.65. openjpa.RuntimeUnenhancedClasses</a></span></dt><dt><span class="section"><a href="#openjpa.SavepointManager">5.66.
openjpa.SavepointManager
</a></span></dt><dt><span class="section"><a href="#openjpa.Sequence">5.67.
openjpa.Sequence
</a></span></dt><dt><span class="section"><a href="#openjpa.Specification">5.68.
openjpa.Specification
</a></span></dt><dt><span class="section"><a href="#openjpa.TransactionMode">5.69.
openjpa.TransactionMode
</a></span></dt><dt><span class="section"><a href="#openjpa.UseTCCLinSelectNew">5.70.
openjpa.UseTCCLinSelectNew
</a></span></dt><dt><span class="section"><a href="#openjpa.WriteLockLevel">5.71.
openjpa.WriteLockLevel
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_conf_jdbc">6.
OpenJPA JDBC Properties
</a></span></dt><dd><dl><dt><span class="section"><a href="#openjpa.jdbc.ConnectionDecorators">6.1.
openjpa.jdbc.ConnectionDecorators
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DBDictionary">6.2.
openjpa.jdbc.DBDictionary
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DriverDataSource">6.3.
openjpa.jdbc.DriverDataSource
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.EagerFetchMode">6.4.
openjpa.jdbc.EagerFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.FetchDirection">6.5.
openjpa.jdbc.FetchDirection
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.JDBCListeners">6.6.
openjpa.jdbc.JDBCListeners
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.LRSSize">6.7.
openjpa.jdbc.LRSSize
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingDefaults">6.8.
openjpa.jdbc.MappingDefaults
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingFactory">6.9.
openjpa.jdbc.MappingFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.QuerySQLCache">6.10.
openjpa.jdbc.QuerySQLCache
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.ResultSetType">6.11.
openjpa.jdbc.ResultSetType
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schema">6.12.
openjpa.jdbc.Schema
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SchemaFactory">6.13.
openjpa.jdbc.SchemaFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schemas">6.14.
openjpa.jdbc.Schemas
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SQLFactory">6.15.
openjpa.jdbc.SQLFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SubclassFetchMode">6.16.
openjpa.jdbc.SubclassFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SynchronizeMappings">6.17.
openjpa.jdbc.SynchronizeMappings
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.TransactionIsolation">6.18.
openjpa.jdbc.TransactionIsolation
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.UpdateManager">6.19.
openjpa.jdbc.UpdateManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_spec_compatibility">6.20. Compatibility with Specification</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e6704"></a>
<div class="section" id="ref_guide_conf_intro"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Introduction
</h2></div></div></div>
<p>
This chapter describes the OpenJPA configuration framework. It concludes with
descriptions of all the configuration properties recognized by OpenJPA. You may
want to browse these properties now, but it is not necessary. Most of them will
be referenced later in the documentation as we explain the various features they
apply to.
</p>
</div>
<div class="section" id="ref_guide_conf_specify"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Runtime Configuration
</h2></div></div></div>
<a class="indexterm" name="d5e6711"></a>
<p>
The OpenJPA runtime includes a comprehensive system of configuration defaults
and overrides:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e6718"></a>
OpenJPA first looks for an optional <code class="filename">openjpa.xml</code> resource.
OpenJPA searches for this resource in each top-level directory of your <code class="literal">
CLASSPATH</code>. OpenJPA will also find the resource if you place it within
a <code class="filename">META-INF</code> directory in any top-level directory of the
<code class="literal">CLASSPATH</code>. The <code class="filename">openjpa.xml</code> resource
contains property settings in <a class="link" href="#jpa_overview_persistence_xml" title="1.&nbsp; persistence.xml">
JPA's XML format</a>.
</p>
</li><li class="listitem">
<p>
You can customize the name or location of the above resource by specifying the
correct resource path in the <code class="literal">openjpa.properties</code> System
property.
</p>
</li><li class="listitem">
<p>
You can override any value defined in the above resource by setting the System
property of the same name to the desired value.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e6733"></a>
In JPA, the values in the standard <code class="filename"> META-INF/persistence.xml
</code> bootstrapping file used by the
<a class="link" href="#jpa_overview_persistence" title="Chapter&nbsp;6.&nbsp; Persistence"><code class="classname">Persistence</code>
</a> class at runtime override the values in the above resource, as well as
any System property settings. The <code class="classname">Map</code> passed to
<code class="methodname">Persistence.createEntityManagerFactory</code> at runtime also
overrides previous settings, including properties defined in <code class="filename">
persistence.xml</code>.
</p>
</li><li class="listitem">
<p>
In JPA, The <code class="classname">Map</code> passed to the methods defined in the
<code class="classname">Query</code> and <code class="classname">EntityManager</code> interfaces
at runtime also overrides previous settings, including properties defined in
<code class="filename">persistence.xml</code>. The <code class="classname">Map</code> is in
effect only during the method invocation.
</p>
</li><li class="listitem">
<p>
When using JCA deployment the <code class="literal">config-property</code> values in your
<code class="filename">ra.xml</code> file override other settings.
</p>
</li><li class="listitem">
<p>
All OpenJPA command-line tools accept flags that allow you to specify the
configuration resource to use, and to override any property.
<a class="xref" href="#ref_guide_conf_devtools" title="3.&nbsp; Command Line Configuration">Section&nbsp;3, &#8220;
Command Line Configuration
&#8221;</a> describes these flags.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Internally, the OpenJPA runtime environment and development
tools manipulate property settings through a general
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/conf/Configuration.html" target="_top">
<code class="classname">Configuration</code></a> interface, and in particular its
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html" target="_top">
<code class="classname">OpenJPAConfiguration</code></a> and
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html" target="_top">
<code class="classname">JDBCConfiguration</code></a> subclasses. For advanced
customization, OpenJPA's extended runtime interfaces and its development tools
allow you to access these interfaces directly. See the <a class="ulink" href="../../apidocs/" target="_top">
Javadoc</a> for details.
</p>
</div>
</div>
<div class="section" id="ref_guide_conf_devtools"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Command Line Configuration
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_conf_devtools_format">3.1.
Code Formatting
</a></span></dt></dl></div>
<a class="indexterm" name="d5e6767"></a>
<p>
OpenJPA development tools share the same set of configuration defaults and
overrides as the runtime system. They also allow you to specify property values
on the command line:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-properties/-p &lt;configuration file or resource&gt;</code>: Use
the <code class="literal">-properties</code> flag, or its shorter <code class="literal">-p</code>
form, to specify a configuration file to use. Note that OpenJPA always searches
the default file locations described above, so this flag is only needed when you
do not have a default resource in place, or when you wish to override the
defaults. The given value can be the path to a file, or the resource name of a
file somewhere in the <code class="literal">CLASSPATH</code>. OpenJPA will search the
given location as well as the location prefixed by <code class="filename"> META-INF/
</code>. Thus, to point an OpenJPA tool at <code class="filename">
META-INF/my-persistence.xml</code>, you can use:
</p>
<pre class="programlisting">
&lt;tool&gt; -p my-persistence.xml
</pre>
<p>
If you want to run a tool against just one particular persistence unit in
a configuration file, you can do so by specifying an anchor along with the
resource. If you do not specify an anchor, the tools will run against all
the persistence units defined within the specified resource, or the default
resource if none is specified. If the persistence unit is defined within
the default resource location, then you can just specify the raw anchor itself:
</p>
<pre class="programlisting">
&lt;tool&gt; -p my-persistence.xml#sales-persistence-unit
&lt;tool&gt; -p #invoice-persistence-unit
</pre>
</li><li class="listitem">
<p>
<code class="literal">-&lt;property name&gt; &lt;property value&gt;</code>: Any
configuration property that you can specify in a configuration file can be
overridden with a command line flag. The flag name is always the last token of
the corresponding property name, with the first letter in either upper or lower
case. For example, to override the <code class="literal">openjpa.ConnectionUserName</code>
property, you could pass the <code class="literal">-connectionUserName &lt;value&gt;
</code> flag to any tool. Values set this way override both the values in the
configuration file and values set via System properties.
</p>
</li></ul></div>
<div class="section" id="ref_guide_conf_devtools_format"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;
Code Formatting
</h3></div></div></div>
<a class="indexterm" name="d5e6790"></a>
<p>
Some OpenJPA development tools generate Java code. These tools share a common
set of command-line flags for formatting their output to match your coding
style. All code formatting flags can begin with either the <code class="literal">codeFormat
</code> or <code class="literal">cf</code> prefix.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-codeFormat./-cf.tabSpaces &lt;spaces&gt;</code>: The number of
spaces that make up a tab, or 0 to use tab characters. Defaults to using tab
characters.
</p>
</li><li class="listitem">
<p>
<code class="literal">-codeFormat./-cf.spaceBeforeParen &lt;true/t | false/f&gt;</code>:
Whether or not to place a space before opening parentheses on method calls, if
statements, loops, etc. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-codeFormat./-cf.spaceInParen &lt;true/t | false/f&gt;</code>:
Whether or not to place a space within parentheses; i.e. <code class="literal">method( arg)
</code>. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-codeFormat./-cf.braceOnSameLine &lt;true/t | false/f&gt;</code>:
Whether or not to place opening braces on the same line as the declaration that
begins the code block, or on the next line. Defaults to <code class="literal">true</code>
.
</p>
</li><li class="listitem">
<p>
<code class="literal">-codeFormat./-cf.braceAtSameTabLevel &lt;true/t | false/f&gt;</code>
: When the <code class="literal">braceOnSameLine</code> option is disabled, you can choose
whether to place the brace at the same tab level of the contained code. Defaults
to <code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-codeFormat./-cf.scoreBeforeFieldName &lt;true/t | false/f&gt;
</code>: Whether to prefix an underscore to names of private member
variables. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-codeFormat./-cf.linesBetweenSections &lt;lines&gt;</code>: The
number of lines to skip between sections of code. Defaults to 1.
</p>
</li></ul></div>
<div class="example" id="ref_guide_conf_devtools_format_ex"><p class="title"><b>Example&nbsp;2.1.&nbsp;
Code Formatting with the Application Id Tool
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.enhance.ApplicationIdTool -cf.spaceBeforeParen true -cf.tabSpaces 4
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_conf_plugins"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Plugin Configuration
</h2></div></div></div>
<a class="indexterm" name="d5e6829"></a>
<a class="indexterm" name="d5e6832"></a>
<p>
Because OpenJPA is a highly customizable environment, many configuration
properties relate to the creation and configuration of system plugins. Plugin
properties have a syntax very similar to that of Java annotations. They allow
you to specify both what class to use for the plugin and how to configure the
public fields or bean properties of the instantiated plugin instance. The
easiest way to describe the plugin syntax is by example:
</p>
<p>
OpenJPA has a pluggable L2 caching mechanism that is controlled by the <code class="literal">
openjpa.DataCache</code> configuration property. Suppose that you have
created a new class, <code class="classname">com.xyz.MyDataCache</code>, that you want
OpenJPA to use for caching. You've made instances of <code class="literal">MyDataCache
</code> configurable via two methods, <code class="methodname">setCacheSize(int size)
</code> and <code class="methodname">setRemoteHost(String host)</code>. The
sample below shows how you would tell OpenJPA to use an instance of your custom
plugin with a max size of 1000 and a remote host of <code class="literal">cacheserver
</code>.
</p>
<pre class="programlisting">
&lt;property name="openjpa.DataCache"
value="com.xyz.MyDataCache(CacheSize=1000, RemoteHost=cacheserver)"/&gt;
</pre>
<p>
As you can see, plugin properties take a class name, followed by a
comma-separated list of values for the plugin's public fields or bean properties
in parentheses. OpenJPA will match each named property to a field or setter
method in the instantiated plugin instance, and set the field or invoke the
method with the given value (after converting the value to the right type, of
course). The first letter of the property names can be in either upper or lower
case. The following would also have been valid:
</p>
<pre class="programlisting">
com.xyz.MyDataCache(cacheSize=1000, remoteHost=cacheserver)
</pre>
<p>
If you do not need to pass any property settings to a plugin, you can just name
the class to use:
</p>
<pre class="programlisting">
com.xyz.MyDataCache
</pre>
<p>
Similarly, if the plugin has a default class that you do not want to change, you
can simply specify a list of property settings, without a class name. For
example, OpenJPA's query cache companion to the data cache has a default
implementation suitable to most users, but you still might want to change the
query cache's size. It has a <code class="literal">CacheSize</code> property for this
purpose:
</p>
<pre class="programlisting">
CacheSize=1000
</pre>
<p>
Finally, many of OpenJPA's built-in options for plugins have short alias names
that you can use in place of the full class name. The data cache property, for
example, has an available alias of <code class="literal">true</code> for the standard
cache implementation. The property value simply becomes:
</p>
<pre class="programlisting">
true
</pre>
<p>
The standard cache implementation class also has a <code class="literal">CacheSize</code>
property, so to use the standard implementation and configure the size, specify:
</p>
<pre class="programlisting">
true(CacheSize=1000)
</pre>
<p>
The remainder of this chapter reviews the set of configuration properties
OpenJPA recognizes.
</p>
</div>
<div class="section" id="ref_guide_conf_openjpa"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
OpenJPA Properties
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#openjpa.AutoClear">5.1.
openjpa.AutoClear
</a></span></dt><dt><span class="section"><a href="#openjpa.AutoDetach">5.2.
openjpa.AutoDetach
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerFactory">5.3.
openjpa.BrokerFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.BrokerImpl">5.4.
openjpa.BrokerImpl
</a></span></dt><dt><span class="section"><a href="#openjpa.Callbacks">5.5. openjpa.Callbacks</a></span></dt><dt><span class="section"><a href="#openjpa.ClassResolver">5.6.
openjpa.ClassResolver
</a></span></dt><dt><span class="section"><a href="#openjpa.Compatibility">5.7.
openjpa.Compatibility
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionDriverName">5.8.
openjpa.ConnectionDriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2DriverName">5.9.
openjpa.Connection2DriverName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory">5.10.
openjpa.ConnectionFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2">5.11.
openjpa.ConnectionFactory2
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryName">5.12.
openjpa.ConnectionFactoryName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Name">5.13.
openjpa.ConnectionFactory2Name
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryMode">5.14.
openjpa.ConnectionFactoryMode
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactoryProperties">5.15.
openjpa.ConnectionFactoryProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionFactory2Properties">5.16.
openjpa.ConnectionFactory2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionPassword">5.17.
openjpa.ConnectionPassword
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Password">5.18.
openjpa.Connection2Password
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionProperties">5.19.
openjpa.ConnectionProperties
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2Properties">5.20.
openjpa.Connection2Properties
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionURL">5.21.
openjpa.ConnectionURL
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2URL">5.22.
openjpa.Connection2URL
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionUserName">5.23.
openjpa.ConnectionUserName
</a></span></dt><dt><span class="section"><a href="#openjpa.Connection2UserName">5.24.
openjpa.Connection2UserName
</a></span></dt><dt><span class="section"><a href="#openjpa.ConnectionRetainMode">5.25.
openjpa.ConnectionRetainMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCache">5.26.
openjpa.DataCache
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheManager">5.27.
openjpa.DataCacheManager
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheMode">5.28.
openjpa.DataCacheMode
</a></span></dt><dt><span class="section"><a href="#openjpa.DataCacheTimeout">5.29.
openjpa.DataCacheTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.DetachState">5.30.
openjpa.DetachState
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicDataStructs">5.31.
openjpa.DynamicDataStructs
</a></span></dt><dt><span class="section"><a href="#openjpa.DynamicEnhancementAgent">5.32. openjpa.DynamicEnhancementAgent</a></span></dt><dt><span class="section"><a href="#openjpa.FetchBatchSize">5.33.
openjpa.FetchBatchSize
</a></span></dt><dt><span class="section"><a href="#openjpa.EncryptionProvider">5.34.
openjpa.EncryptionProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.FetchGroups">5.35.
openjpa.FetchGroups
</a></span></dt><dt><span class="section"><a href="#openjpa.FlushBeforeQueries">5.36.
openjpa.FlushBeforeQueries
</a></span></dt><dt><span class="section"><a href="#openjpa.IgnoreChanges">5.37.
openjpa.IgnoreChanges
</a></span></dt><dt><span class="section"><a href="#openjpa.Id">5.38. openjpa.Id</a></span></dt><dt><span class="section"><a href="#openjpa.InitializeEagerly">5.39.
openjpa.InitializeEagerly
</a></span></dt><dt><span class="section"><a href="#openjpa.Instrumentation">5.40.
openjpa.Instrumentation
</a></span></dt><dt><span class="section"><a href="#openjpa.InverseManager">5.41.
openjpa.InverseManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockManager">5.42.
openjpa.LockManager
</a></span></dt><dt><span class="section"><a href="#openjpa.LockTimeout">5.43.
openjpa.LockTimeout
</a></span></dt><dt><span class="section"><a href="#openjpa.Log">5.44.
openjpa.Log
</a></span></dt><dt><span class="section"><a href="#openjpa.ManagedRuntime">5.45.
openjpa.ManagedRuntime
</a></span></dt><dt><span class="section"><a href="#openjpa.Mapping">5.46.
openjpa.Mapping
</a></span></dt><dt><span class="section"><a href="#openjpa.MaxFetchDepth">5.47.
openjpa.MaxFetchDepth
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataFactory">5.48.
openjpa.MetaDataFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.MetaDataRepository">5.49.
openjpa.MetaDataRepository
</a></span></dt><dt><span class="section"><a href="#openjpa.Multithreaded">5.50.
openjpa.Multithreaded
</a></span></dt><dt><span class="section"><a href="#openjpa.Optimistic">5.51.
openjpa.Optimistic
</a></span></dt><dt><span class="section"><a href="#openjpa.OptimizeIdCopy">5.52.
openjpa.OptimizeIdCopy
</a></span></dt><dt><span class="section"><a href="#openjpa.OrphanedKeyAction">5.53.
openjpa.OrphanedKeyAction
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalRead">5.54.
openjpa.NontransactionalRead
</a></span></dt><dt><span class="section"><a href="#openjpa.NontransactionalWrite">5.55.
openjpa.NontransactionalWrite
</a></span></dt><dt><span class="section"><a href="#openjpa.ProxyManager">5.56.
openjpa.ProxyManager
</a></span></dt><dt><span class="section"><a href="#openjpa.PostLoadOnMerge">5.57.
openjpa.PostLoadOnMerge
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCache">5.58.
openjpa.QueryCache
</a></span></dt><dt><span class="section"><a href="#openjpa.QueryCompilationCache">5.59.
openjpa.QueryCompilationCache
</a></span></dt><dt><span class="section"><a href="#openjpa.ReadLockLevel">5.60.
openjpa.ReadLockLevel
</a></span></dt><dt><span class="section"><a href="#openjpa.RemoteCommitProvider">5.61.
openjpa.RemoteCommitProvider
</a></span></dt><dt><span class="section"><a href="#openjpa.RestoreState">5.62.
openjpa.RestoreState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetainState">5.63.
openjpa.RetainState
</a></span></dt><dt><span class="section"><a href="#openjpa.RetryClassRegistration">5.64.
openjpa.RetryClassRegistration
</a></span></dt><dt><span class="section"><a href="#openjpa.RuntimeUnenhancedClasses">5.65. openjpa.RuntimeUnenhancedClasses</a></span></dt><dt><span class="section"><a href="#openjpa.SavepointManager">5.66.
openjpa.SavepointManager
</a></span></dt><dt><span class="section"><a href="#openjpa.Sequence">5.67.
openjpa.Sequence
</a></span></dt><dt><span class="section"><a href="#openjpa.Specification">5.68.
openjpa.Specification
</a></span></dt><dt><span class="section"><a href="#openjpa.TransactionMode">5.69.
openjpa.TransactionMode
</a></span></dt><dt><span class="section"><a href="#openjpa.UseTCCLinSelectNew">5.70.
openjpa.UseTCCLinSelectNew
</a></span></dt><dt><span class="section"><a href="#openjpa.WriteLockLevel">5.71.
openjpa.WriteLockLevel
</a></span></dt></dl></div>
<a class="indexterm" name="d5e6860"></a>
<p>
OpenJPA defines many configuration properties. Most of these properties are
provided for advanced users who wish to customize OpenJPA's behavior; the
majority of developers can omit them. The following properties apply to any
OpenJPA back-end, though the given descriptions are tailored to OpenJPA's
default JDBC store.
</p>
<p>
A few of the properties recognized by OpenJPA have been standardized in JPA 2.0
specification using equivalent names. These properties can be specified either
by the JPA standard key or equivalent OpenJPA key. Specifying the same key once
as JPA standard key and again as equivalent OpenJPA key in the same configuration,
however, is not allowed. The following table lists these standard JPA properties
and their OpenJPA equivalent.
</p>
<div class="table" id="d5e6865"><p class="title"><b>Table&nbsp;2.1.&nbsp;
Standard JPA Properties and OpenJPA equivalents
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Standard JPA Properties and OpenJPA equivalents&#xA; " border="1"><colgroup><col align="left" class="StandardJPA"><col align="left" class="OpenJPAEquivalent"></colgroup><thead><tr><th align="left">Standard JPA 2.0</th><th align="left">OpenJPA Equivalent</th></tr></thead><tbody><tr><td align="left">javax.persistence.jdbc.driver</td><td align="left">openjpa.ConnectionDriverName</td></tr><tr><td align="left">javax.persistence.jdbc.url</td><td align="left">openjpa.ConnectionURL</td></tr><tr><td align="left">javax.persistence.jdbc.user</td><td align="left">openjpa.ConnectionUserName</td></tr><tr><td align="left">javax.persistence.jdbc.password</td><td align="left">openjpa.ConnectionPassword</td></tr></tbody></table>
</div></div><br class="table-break">
<div class="section" id="openjpa.AutoClear"><div class="titlepage"><div><div><h3 class="title">5.1.&nbsp;
openjpa.AutoClear
</h3></div></div></div>
<a class="indexterm" name="d5e6889"></a>
<a class="indexterm" name="d5e6891"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.AutoClear
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getAutoClear()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getAutoClear
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
AutoClear</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">datastore</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">datastore</code>,
<code class="literal">all</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> When to automatically clear
instance state: on entering a datastore transaction, or on entering any
transaction.
</p>
</div>
<div class="section" id="openjpa.AutoDetach"><div class="titlepage"><div><div><h3 class="title">5.2.&nbsp;
openjpa.AutoDetach
</h3></div></div></div>
<a class="indexterm" name="d5e6916"></a>
<a class="indexterm" name="d5e6918"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.AutoDetach
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getAutoDetach()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getAutoDetach
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
AutoDetach</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> - null
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">close</code>,
<code class="literal">commit</code>, <code class="literal">nontx-read</code>, <code class="literal">rollback</code>, <code class="literal">none</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A comma-separated list of events
when managed instances will be automatically detached. When using the OpenJPA EntityManager this defaults to
<code class="literal">close</code>, and <code class="literal">rollback</code> per the JPA spec. If you need to change this setting, you
need to set it directly on an instantiated EntityManager.
</p>
<p>
<code class="literal">none</code> option is exclusive. It can not be specified with any other option.
<code class="literal">none</code> option implies that managed objects will not be detached from the persistence context,
the second-class object fields such as collections or date will <span class="emphasis"><em>not</em></span> be proxied unlike normal
circumstances. This option is relevant for specific use cases where the user application would not refer to the
managed objects after the transaction and/or the context ends e.g. typical batch insertion scenario.
</p>
</div>
<div class="section" id="openjpa.BrokerFactory"><div class="titlepage"><div><div><h3 class="title">5.3.&nbsp;
openjpa.BrokerFactory
</h3></div></div></div>
<a class="indexterm" name="d5e6951"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.BrokerFactory
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getBrokerFactory()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getBrokerFactory
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
BrokerFactory</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">jdbc</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">jdbc</code>,
<code class="literal">abstractstore</code>, <code class="literal">remote</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/BrokerFactory.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.BrokerFactory</code></a> type to
use.
</p>
</div>
<div class="section" id="openjpa.BrokerImpl"><div class="titlepage"><div><div><h3 class="title">5.4.&nbsp;
openjpa.BrokerImpl
</h3></div></div></div>
<a class="indexterm" name="d5e6978"></a>
<a class="indexterm" name="d5e6980"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.BrokerImpl
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getBrokerImpl()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getBrokerImpl
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
BrokerImpl</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">default</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/Broker.html" target="_top"><code class="classname">
org.apache.openjpa.kernel.Broker</code></a> type to use at runtime. See
<a class="xref" href="#ref_guide_runtime_broker_extension" title="1.2.&nbsp; Broker Customization and Eviction">Section&nbsp;1.2, &#8220;
Broker Customization and Eviction
&#8221;</a> on for details.
</p>
</div>
<div class="section" id="openjpa.Callbacks"><div class="titlepage"><div><div><h3 class="title">5.5.&nbsp;openjpa.Callbacks</h3></div></div></div>
<a class="indexterm" name="d5e7004"></a>
<a class="indexterm" name="d5e7006"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Callbacks</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getCallbackOptionsInstance()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getCallbackOptionsInstance</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">Callbacks</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">default</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) to fine tune some of the configurable
properties related to callbacks. The plug-in supports two boolean properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p><code class="literal">PostPersistCallbackImmediate</code>: whether the
post-persist callback is invoked as soon as a new instance
is managed. The default is <code class="literal">false</code>, implies that
the post-persist callback is invoked after the instance been committed
or flushed to the datastore.
</p>
</li><li class="listitem">
<p><code class="literal">AllowsMultipleMethodsForSameCallback</code>: whether
multiple methods of the same class can handle the same callback event.
Defaults to <code class="literal">false</code>.
</p>
</li></ul></div>
</div>
<div class="section" id="openjpa.ClassResolver"><div class="titlepage"><div><div><h3 class="title">5.6.&nbsp;
openjpa.ClassResolver
</h3></div></div></div>
<a class="indexterm" name="d5e7036"></a>
<a class="indexterm" name="d5e7038"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.ClassResolver
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getClassResolver()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getClassResolver
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ClassResolver</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">default</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/util/ClassResolver.html" target="_top"><code class="classname">
org.apache.openjpa.util.ClassResolver</code></a> implementation to use
for class name resolution. You may wish to plug in your own resolver if you have
special classloading needs.
</p>
</div>
<div class="section" id="openjpa.Compatibility"><div class="titlepage"><div><div><h3 class="title">5.7.&nbsp;
openjpa.Compatibility
</h3></div></div></div>
<a class="indexterm" name="d5e7061"></a>
<a class="indexterm" name="d5e7063"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Compatibility
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getCompatibility()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getCompatibility
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Compatibility</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Encapsulates options to mimic the
behavior of previous OpenJPA releases.
</p>
</div>
<div class="section" id="openjpa.ConnectionDriverName"><div class="titlepage"><div><div><h3 class="title">5.8.&nbsp;
openjpa.ConnectionDriverName
</h3></div></div></div>
<a class="indexterm" name="d5e7081"></a>
<a class="indexterm" name="d5e7083"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionDriverName</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionDriverName()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionDriverName
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionDriverName</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The full class name of either the
JDBC <code class="classname">java.sql.Driver</code>, or a <code class="classname">
javax.sql.DataSource</code> implementation to use to connect to the
database. See <a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.Connection2DriverName"><div class="titlepage"><div><div><h3 class="title">5.9.&nbsp;
openjpa.Connection2DriverName
</h3></div></div></div>
<a class="indexterm" name="d5e7105"></a>
<a class="indexterm" name="d5e7107"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.Connection2DriverName</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnection2DriverName()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnection2DriverName
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Connection2DriverName</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> This property is equivalent to the
<code class="literal">openjpa.ConnectionDriverName</code> property described in
<a class="xref" href="#openjpa.ConnectionDriverName" title="5.8.&nbsp; openjpa.ConnectionDriverName">Section&nbsp;5.8, &#8220;
openjpa.ConnectionDriverName
&#8221;</a>, but applies to the
alternate connection factory used for unmanaged connections. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionFactory"><div class="titlepage"><div><div><h3 class="title">5.10.&nbsp;
openjpa.ConnectionFactory
</h3></div></div></div>
<a class="indexterm" name="d5e7129"></a>
<a class="indexterm" name="d5e7131"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionFactory</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionFactory()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionFactory
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionFactory</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A <code class="classname">javax.sql.DataSource
</code> to use to connect to the database. See
<a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionFactory2"><div class="titlepage"><div><div><h3 class="title">5.11.&nbsp;
openjpa.ConnectionFactory2
</h3></div></div></div>
<a class="indexterm" name="d5e7152"></a>
<a class="indexterm" name="d5e7154"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionFactory2</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionFactory2()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionFactory2
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionFactory2</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> An unmanaged <code class="classname">
javax.sql.DataSource</code> to use to connect to the database. See
<a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionFactoryName"><div class="titlepage"><div><div><h3 class="title">5.12.&nbsp;
openjpa.ConnectionFactoryName
</h3></div></div></div>
<a class="indexterm" name="d5e7175"></a>
<a class="indexterm" name="d5e7177"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionFactoryName</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionFactoryName()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionFactoryName
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionFactoryName</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The JNDI location of a <code class="classname">
javax.sql.DataSource</code> to use to connect to the database. See
<a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionFactory2Name"><div class="titlepage"><div><div><h3 class="title">5.13.&nbsp;
openjpa.ConnectionFactory2Name
</h3></div></div></div>
<a class="indexterm" name="d5e7198"></a>
<a class="indexterm" name="d5e7200"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionFactory2Name</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionFactory2Name()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionFactory2Name
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionFactory2Name</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The JNDI location of an unmanaged
<code class="classname">javax.sql.DataSource</code> to use to connect to the database.
See <a class="xref" href="#ref_guide_enterprise_xa" title="3.&nbsp; XA Transactions">Section&nbsp;3, &#8220;
XA Transactions
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionFactoryMode"><div class="titlepage"><div><div><h3 class="title">5.14.&nbsp;
openjpa.ConnectionFactoryMode
</h3></div></div></div>
<a class="indexterm" name="d5e7221"></a>
<a class="indexterm" name="d5e7223"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionFactoryMode</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionFactoryMode()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionFactoryMode
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionFactoryMode</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">local</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">local</code>,
<code class="literal">managed</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The connection factory mode to use
when integrating with the application server's managed transactions. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionFactoryProperties"><div class="titlepage"><div><div><h3 class="title">5.15.&nbsp;
openjpa.ConnectionFactoryProperties
</h3></div></div></div>
<a class="indexterm" name="d5e7248"></a>
<a class="indexterm" name="d5e7250"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionFactoryProperties</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionFactoryProperties()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionFactoryProperties
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionFactoryProperties</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) listing properties for
configuration of the datasource in use. See the
<a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionFactory2Properties"><div class="titlepage"><div><div><h3 class="title">5.16.&nbsp;
openjpa.ConnectionFactory2Properties
</h3></div></div></div>
<a class="indexterm" name="d5e7271"></a>
<a class="indexterm" name="d5e7273"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionFactory2Properties</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionFactory2Properties()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionFactory2Properties
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionFactory2Properties</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> This property is equivalent to the
<code class="literal">openjpa.ConnectionFactoryProperties</code> property described in
<a class="xref" href="#openjpa.ConnectionFactoryProperties" title="5.15.&nbsp; openjpa.ConnectionFactoryProperties">Section&nbsp;5.15, &#8220;
openjpa.ConnectionFactoryProperties
&#8221;</a>, but applies to the
alternate connection factory used for unmanaged connections. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionPassword"><div class="titlepage"><div><div><h3 class="title">5.17.&nbsp;
openjpa.ConnectionPassword
</h3></div></div></div>
<a class="indexterm" name="d5e7295"></a>
<a class="indexterm" name="d5e7297"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionPassword</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionPassword()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionPassword
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionPassword</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The password for the user
specified in the <code class="literal">ConnectionUserName</code> property. See
<a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.Connection2Password"><div class="titlepage"><div><div><h3 class="title">5.18.&nbsp;
openjpa.Connection2Password
</h3></div></div></div>
<a class="indexterm" name="d5e7318"></a>
<a class="indexterm" name="d5e7320"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.Connection2Password</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnection2Password()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnection2Password
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Connection2Password</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> This property is equivalent to the
<code class="literal">openjpa.ConnectionPassword</code> property described in
<a class="xref" href="#openjpa.ConnectionPassword" title="5.17.&nbsp; openjpa.ConnectionPassword">Section&nbsp;5.17, &#8220;
openjpa.ConnectionPassword
&#8221;</a>, but applies to the
alternate connection factory used for unmanaged connections. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionProperties"><div class="titlepage"><div><div><h3 class="title">5.19.&nbsp;
openjpa.ConnectionProperties
</h3></div></div></div>
<a class="indexterm" name="d5e7342"></a>
<a class="indexterm" name="d5e7344"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionProperties</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionProperties()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionProperties
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionProperties</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) listing properties to configure
the driver listed in the <code class="literal">ConnectionDriverName</code> property
described below. See <a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.Connection2Properties"><div class="titlepage"><div><div><h3 class="title">5.20.&nbsp;
openjpa.Connection2Properties
</h3></div></div></div>
<a class="indexterm" name="d5e7366"></a>
<a class="indexterm" name="d5e7368"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.Connection2Properties</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnection2Properties()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnection2Properties
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Connection2Properties</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> This property is equivalent to the
<code class="literal">openjpa.ConnectionProperties</code> property described in
<a class="xref" href="#openjpa.ConnectionProperties" title="5.19.&nbsp; openjpa.ConnectionProperties">Section&nbsp;5.19, &#8220;
openjpa.ConnectionProperties
&#8221;</a>, but applies to the
alternate connection factory used for unmanaged connections. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionURL"><div class="titlepage"><div><div><h3 class="title">5.21.&nbsp;
openjpa.ConnectionURL
</h3></div></div></div>
<a class="indexterm" name="d5e7390"></a>
<a class="indexterm" name="d5e7392"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.ConnectionURL
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionURL()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionURL
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionURL</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The JDBC URL for the database. See
<a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.Connection2URL"><div class="titlepage"><div><div><h3 class="title">5.22.&nbsp;
openjpa.Connection2URL
</h3></div></div></div>
<a class="indexterm" name="d5e7412"></a>
<a class="indexterm" name="d5e7414"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Connection2URL
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnection2URL()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnection2URL
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Connection2URL</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> This property is equivalent to the
<code class="literal">openjpa.ConnectionURL</code> property described in
<a class="xref" href="#openjpa.ConnectionURL" title="5.21.&nbsp; openjpa.ConnectionURL">Section&nbsp;5.21, &#8220;
openjpa.ConnectionURL
&#8221;</a>, but applies to the alternate
connection factory used for unmanaged connections. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionUserName"><div class="titlepage"><div><div><h3 class="title">5.23.&nbsp;
openjpa.ConnectionUserName
</h3></div></div></div>
<a class="indexterm" name="d5e7436"></a>
<a class="indexterm" name="d5e7438"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionUserName</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionUserName()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionUserName
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionUserName</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The user name to use when
connecting to the database. See the <a class="xref" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">Chapter&nbsp;4, <i>
JDBC
</i></a>
for details.
</p>
</div>
<div class="section" id="openjpa.Connection2UserName"><div class="titlepage"><div><div><h3 class="title">5.24.&nbsp;
openjpa.Connection2UserName
</h3></div></div></div>
<a class="indexterm" name="d5e7458"></a>
<a class="indexterm" name="d5e7460"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.Connection2UserName</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnection2UserName()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getConnection2UserName
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Connection2UserName</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> This property is equivalent to the
<code class="literal">openjpa.ConnectionUserName</code> property described in
<a class="xref" href="#openjpa.ConnectionUserName" title="5.23.&nbsp; openjpa.ConnectionUserName">Section&nbsp;5.23, &#8220;
openjpa.ConnectionUserName
&#8221;</a>, but applies to the
alternate connection factory used for unmanaged connections. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ConnectionRetainMode"><div class="titlepage"><div><div><h3 class="title">5.25.&nbsp;
openjpa.ConnectionRetainMode
</h3></div></div></div>
<a class="indexterm" name="d5e7482"></a>
<a class="indexterm" name="d5e7484"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.ConnectionRetainMode</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getConnectionRetainMode()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getConnectionRetainMode
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionRetainMode</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">on-demand</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Controls how OpenJPA uses
datastore connections. This property can also be specified for individual
sessions. See <a class="xref" href="#ref_guide_dbsetup_retain" title="8.&nbsp; Configuring the Use of JDBC Connections">Section&nbsp;8, &#8220;
Configuring the Use of JDBC Connections
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.DataCache"><div class="titlepage"><div><div><h3 class="title">5.26.&nbsp;
openjpa.DataCache
</h3></div></div></div>
<a class="indexterm" name="d5e7505"></a>
<a class="indexterm" name="d5e7507"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.DataCache
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getDataCache()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getDataCache
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DataCache</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin list string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/datacache/DataCache.html" target="_top"><code class="classname">
org.apache.openjpa.datacache.DataCache</code></a>s to use for data
caching. See <a class="xref" href="#ref_guide_cache_conf" title="1.1.&nbsp; Data Cache Configuration">Section&nbsp;1.1, &#8220;
Data Cache Configuration
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.DataCacheManager"><div class="titlepage"><div><div><h3 class="title">5.27.&nbsp;
openjpa.DataCacheManager
</h3></div></div></div>
<a class="indexterm" name="d5e7531"></a>
<a class="indexterm" name="d5e7533"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.DataCacheManager</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getDataCacheManager()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getDataCacheManager
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DataCacheManager</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">default</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/datacache/DataCacheManager.html" target="_top">
<code class="classname">openjpa.datacache.DataCacheManager</code></a> that manages
the system data caches. See <a class="xref" href="#ref_guide_cache" title="1.&nbsp; Data Cache">Section&nbsp;1, &#8220;
Data Cache
&#8221;</a> for details
on data caching.
</p>
</div>
<div class="section" id="openjpa.DataCacheMode"><div class="titlepage"><div><div><h3 class="title">5.28.&nbsp;
openjpa.DataCacheMode
</h3></div></div></div>
<a class="indexterm" name="d5e7557"></a>
<a class="indexterm" name="d5e7559"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.DataCacheMode</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getDataCacheMode()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getDataCacheMode
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DataCacheMode</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">DataCacheMode.UNSPECIFIED (see javadoc for details)</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span>Determines which entities will be included in the DataCache. May be any of the values defined in <a class="ulink" href="../../apidocs/org/apache/openjpa/datacache/DataCacheMode.html" target="_top">../../apidocs/org/apache/openjpa/datacache/DataCacheMode.html</a>.
</p>
</div>
<div class="section" id="openjpa.DataCacheTimeout"><div class="titlepage"><div><div><h3 class="title">5.29.&nbsp;
openjpa.DataCacheTimeout
</h3></div></div></div>
<a class="indexterm" name="d5e7580"></a>
<a class="indexterm" name="d5e7582"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.DataCacheTimeout</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getDataCacheTimeout()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getDataCacheTimeout
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DataCacheTimeout</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">-1</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The number of milliseconds that
data in the data cache is valid. Set this to -1 to indicate that data should not
expire from the cache. This property can also be specified for individual
classes. See <a class="xref" href="#ref_guide_cache_conf" title="1.1.&nbsp; Data Cache Configuration">Section&nbsp;1.1, &#8220;
Data Cache Configuration
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.DetachState"><div class="titlepage"><div><div><h3 class="title">5.30.&nbsp;
openjpa.DetachState
</h3></div></div></div>
<a class="indexterm" name="d5e7603"></a>
<a class="indexterm" name="d5e7605"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.DetachState
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfigurationImpl.html#getDetachState()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfigurationImpl.getDetachState
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DetachState</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">loaded</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">loaded</code>,
<code class="literal">fetch-groups</code>, <code class="literal">all</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Determines which fields are part
of the detached graph and related options. For more details, see
<a class="xref" href="#ref_guide_detach_graph" title="1.3.&nbsp; Defining the Detached Object Graph">Section&nbsp;1.3, &#8220;
Defining the Detached Object Graph
&#8221;</a>.
</p>
</div>
<div class="section" id="openjpa.DynamicDataStructs"><div class="titlepage"><div><div><h3 class="title">5.31.&nbsp;
openjpa.DynamicDataStructs
</h3></div></div></div>
<a class="indexterm" name="d5e7632"></a>
<a class="indexterm" name="d5e7634"></a>
<a class="indexterm" name="d5e7637"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.DynamicDataStructs</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getDynamicDataStructs()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getDynamicDataStructs
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DynamicDataStructs</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether to dynamically generate
customized structs to hold persistent data. Both the OpenJPA data cache and the
remote framework rely on data structs to cache and transfer persistent state.
With dynamic structs, OpenJPA can customize data storage for each class,
eliminating the need to generate primitive wrapper objects. This saves memory
and speeds up certain runtime operations. The price is a longer warm-up time for
the application - generating and loading custom classes into the JVM takes time.
Therefore, only set this property to <code class="literal">true</code> if you have a
long-running application where the initial cost of class generation is offset by
memory and speed optimization over time.
</p>
</div>
<div class="section" id="openjpa.DynamicEnhancementAgent"><div class="titlepage"><div><div><h3 class="title">5.32.&nbsp;openjpa.DynamicEnhancementAgent</h3></div></div></div>
<p>
<span class="bold"><strong>Property name: </strong></span>
<code class="literal">openjpa.DynamicEnhancementAgent</code>
</p>
<p>
<span class="bold"><strong>Configuration API: </strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getDynamicEnhancementAgent()" target="_top">org.apache.openjpa.conf.OpenJPAConfiguration.getDynamicEnhancementAgent</a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config property:</strong></span>
DynamicEnhancementAgent
</p>
<p>
<span class="bold"><strong>Default: </strong></span>
<code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span>
The DynamicEnhancementAgent property controls whether or not
OpenJPA will attempt to dynamically load the PCEnhancer
javaagent.
</p>
<p>
See the reference guide for more information
<a class="xref" href="#ref_guide_pc_enhance_dynamic" title="2.4.&nbsp; Enhancing Dynamically at Runtime">Section&nbsp;2.4, &#8220;
Enhancing Dynamically at Runtime
&#8221;</a>
</p>
</div>
<div class="section" id="openjpa.FetchBatchSize"><div class="titlepage"><div><div><h3 class="title">5.33.&nbsp;
openjpa.FetchBatchSize
</h3></div></div></div>
<a class="indexterm" name="d5e7675"></a>
<a class="indexterm" name="d5e7677"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.FetchBatchSize
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getFetchBatchSize()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getFetchBatchSize
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
FetchBatchSize</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">-1</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The number of rows to fetch at
once when scrolling through a result set. The fetch size can also be set at
runtime. See <a class="xref" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">Section&nbsp;10, &#8220;
Large Result Sets
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.EncryptionProvider"><div class="titlepage"><div><div><h3 class="title">5.34.&nbsp;
openjpa.EncryptionProvider
</h3></div></div></div>
<a class="indexterm" name="d5e7698"></a>
<a class="indexterm" name="d5e7700"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.EncryptionProvider</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getEncryptionProvider()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getEncryptionProvider</code>
</a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span>
<code class="literal">EncryptionProvider</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin list string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/encryption/EncryptionProvider.html" target="_top"><code class="classname">
org.apache.openjpa.lib.encryption.EncryptionProvider</code></a>s to use for connection password
encryption. See <a class="xref" href="#ref_guide_encryption" title="Chapter&nbsp;11.&nbsp; Encryption Provider">Chapter&nbsp;11, <i>
Encryption Provider
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.FetchGroups"><div class="titlepage"><div><div><h3 class="title">5.35.&nbsp;
openjpa.FetchGroups
</h3></div></div></div>
<a class="indexterm" name="d5e7723"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.FetchGroups
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getFetchGroups()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getFetchGroups
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
FetchGroups</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A comma-separated list of fetch
group names that are to be loaded when retrieving objects from the datastore.
Fetch groups can also be set at runtime. See <a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a>
for details.
</p>
</div>
<div class="section" id="openjpa.FlushBeforeQueries"><div class="titlepage"><div><div><h3 class="title">5.36.&nbsp;
openjpa.FlushBeforeQueries
</h3></div></div></div>
<a class="indexterm" name="d5e7743"></a>
<a class="indexterm" name="d5e7745"></a>
<a class="indexterm" name="d5e7748"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.FlushBeforeQueries</code>
</p>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.FlushBeforeQueries</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getFlushBeforeQueries()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getFlushBeforeQueries
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
FlushBeforeQueries</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether or not to flush any
changes made in the current transaction to the datastore before executing a
query. See <a class="xref" href="#ref_guide_dbsetup_retain" title="8.&nbsp; Configuring the Use of JDBC Connections">Section&nbsp;8, &#8220;
Configuring the Use of JDBC Connections
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.IgnoreChanges"><div class="titlepage"><div><div><h3 class="title">5.37.&nbsp;
openjpa.IgnoreChanges
</h3></div></div></div>
<a class="indexterm" name="d5e7772"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.IgnoreChanges
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getIgnoreChanges()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getIgnoreChanges
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
IgnoreChanges</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether to consider modifications
to persistent objects made in the current transaction when evaluating queries.
Setting this to <code class="literal">true</code> allows OpenJPA to ignore changes and
execute the query directly against the datastore. A value of <code class="literal">false
</code> forces OpenJPA to consider whether the changes in the current
transaction affect the query, and if so to either evaluate the query in-memory
or flush before running it against the datastore.
</p>
</div>
<div class="section" id="openjpa.Id"><div class="titlepage"><div><div><h3 class="title">5.38.&nbsp;openjpa.Id</h3></div></div></div>
<a class="indexterm" name="d5e7793"></a>
<p>
<span class="bold"><strong>Property name:</strong></span>
<code class="literal">openjpa.Id</code>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property:</strong></span>
<code class="literal">Id</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> none
</p>
<p>
<span class="bold"><strong>Description:</strong></span> An
environment-specific identifier for this configuration. This
might correspond to a JPA persistence-unit name, or to some other
more-unique value available in the current environment.
</p>
</div>
<div class="section" id="openjpa.InitializeEagerly"><div class="titlepage"><div><div><h3 class="title">5.39.&nbsp;
openjpa.InitializeEagerly
</h3></div></div></div>
<a class="indexterm" name="d5e7807"></a>
<a class="indexterm" name="d5e7809"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.InitializeEagerly
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#isInitializeEagerly()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.isInitializeEagerly
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
InitializeEagerly</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">false</code>,
<code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Controls whether initialization
is eager or lazy. Eager initialization imply all persistent classes, their
mapping information, database connectivity and all other resources specified in
the configuration of a persistence unit will be initialized when a persistent
unit is constructed. The default behavior is
lazy i.e. persistent classes, database and other resources are initialized only
when the application refers to a resource for the first time.
</p>
</div>
<div class="section" id="openjpa.Instrumentation"><div class="titlepage"><div><div><h3 class="title">5.40.&nbsp;
openjpa.Instrumentation
</h3></div></div></div>
<a class="indexterm" name="d5e7833"></a>
<a class="indexterm" name="d5e7835"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.Instrumentation</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getInstrumentation()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getInstrumentation
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Instrumentation</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">-</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">jmx</code>,
<code class="literal">custom plugin string</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing one or more instances of
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/instrumentation/InstrumentationProvider.html" target="_top">
<code class="classname">org.apache.openjpa.lib.instrumentation.InstrumentationProvider</code></a> and
specific instruments to enable. See <a class="xref" href="#ref_guide_instrumentation" title="Chapter&nbsp;16.&nbsp; Instrumentation">Chapter&nbsp;16, <i>
Instrumentation
</i></a> for details.
</p>
</div>
<div class="section" id="openjpa.InverseManager"><div class="titlepage"><div><div><h3 class="title">5.41.&nbsp;
openjpa.InverseManager
</h3></div></div></div>
<a class="indexterm" name="d5e7862"></a>
<a class="indexterm" name="d5e7864"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.InverseManager
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getInverseManager()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getInverseManager
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
InverseManager</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">false</code>,
<code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing a
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/InverseManager.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.InverseManager</code></a> to use
for managing bidirectional relations upon a flush. See
<a class="xref" href="#ref_guide_inverses" title="5.&nbsp; Managed Inverses">Section&nbsp;5, &#8220;
Managed Inverses
&#8221;</a> for usage documentation.
</p>
</div>
<div class="section" id="openjpa.LockManager"><div class="titlepage"><div><div><h3 class="title">5.42.&nbsp;
openjpa.LockManager
</h3></div></div></div>
<a class="indexterm" name="d5e7892"></a>
<a class="indexterm" name="d5e7894"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.LockManager
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getLockManager()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getLockManager
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
LockManager</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">mixed</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">none</code>, <code class="literal">version</code>,
<code class="literal">pessimistic</code>, <code class="literal">mixed</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing a
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/LockManager.html" target="_top"><code class="classname">
org.apache.openjpa.kernel.LockManager</code></a> to use for acquiring
locks on persistent instances during transactions. See
<a class="xref" href="#ref_guide_locking_lockmgr" title="3.4.&nbsp; Lock Manager">Section&nbsp;3.4, &#8220;
Lock Manager
&#8221;</a> for more information.
</p>
</div>
<div class="section" id="openjpa.LockTimeout"><div class="titlepage"><div><div><h3 class="title">5.43.&nbsp;
openjpa.LockTimeout
</h3></div></div></div>
<a class="indexterm" name="d5e7924"></a>
<a class="indexterm" name="d5e7926"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.LockTimeout
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getLockTimeout()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getLockTimeout
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
LockTimeout</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">-1</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The number of milliseconds to wait
for an object lock before throwing an exception, or -1 for no limit. See
<a class="xref" href="#ref_guide_locking" title="3.&nbsp; Object Locking">Section&nbsp;3, &#8220;
Object Locking
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.Log"><div class="titlepage"><div><div><h3 class="title">5.44.&nbsp;
openjpa.Log
</h3></div></div></div>
<a class="indexterm" name="d5e7947"></a>
<a class="indexterm" name="d5e7949"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Log</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/conf/Configuration.html#getLog()" target="_top">
<code class="methodname">org.apache.openjpa.lib.conf.Configuration.getLog</code>
</a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">Log
</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">openjpa</code>,
<code class="literal">commons</code>, <code class="literal">log4j</code>, <code class="literal">slf4j</code>,
<code class="literal">none</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing a
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/log/LogFactory.html" target="_top"><code class="classname">
org.apache.openjpa.lib.log.LogFactory</code></a> to use for logging.
For details on logging, see <a class="xref" href="#ref_guide_logging" title="Chapter&nbsp;3.&nbsp; Logging and Auditing">Chapter&nbsp;3, <i>
Logging and Auditing
</i></a>.
</p>
</div>
<div class="section" id="openjpa.ManagedRuntime"><div class="titlepage"><div><div><h3 class="title">5.45.&nbsp;
openjpa.ManagedRuntime
</h3></div></div></div>
<a class="indexterm" name="d5e7980"></a>
<a class="indexterm" name="d5e7982"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.ManagedRuntime
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getManagedRuntime()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getManagedRuntime
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ManagedRuntime</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">auto</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/ee/ManagedRuntime.html" target="_top"><code class="classname">
org.apache.openjpa.ee.ManagedRuntime</code></a> implementation to use
for obtaining a reference to the <code class="classname">TransactionManager</code> in an
enterprise environment.
</p>
</div>
<div class="section" id="openjpa.Mapping"><div class="titlepage"><div><div><h3 class="title">5.46.&nbsp;
openjpa.Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e8007"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Mapping
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getMapping()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getMapping</code>
</a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Mapping</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The symbolic name of the
object-to-datastore mapping to use.
</p>
</div>
<div class="section" id="openjpa.MaxFetchDepth"><div class="titlepage"><div><div><h3 class="title">5.47.&nbsp;
openjpa.MaxFetchDepth
</h3></div></div></div>
<a class="indexterm" name="d5e8025"></a>
<a class="indexterm" name="d5e8027"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.MaxFetchDepth
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getMaxFetchDepth()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getMaxFetchDepth
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
MaxFetchDepth</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">-1</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The maximum depth of relations to
traverse when eager fetching. Use -1 for no limit. Defaults to no limit. See
<a class="xref" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">Section&nbsp;8, &#8220;
Eager Fetching
&#8221;</a> for details on eager fetching.
</p>
</div>
<div class="section" id="openjpa.MetaDataFactory"><div class="titlepage"><div><div><h3 class="title">5.48.&nbsp;
openjpa.MetaDataFactory
</h3></div></div></div>
<a class="indexterm" name="d5e8048"></a>
<a class="indexterm" name="d5e8050"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.MetaDataFactory
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getMetaDataFactory()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getMetaDataFactory
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
MetaDataFactory</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> <code class="literal">jpa</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/meta/MetaDataFactory.html" target="_top">
<code class="classname">openjpa.meta.MetaDataFactory</code></a> to use to store and
retrieve metadata for your persistent classes. See
<a class="xref" href="#ref_guide_meta_factory" title="1.&nbsp; Metadata Factory">Section&nbsp;1, &#8220;
Metadata Factory
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.MetaDataRepository"><div class="titlepage"><div><div><h3 class="title">5.49.&nbsp;
openjpa.MetaDataRepository
</h3></div></div></div>
<a class="indexterm" name="d5e8074"></a>
<a class="indexterm" name="d5e8076"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.MetaDataRepository
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getMetaDataRepository()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getMetaDataRepository
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
MetaDataRepository</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span>none<code class="literal"></code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/meta/MetaDataRepository.html" target="_top">
<code class="classname">openjpa.meta.MetaDataRepository</code></a> to use to store and
retrieve metadata for your persistent classes. See
<a class="xref" href="#ref_guide_meta_repository" title="2.&nbsp;Metadata Repository">Section&nbsp;2, &#8220;Metadata Repository&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.Multithreaded"><div class="titlepage"><div><div><h3 class="title">5.50.&nbsp;
openjpa.Multithreaded
</h3></div></div></div>
<a class="indexterm" name="d5e8100"></a>
<a class="indexterm" name="d5e8102"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Multithreaded
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getMultithreaded()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getMultithreaded
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Multithreaded</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether persistent instances and
OpenJPA components other than the <code class="classname">EntityManagerFactory</code>
will be accessed by multiple threads at once.
</p>
</div>
<div class="section" id="openjpa.Optimistic"><div class="titlepage"><div><div><h3 class="title">5.51.&nbsp;
openjpa.Optimistic
</h3></div></div></div>
<a class="indexterm" name="d5e8123"></a>
<a class="indexterm" name="d5e8125"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Optimistic
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getOptimistic()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getOptimistic
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Optimistic</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Selects between optimistic and
pessimistic (datastore) transactional modes.
</p>
</div>
<div class="section" id="openjpa.OptimizeIdCopy"><div class="titlepage"><div><div><h3 class="title">5.52.&nbsp;
openjpa.OptimizeIdCopy
</h3></div></div></div>
<a class="indexterm" name="d5e8145"></a>
<a class="indexterm" name="d5e8147"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.OptimizeIdCopy
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getOptimizeIdCopy()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getOptimizeIdCopy
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
OptimizeIdCopy</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Attempt to optimize id class copy operations
used internally by the provider during various ORM operations. This optimization is only
applicable for entities using simple id classes (via @IdClass or XML equivalent) that do not
have public setters, provide a public constructor with exact matching parameter types, and
perform direct assignments to id class fields within the constructor. If these conditions
are met, OpenJPA will use a public constructor during internal id copy operations instead
of less optimal reflection. Optimization of id copy occurs during the enhancement phase.
If the enhancer determines optimization cannot occur, it will fallback to the normal behavior.
A side effect of enabling this property is that an id class constructor will be called by
the provider during runtime operations. If there is logic in the constructor in addition
to field initialization, (parameter verification, for example) that logic will also be
executed during the operation, which could result in a change in runtime behavior.
</p>
</div>
<div class="section" id="openjpa.OrphanedKeyAction"><div class="titlepage"><div><div><h3 class="title">5.53.&nbsp;
openjpa.OrphanedKeyAction
</h3></div></div></div>
<a class="indexterm" name="d5e8167"></a>
<a class="indexterm" name="d5e8169"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.OrphanedKeyAction</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getOrphanedKeyAction()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getOrphanedKeyAction
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
OrphanedKeyAction</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">log</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">log</code>,
<code class="literal">exception</code>, <code class="literal">none</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing a
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/OrphanedKeyAction.html" target="_top">
<code class="classname">org.apache.openjpa.event.OrphanedKeyAction</code></a> to
invoke when OpenJPA discovers an orphaned datastore key. See
<a class="xref" href="#ref_guide_orphan" title="11.&nbsp; Orphaned Keys">Section&nbsp;11, &#8220;
Orphaned Keys
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.NontransactionalRead"><div class="titlepage"><div><div><h3 class="title">5.54.&nbsp;
openjpa.NontransactionalRead
</h3></div></div></div>
<a class="indexterm" name="d5e8198"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.NontransactionalRead</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getNontransactionalRead()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getNontransactionalRead
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
NontransactionalRead</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether the OpenJPA runtime will
allow you to read data outside of a transaction.
</p>
</div>
<div class="section" id="openjpa.NontransactionalWrite"><div class="titlepage"><div><div><h3 class="title">5.55.&nbsp;
openjpa.NontransactionalWrite
</h3></div></div></div>
<a class="indexterm" name="d5e8217"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.NontransactionalWrite</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getNontransactionalWrite()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getNontransactionalWrite
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
NontransactionalWrite</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> <code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether you can modify persistent
objects and perform persistence operations outside of a transaction. Changes
will take effect on the next transaction.
</p>
</div>
<div class="section" id="openjpa.ProxyManager"><div class="titlepage"><div><div><h3 class="title">5.56.&nbsp;
openjpa.ProxyManager
</h3></div></div></div>
<a class="indexterm" name="d5e8236"></a>
<a class="indexterm" name="d5e8238"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.ProxyManager
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getProxyManager()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getProxyManager
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ProxyManager</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">default</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing a
<a class="ulink" href="../../apidocs/org/apache/openjpa/util/ProxyManager.html" target="_top"><code class="classname">
org.apache.openjpa.util.ProxyManager</code></a> to use for proxying
mutable second class objects. See
<a class="xref" href="#ref_guide_pc_scos_proxy_custom" title="6.4.3.&nbsp; Custom Proxies">Section&nbsp;6.4.3, &#8220;
Custom Proxies
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.PostLoadOnMerge"><div class="titlepage"><div><div><h3 class="title">5.57.&nbsp;
openjpa.PostLoadOnMerge
</h3></div></div></div>
<a class="indexterm" name="d5e8262"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.PostLoadOnMerge</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getPostLoadOnMerge()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getPostLoadOnMerge
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
PostLoadOnMerge</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether the OpenJPA runtime will
trigger a PostLoad lifecycle event for EntityManager#merge(). If you enable this
option, OpenJPA will also ensure that the whole entity from the database will
get passed to the PostLoad entity listener.
</p>
</div>
<div class="section" id="openjpa.QueryCache"><div class="titlepage"><div><div><h3 class="title">5.58.&nbsp;
openjpa.QueryCache
</h3></div></div></div>
<a class="indexterm" name="d5e8281"></a>
<a class="indexterm" name="d5e8283"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.QueryCache
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getQueryCache()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getQueryCache
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
QueryCache</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/datacache/QueryCache.html" target="_top">
<code class="classname">org.apache.openjpa.datacache.QueryCache</code></a>
implementation to use for caching of queries loaded from the data store. See
<a class="xref" href="#ref_guide_cache_query" title="1.4.&nbsp; Query Cache">Section&nbsp;1.4, &#8220;
Query Cache
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.QueryCompilationCache"><div class="titlepage"><div><div><h3 class="title">5.59.&nbsp;
openjpa.QueryCompilationCache
</h3></div></div></div>
<a class="indexterm" name="d5e8307"></a>
<a class="indexterm" name="d5e8309"></a>
<p>
<span class="bold"><strong>Property name:</strong></span>
<code class="literal">openjpa.QueryCompilationCache</code>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property:</strong></span>
<code class="literal">QueryCompilationCache</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> <code class="literal">true</code>.
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<code class="classname">java.util.Map</code> to use for caching of data used during
query compilation. See <a class="xref" href="#ref_guide_cache_querycomp" title="2.&nbsp; Query Compilation Cache">Section&nbsp;2, &#8220;
Query Compilation Cache
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.ReadLockLevel"><div class="titlepage"><div><div><h3 class="title">5.60.&nbsp;
openjpa.ReadLockLevel
</h3></div></div></div>
<a class="indexterm" name="d5e8328"></a>
<a class="indexterm" name="d5e8330"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.ReadLockLevel
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getReadLockLevel()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getReadLockLevel
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ReadLockLevel</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">read</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">none</code>,
<code class="literal">read</code>, <code class="literal">write</code>,
<code class="literal">optimistic</code>, <code class="literal">optimistic-force-increment</code>,
<code class="literal">pessimistic-read</code>, <code class="literal">pessimistic-write</code>,
<code class="literal">pessimistic-force-increment</code>, numeric values for
lock-manager specific lock levels
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The default level at which to lock
objects retrieved during a non-optimistic transaction. Note that for the default
JDBC lock manager, <code class="literal"> read</code> and <code class="literal">write</code> lock
levels are equivalent. Lock levels <code class="literal">pessimistic-read</code>,
<code class="literal">pessimistic-write</code> and
<code class="literal">pessimistic-force-increment</code> are in effect only when the
<code class="literal">mixed</code> lock manager is used.
</p>
</div>
<div class="section" id="openjpa.RemoteCommitProvider"><div class="titlepage"><div><div><h3 class="title">5.61.&nbsp;
openjpa.RemoteCommitProvider
</h3></div></div></div>
<a class="indexterm" name="d5e8366"></a>
<a class="indexterm" name="d5e8368"></a>
<a class="indexterm" name="d5e8371"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.RemoteCommitProvider</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getRemoteCommitProvider()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getRemoteCommitProvider
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
RemoteCommitProvider</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> - If <code class="literal">openjpa.DataCache</code> is enabled, the default value is <code class="literal">sjvm</code>.
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/RemoteCommitProvider.html" target="_top">
<code class="classname">org.apache.openjpa.event.RemoteCommitProvider</code></a>
implementation to use for distributed event notification. See
<a class="xref" href="#ref_guide_event_conf" title="2.1.&nbsp; Remote Commit Provider Configuration">Section&nbsp;2.1, &#8220;
Remote Commit Provider Configuration
&#8221;</a> for more information.
</p>
</div>
<div class="section" id="openjpa.RestoreState"><div class="titlepage"><div><div><h3 class="title">5.62.&nbsp;
openjpa.RestoreState
</h3></div></div></div>
<a class="indexterm" name="d5e8396"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.RestoreState
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getRestoreState()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getRestoreState
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
RestoreState</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">none</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">none</code>,
<code class="literal">immutable</code>, <code class="literal">all</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether to restore managed fields
to their pre-transaction values when a rollback occurs.
</p>
</div>
<div class="section" id="openjpa.RetainState"><div class="titlepage"><div><div><h3 class="title">5.63.&nbsp;
openjpa.RetainState
</h3></div></div></div>
<a class="indexterm" name="d5e8420"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.RetainState
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getRetainState()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getRetainState
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
RetainState</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">true</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether persistent fields retain
their values on transaction commit.
</p>
</div>
<div class="section" id="openjpa.RetryClassRegistration"><div class="titlepage"><div><div><h3 class="title">5.64.&nbsp;
openjpa.RetryClassRegistration
</h3></div></div></div>
<a class="indexterm" name="d5e8439"></a>
<a class="indexterm" name="d5e8441"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.RetryClassRegistration</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getRetryClassRegistration()" target="_top">
<code class="methodname">
org.apache.openjpa.conf.OpenJPAConfiguration.getRetryClassRegistration
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
RetryClassRegistration</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Controls whether to log a warning
and defer registration instead of throwing an exception when a persistent class
cannot be fully processed. This property should <span class="emphasis"><em>only</em></span> be
used in complex classloader situations where security is preventing OpenJPA from
reading registered classes. Setting this to true unnecessarily may obscure more
serious problems.
</p>
</div>
<div class="section" id="openjpa.RuntimeUnenhancedClasses"><div class="titlepage"><div><div><h3 class="title">5.65.&nbsp;openjpa.RuntimeUnenhancedClasses</h3></div></div></div>
<p>
<span class="bold"><strong>Property name: </strong></span>
<code class="literal">openjpa.RuntimeUnenhancedClasses</code>
</p>
<p>
<span class="bold"><strong>Configuration API: </strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getRuntimeUnenhancedClasses()" target="_top">org.apache.openjpa.conf.OpenJPAConfiguration.getRuntimeUnenhancedClasses</a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config property:</strong></span>
RuntimeUnenhancedClasses
</p>
<p>
<span class="bold"><strong>Default: </strong></span>
<code class="literal">unsupported</code>
</p>
<p>
<span class="bold"><strong>Possible values:</strong></span>
<code class="literal">supported</code>,
<code class="literal">unsupported</code>,
<code class="literal">warn</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span>
The RuntimeUnenhancedClasses property controls how OpenJPA
handles classes that have not been enhanced by the PCEnhancer
tool or automatically by a javaagent. If RuntimeUnenhancedClasses is
set to <code class="literal">supported</code> OpenJPA will automatically
create subclasses for unenhanced entity classes. If set to
<code class="literal">unsupported</code> OpenJPA will not create subclasses
for unenhanced entity classes and will throw an exception when
they are detected. If set to <code class="literal">warn</code> OpenJPA
will not create subclasses for unenhanced entity classes
but will log a warning message.
</p>
<p>
This function is often useful for rapid prototyping but is not
<span class="italic">generally</span>
recommended for use in production. Please consult the reference guide
before changing the default value.
</p>
<p>
See the reference guide section on unenhanced types for more
information
<a class="xref" href="#ref_guide_pc_enhance_unenhanced_types" title="2.5.&nbsp; Omitting the OpenJPA enhancer">Section&nbsp;2.5, &#8220;
Omitting the OpenJPA enhancer
&#8221;</a>
</p>
</div>
<div class="section" id="openjpa.SavepointManager"><div class="titlepage"><div><div><h3 class="title">5.66.&nbsp;
openjpa.SavepointManager
</h3></div></div></div>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.SavepointManager</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getSavepointManager()" target="_top">
org.apache.openjpa.conf.OpenJPAConfiguration.getSavepointManager</a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property:</strong></span>
SavepointManager
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">in-mem</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">in-mem</code>,
<code class="literal">jdbc</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing a
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/SavepointManager.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.SavepointManager</code></a> to
use for managing transaction savepoints. See
<a class="xref" href="#ref_guide_savepoints" title="4.&nbsp; Savepoints">Section&nbsp;4, &#8220;
Savepoints
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.Sequence"><div class="titlepage"><div><div><h3 class="title">5.67.&nbsp;
openjpa.Sequence
</h3></div></div></div>
<a class="indexterm" name="d5e8512"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Sequence
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getSequence()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getSequence
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Sequence</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">table</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/Seq.html" target="_top"><code class="classname">
org.apache.openjpa.kernel.Seq</code></a> implementation to use for the
system sequence. See <a class="xref" href="#ref_guide_sequence" title="6.&nbsp; Generators">Section&nbsp;6, &#8220;
Generators
&#8221;</a> for more
information.
</p>
</div>
<div class="section" id="openjpa.Specification"><div class="titlepage"><div><div><h3 class="title">5.68.&nbsp;
openjpa.Specification
</h3></div></div></div>
<a class="indexterm" name="d5e8535"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.Specification
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getSpecificationInstance()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getSpecificationInstance
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Specification</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">table</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A formatted string describing the Specification
to use for the default configuration options. The format of the Specifcation string is
<code class="literal">name [major.[minor]]</code> where <code class="literal">name</code> denotes the name of the
Specification such as <code class="literal">JPA</code> or <code class="literal">JDO</code>, <code class="literal">major</code>
denotes the major integral version number of the Specification and <code class="literal">minor</code>
denotes a minor version which can be an arbitrary string.
See <a class="xref" href="#ref_guide_spec_compatibility" title="6.20.&nbsp;Compatibility with Specification">Section&nbsp;6.20, &#8220;Compatibility with Specification&#8221;</a> for more information.
</p>
</div>
<div class="section" id="openjpa.TransactionMode"><div class="titlepage"><div><div><h3 class="title">5.69.&nbsp;
openjpa.TransactionMode
</h3></div></div></div>
<a class="indexterm" name="d5e8561"></a>
<a class="indexterm" name="d5e8563"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.TransactionMode
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getTransactionMode()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getTransactionMode
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
TransactionMode</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">local</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">local</code>,
<code class="literal">managed</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The default transaction mode to
use. You can override this setting per-session.
</p>
</div>
<div class="section" id="openjpa.UseTCCLinSelectNew"><div class="titlepage"><div><div><h3 class="title">5.70.&nbsp;
openjpa.UseTCCLinSelectNew
</h3></div></div></div>
<a class="indexterm" name="d5e8587"></a>
<a class="indexterm" name="d5e8589"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.UseTCCLinSelectNew</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getUseTCCLinSelectNew()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getUseTCCLinSelectNew
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">UseTCCLinSelectNew</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Since: </strong></span><code class="literal">OpenJPA-2.4.2</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">true</code>,
<code class="literal">false</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Whether to try to use the ThreadContextClassLoader
as fallback if the given class in a <code class="literal">SELECT NEW</code> statement could not be found
with the default ClassLoader. This is mostly useful in EAR and OSGi environments.
By default the ClassLoader of the entity is used.
</p>
</div>
<div class="section" id="openjpa.WriteLockLevel"><div class="titlepage"><div><div><h3 class="title">5.71.&nbsp;
openjpa.WriteLockLevel
</h3></div></div></div>
<a class="indexterm" name="d5e8617"></a>
<a class="indexterm" name="d5e8619"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.WriteLockLevel
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getWriteLockLevel()" target="_top">
<code class="methodname">org.apache.openjpa.conf.OpenJPAConfiguration.getWriteLockLevel
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
WriteLockLevel</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">write</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">none</code>,
<code class="literal">read</code>, <code class="literal">write</code>,
<code class="literal">optimistic</code>, <code class="literal">optimistic-force-increment</code>,
<code class="literal">pessimistic-read</code>, <code class="literal">pessimistic-write</code>,
<code class="literal">pessimistic-force-increment</code>, numeric values for
lock-manager specific lock levels.
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The default level at which to lock
objects changed during a non-optimistic transaction. Note that for the default
JDBC lock manager, <code class="literal"> read</code> and <code class="literal">write</code> lock
levels are equivalent. Lock levels <code class="literal">pessimistic-read</code>,
<code class="literal">pessimistic-write</code> and
<code class="literal">pessimistic-force-increment</code> are in effect only when the
<code class="literal">mixed</code> lock manager is used.
</p>
</div>
</div>
<div class="section" id="ref_guide_conf_jdbc"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
OpenJPA JDBC Properties
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#openjpa.jdbc.ConnectionDecorators">6.1.
openjpa.jdbc.ConnectionDecorators
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DBDictionary">6.2.
openjpa.jdbc.DBDictionary
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.DriverDataSource">6.3.
openjpa.jdbc.DriverDataSource
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.EagerFetchMode">6.4.
openjpa.jdbc.EagerFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.FetchDirection">6.5.
openjpa.jdbc.FetchDirection
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.JDBCListeners">6.6.
openjpa.jdbc.JDBCListeners
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.LRSSize">6.7.
openjpa.jdbc.LRSSize
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingDefaults">6.8.
openjpa.jdbc.MappingDefaults
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.MappingFactory">6.9.
openjpa.jdbc.MappingFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.QuerySQLCache">6.10.
openjpa.jdbc.QuerySQLCache
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.ResultSetType">6.11.
openjpa.jdbc.ResultSetType
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schema">6.12.
openjpa.jdbc.Schema
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SchemaFactory">6.13.
openjpa.jdbc.SchemaFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.Schemas">6.14.
openjpa.jdbc.Schemas
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SQLFactory">6.15.
openjpa.jdbc.SQLFactory
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SubclassFetchMode">6.16.
openjpa.jdbc.SubclassFetchMode
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.SynchronizeMappings">6.17.
openjpa.jdbc.SynchronizeMappings
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.TransactionIsolation">6.18.
openjpa.jdbc.TransactionIsolation
</a></span></dt><dt><span class="section"><a href="#openjpa.jdbc.UpdateManager">6.19.
openjpa.jdbc.UpdateManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_spec_compatibility">6.20. Compatibility with Specification</a></span></dt></dl></div>
<a class="indexterm" name="d5e8655"></a>
<p>
The following properties apply exclusively to the OpenJPA JDBC back-end.
</p>
<div class="section" id="openjpa.jdbc.ConnectionDecorators"><div class="titlepage"><div><div><h3 class="title">6.1.&nbsp;
openjpa.jdbc.ConnectionDecorators
</h3></div></div></div>
<a class="indexterm" name="d5e8661"></a>
<a class="indexterm" name="d5e8663"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.ConnectionDecorators</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getConnectionDecorators()" target="_top">
<code class="methodname">
org.apache.openjpa.jdbc.conf.JDBCConfiguration.getConnectionDecorators
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ConnectionDecorators</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A comma-separated list of plugin
strings (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/jdbc/ConnectionDecorator.html" target="_top">
<code class="classname">org.apache.openjpa.lib.jdbc.ConnectionDecorator</code></a>
instances to install on the connection factory. These decorators can wrap
connections passed from the underlying <code class="classname">DataSource</code> to add
functionality. OpenJPA will pass all connections through the list of decorators
before using them. Note that by default OpenJPA employs all
of the built-in decorators in the <code class="classname">org.apache.openjpa.lib.jdbc
</code> package already; you do not need to list them here.
</p>
</div>
<div class="section" id="openjpa.jdbc.DBDictionary"><div class="titlepage"><div><div><h3 class="title">6.2.&nbsp;
openjpa.jdbc.DBDictionary
</h3></div></div></div>
<a class="indexterm" name="d5e8687"></a>
<a class="indexterm" name="d5e8689"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.DBDictionary</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getDBDictionary()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getDBDictionary
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DBDictionary</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> Based on the
<a class="link" href="#openjpa.ConnectionURL" title="5.21.&nbsp; openjpa.ConnectionURL"><code class="literal">openjpa.ConnectionURL</code>
</a><a class="link" href="#openjpa.ConnectionDriverName" title="5.8.&nbsp; openjpa.ConnectionDriverName"><code class="literal">
openjpa.ConnectionDriverName</code></a>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/DBDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.DBDictionary</code></a> to use
for database interaction. OpenJPA typically auto-configures the dictionary based
on the JDBC URL, but you may have to set this property explicitly if you are
using an unrecognized driver, to plug in your own dictionary for a database
OpenJPA does not support out-of-the-box, or if you like to change the default
configuration of an existing dictionary. See
<a class="xref" href="#ref_guide_dbsetup_dbsupport" title="4.&nbsp; Database Support">Section&nbsp;4, &#8220;
Database Support
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.DriverDataSource"><div class="titlepage"><div><div><h3 class="title">6.3.&nbsp;
openjpa.jdbc.DriverDataSource
</h3></div></div></div>
<a class="indexterm" name="d5e8716"></a>
<a class="indexterm" name="d5e8718"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.DriverDataSource</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getDriverDataSource()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getDriverDataSource
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
DriverDataSource</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">auto</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">auto</code>,
<code class="literal">dbcp</code>, <code class="literal">simple</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The alias or full class name of
the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/DriverDataSource.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.schema.DriverDataSource</code></a>
implementation to use to wrap JDBC Driver classes with javax.sql.DataSource
instances.
The <code class="classname">org.apache.commons.dbcp2.BasicDataSource</code> Apache Commons DBCP2 to be available on the classpath and provides connection pooling.
</p>
</div>
<div class="section" id="openjpa.jdbc.EagerFetchMode"><div class="titlepage"><div><div><h3 class="title">6.4.&nbsp;
openjpa.jdbc.EagerFetchMode
</h3></div></div></div>
<a class="indexterm" name="d5e8746"></a>
<a class="indexterm" name="d5e8748"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.EagerFetchMode</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getEagerFetchMode()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getEagerFetchMode
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
EagerFetchMode</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">parallel</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">parallel</code>,
<code class="literal">join</code>, <code class="literal">none</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Optimizes how OpenJPA loads
persistent relations. This setting can also be varied at runtime. See
<a class="xref" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">Section&nbsp;8, &#8220;
Eager Fetching
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.FetchDirection"><div class="titlepage"><div><div><h3 class="title">6.5.&nbsp;
openjpa.jdbc.FetchDirection
</h3></div></div></div>
<a class="indexterm" name="d5e8774"></a>
<a class="indexterm" name="d5e8776"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.FetchDirection</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getFetchDirection()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getFetchDirection
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
FetchDirection</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">forward</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">forward</code>,
<code class="literal">reverse</code>, <code class="literal">unknown</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The expected order in which query
result lists will be accessed. This property can also be varied at runtime. See
<a class="xref" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">Section&nbsp;10, &#8220;
Large Result Sets
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.JDBCListeners"><div class="titlepage"><div><div><h3 class="title">6.6.&nbsp;
openjpa.jdbc.JDBCListeners
</h3></div></div></div>
<a class="indexterm" name="d5e8802"></a>
<a class="indexterm" name="d5e8804"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.JDBCListeners</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getJDBCListeners()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getJDBCListeners
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
JDBCListeners</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A comma-separated list of plugin
strings (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/jdbc/JDBCListener.html" target="_top">
<code class="classname">org.apache.openjpa.lib.jdbc.JDBCListener</code></a> event
listeners to install. These listeners will be notified on various JDBC-related
events.
</p>
</div>
<div class="section" id="openjpa.jdbc.LRSSize"><div class="titlepage"><div><div><h3 class="title">6.7.&nbsp;
openjpa.jdbc.LRSSize
</h3></div></div></div>
<a class="indexterm" name="d5e8826"></a>
<a class="indexterm" name="d5e8828"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.jdbc.LRSSize
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getLRSSize()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getLRSSize
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
LRSSize</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">query</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">query</code>,
<code class="literal">last</code>, <code class="literal">unknown</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The strategy to use to calculate
the size of a result list. This property can also be varied at runtime. See
<a class="xref" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">Section&nbsp;10, &#8220;
Large Result Sets
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.MappingDefaults"><div class="titlepage"><div><div><h3 class="title">6.8.&nbsp;
openjpa.jdbc.MappingDefaults
</h3></div></div></div>
<a class="indexterm" name="d5e8854"></a>
<a class="indexterm" name="d5e8856"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.MappingDefaults</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getMappingDefaults()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getMappingDefaults
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
MappingDefaults</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> jpa
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/MappingDefaults.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.MappingDefaults</code></a> to
use to define default column names, table names, and constraints for your
persistent classes. See <a class="xref" href="#ref_guide_mapping_factory" title="5.&nbsp; Mapping Factory">Section&nbsp;5, &#8220;
Mapping Factory
&#8221;</a> for
details.
</p>
</div>
<div class="section" id="openjpa.jdbc.MappingFactory"><div class="titlepage"><div><div><h3 class="title">6.9.&nbsp;
openjpa.jdbc.MappingFactory
</h3></div></div></div>
<a class="indexterm" name="d5e8879"></a>
<a class="indexterm" name="d5e8881"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.MappingFactory</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getMappingFactory()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getMappingFactory
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
MappingFactory</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/meta/MetaDataFactory.html" target="_top">
<code class="classname">org.apache.openjpa.meta.MetaDataFactory</code></a> to use to
store and retrieve object-relational mapping information for your persistent
classes. See <a class="xref" href="#ref_guide_mapping_factory" title="5.&nbsp; Mapping Factory">Section&nbsp;5, &#8220;
Mapping Factory
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.QuerySQLCache"><div class="titlepage"><div><div><h3 class="title">6.10.&nbsp;
openjpa.jdbc.QuerySQLCache
</h3></div></div></div>
<a class="indexterm" name="d5e8904"></a>
<a class="indexterm" name="d5e8906"></a>
<p>
<span class="bold"><strong>Property name:</strong></span>
<code class="literal">openjpa.jdbc.QuerySQLCache</code>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property:</strong></span>
<code class="literal">QuerySQLCache</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> <code class="literal">true</code>.
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the options to cache and
reuse SQL statements generated for JPQL queries.
See <a class="xref" href="#ref_guide_cache_querysql" title="3.&nbsp;Prepared SQL Cache">Section&nbsp;3, &#8220;Prepared SQL Cache&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.ResultSetType"><div class="titlepage"><div><div><h3 class="title">6.11.&nbsp;
openjpa.jdbc.ResultSetType
</h3></div></div></div>
<a class="indexterm" name="d5e8924"></a>
<a class="indexterm" name="d5e8926"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.ResultSetType</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getResultSetType()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getResultSetType
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
ResultSetType</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">forward-only</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">forward-only</code>
, <code class="literal">scroll-sensitive</code>, <code class="literal">scroll-insensitive</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The JDBC result set type to use
when fetching result lists. This property can also be varied at runtime. See
<a class="xref" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">Section&nbsp;10, &#8220;
Large Result Sets
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.Schema"><div class="titlepage"><div><div><h3 class="title">6.12.&nbsp;
openjpa.jdbc.Schema
</h3></div></div></div>
<a class="indexterm" name="d5e8952"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.jdbc.Schema
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getSchema()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getSchema
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Schema</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The default schema name to prepend
to unqualified table names. Also, the schema in which OpenJPA will create new
tables. See <a class="xref" href="#ref_guide_schema_def" title="11.&nbsp; Default Schema">Section&nbsp;11, &#8220;
Default Schema
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.SchemaFactory"><div class="titlepage"><div><div><h3 class="title">6.13.&nbsp;
openjpa.jdbc.SchemaFactory
</h3></div></div></div>
<a class="indexterm" name="d5e8972"></a>
<a class="indexterm" name="d5e8974"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.SchemaFactory</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getSchemaFactory()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getSchemaFactory
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
SchemaFactory</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">dynamic</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">dynamic</code>,
<code class="literal">native</code>, <code class="literal">file</code>, <code class="literal">table</code>,
others
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/SchemaFactory.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.schema.SchemaFactory</code></a> to
use to store and retrieve information about the database schema. See
<a class="xref" href="#ref_guide_schema_info_factory" title="12.2.&nbsp; Schema Factory">Section&nbsp;12.2, &#8220;
Schema Factory
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.Schemas"><div class="titlepage"><div><div><h3 class="title">6.14.&nbsp;
openjpa.jdbc.Schemas
</h3></div></div></div>
<a class="indexterm" name="d5e9004"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.jdbc.Schemas
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getSchemas()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getSchemas
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
Schemas</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A comma-separated list of the
schemas and/or tables used for your persistent data. See
<a class="xref" href="#ref_guide_schema_info_list" title="12.1.&nbsp; Schemas List">Section&nbsp;12.1, &#8220;
Schemas List
&#8221;</a> for details.
</p>
</div>
<div class="section" id="openjpa.jdbc.SQLFactory"><div class="titlepage"><div><div><h3 class="title">6.15.&nbsp;
openjpa.jdbc.SQLFactory
</h3></div></div></div>
<a class="indexterm" name="d5e9024"></a>
<a class="indexterm" name="d5e9026"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">openjpa.jdbc.SQLFactory
</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getSQLFactory()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getSQLFactory
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
SQLFactory</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">default</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> A plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/SQLFactory.html" target="_top"><code class="classname">
org.apache.openjpa.jdbc.sql.SQLFactory</code></a> to use to abstract
common SQL constructs.
</p>
</div>
<div class="section" id="openjpa.jdbc.SubclassFetchMode"><div class="titlepage"><div><div><h3 class="title">6.16.&nbsp;
openjpa.jdbc.SubclassFetchMode
</h3></div></div></div>
<a class="indexterm" name="d5e9049"></a>
<a class="indexterm" name="d5e9051"></a>
<a class="indexterm" name="d5e9054"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.SubclassFetchMode</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getSubclassFetchMode()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getSubclassFetchMode
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
SubclassFetchMode</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">parallel</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">parallel</code>,
<code class="literal">join</code>, <code class="literal">none</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> How to select subclass data when
it is in other tables. This setting can also be varied at runtime. See
<a class="xref" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">Section&nbsp;8, &#8220;
Eager Fetching
&#8221;</a>.
</p>
</div>
<div class="section" id="openjpa.jdbc.SynchronizeMappings"><div class="titlepage"><div><div><h3 class="title">6.17.&nbsp;
openjpa.jdbc.SynchronizeMappings
</h3></div></div></div>
<a class="indexterm" name="d5e9080"></a>
<a class="indexterm" name="d5e9082"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.SynchronizeMappings</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getSynchronizeMappings()" target="_top">
<code class="methodname">
org.apache.openjpa.jdbc.conf.JDBCConfiguration.getSynchronizeMappings
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
SynchronizeMappings</code>
</p>
<p>
<span class="bold"><strong>Default:</strong></span> -
</p>
<p>
<span class="bold"><strong>Description:</strong></span> Controls whether OpenJPA will
attempt to run the mapping tool on all persistent classes to synchronize their
mappings and schema at runtime. Useful for rapid test/debug cycles. See
<a class="xref" href="#ref_guide_mapping_synch" title="1.3.&nbsp; Runtime Forward Mapping">Section&nbsp;1.3, &#8220;
Runtime Forward Mapping
&#8221;</a> for more information.
</p>
</div>
<div class="section" id="openjpa.jdbc.TransactionIsolation"><div class="titlepage"><div><div><h3 class="title">6.18.&nbsp;
openjpa.jdbc.TransactionIsolation
</h3></div></div></div>
<a class="indexterm" name="d5e9102"></a>
<a class="indexterm" name="d5e9104"></a>
<a class="indexterm" name="d5e9107"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.TransactionIsolation</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getTransactionIsolation()" target="_top">
<code class="methodname">
org.apache.openjpa.jdbc.conf.JDBCConfiguration.getTransactionIsolation
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
TransactionIsolation</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">default</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">default</code>,
<code class="literal">none</code>, <code class="literal">read-committed</code>, <code class="literal">
read-uncommitted</code>, <code class="literal">repeatable-read</code>, <code class="literal">
serializable</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The JDBC transaction isolation
level to use. See <a class="xref" href="#ref_guide_dbsetup_isolation" title="5.&nbsp; Setting the Transaction Isolation">Section&nbsp;5, &#8220;
Setting the Transaction Isolation
&#8221;</a> for
details.
</p>
</div>
<div class="section" id="openjpa.jdbc.UpdateManager"><div class="titlepage"><div><div><h3 class="title">6.19.&nbsp;
openjpa.jdbc.UpdateManager
</h3></div></div></div>
<a class="indexterm" name="d5e9136"></a>
<a class="indexterm" name="d5e9138"></a>
<p>
<span class="bold"><strong>Property name: </strong></span><code class="literal">
openjpa.jdbc.UpdateManager</code>
</p>
<p>
<span class="bold"><strong>Configuration API:</strong></span>
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html#getUpdateManager()" target="_top">
<code class="methodname">org.apache.openjpa.jdbc.conf.JDBCConfiguration.getUpdateManager
</code></a>
</p>
<p>
<span class="bold"><strong>Resource adaptor config-property: </strong></span><code class="literal">
UpdateManager</code>
</p>
<p>
<span class="bold"><strong>Default: </strong></span><code class="literal">batching-constraint</code>
</p>
<p>
<span class="bold"><strong>Possible values: </strong></span><code class="literal">default</code>,
<code class="literal">operation-order</code>, <code class="literal">constraint</code>, <code class="literal">
batching-constraint</code>, <code class="literal">batching-operation-order</code>
</p>
<p>
<span class="bold"><strong>Description:</strong></span> The full class name of the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/UpdateManager.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.UpdateManager</code></a> to
use to flush persistent object changes to the datastore. The provided default
implementation is
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/BatchingConstraintUpdateManager" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.BatchingConstraintUpdateManager</code>
</a>.
</p>
</div>
<div class="section" id="ref_guide_spec_compatibility"><div class="titlepage"><div><div><h3 class="title">6.20.&nbsp;Compatibility with Specification</h3></div></div></div>
<p>
The default behavior of certain OpenJPA API methods can evolve to align with the behaviors
defined in JPA specification. To maintain backward compatibility, OpenJPA allows configuration
options such that while the default behavior changes to align with current JPA specification, the
previous behaviors can always be emulated.
</p>
<p>
For example, JPA 2.0 specification
introduces a new API <code class="literal">void EntityManager.detach(Object entity)</code> that detaches
the given entity from the current persistence context. OpenJPA has provided similar
feature via <code class="literal">&lt;T&gt; T OpenJPAEntityManager.detach(T entity)</code> prior to JPA 2.0.
OpenJPA <code class="literal">detach()</code>, however, has different default behavior than what JPA 2.0
specification mandates. Firstly, OpenJPA creates a copy of the given entity as a detached instance
and returns it, whereas JPA 2.0 behavior requires the same given entity instance be detached.
Secondly, the given instance is removed from the persistence context for JPA 2.0, whereas
OpenJPA <code class="literal">detach()</code> method, prior to JPA 2.0, does not remove the instance
from the persistence context as a copy is returned. Thirdly, OpenJPA will flush before
detaching a dirty instance so that the detached instance can later be merged, whereas
JPA 2.0 <code class="literal">detach()</code> semantics does not require a dirty instance be flushed
before detach.
</p>
<p>
A user application running with OpenJPA that is compliant to a specific version of JPA specification
can emulate the older behavior by configuring OpenJPA compatibility options.
For example, <code class="literal">openjpa.Compatibility=FlushBeforeDetach=false,CopyOnDetach=true</code>
will emulate the older behavior of detach even when running with OpenJPA that is
compliant to JPA 2.0 specification. The configuration can also be set to a different version of the specification.
For example, <code class="literal">openjpa.Specification="JPA 1.0"</code> configuration setting will emulate
default OpenJPA behavior as it were for JPA specification version 1.0. Setting
<code class="literal">openjpa.Specification</code> is a shorthand for more fine-grained control available via
<code class="literal">openjpa.Compatibility</code>.
</p>
</div>
</div>
</div>
<div class="chapter" id="ref_guide_logging"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;3.&nbsp;
Logging and Auditing
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_logging_channels">1.
Logging Channels
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_openjpa">2.
OpenJPA Logging
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_noop">3.
Disabling Logging
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_log4j">4.
Log4J
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_commons">5.
Apache Commons Logging
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_logging_jdk14">5.1.
JDK java.util.logging
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_logging_slf4j">6.
SLF4J
</a></span></dt><dt><span class="section"><a href="#ref_guide_logging_custom">7.
Custom Log
</a></span></dt><dt><span class="section"><a href="#ref_guide_audit">8. OpenJPA Audit</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e9423">8.1. Configuration</a></span></dt><dt><span class="section"><a href="#d5e9445">8.2. Developing custom auditing</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e9183"></a>
<a class="indexterm" name="d5e9185"></a>
<p>
Logging is an important means of gaining insight into your application's runtime
behavior. OpenJPA provides a flexible logging system that integrates with many
existing runtime systems, such as application servers and servlet runners.
</p>
<p>
There are five built-in logging plugins: a
<a class="link" href="#ref_guide_logging_openjpa" title="2.&nbsp; OpenJPA Logging">default logging framework</a> that
covers most needs, a <a class="link" href="#ref_guide_logging_log4j" title="4.&nbsp; Log4J"> Log4J</a>
delegate, a <a class="link" href="#ref_guide_logging_slf4j" title="6.&nbsp; SLF4J"> SLF4J</a>
delegate, an <a class="link" href="#ref_guide_logging_commons" title="5.&nbsp; Apache Commons Logging"> Apache Commons Logging
</a> delegate, and a <a class="link" href="#ref_guide_logging_noop" title="3.&nbsp; Disabling Logging">no-op</a>
implementation for disabling logging.
</p>
<div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Warning</h3>
<p>
Logging can have a negative impact on performance. Disable verbose logging (such
as logging of SQL statements) before running any performance tests. It is
advisable to limit or disable logging for a production system. You can disable
logging altogether by setting the <code class="literal">openjpa.Log</code> property to
<code class="literal">none</code>.
</p>
</div>
<div class="section" id="ref_guide_logging_channels"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Logging Channels
</h2></div></div></div>
<a class="indexterm" name="d5e9200"></a>
<p>
Logging is done over a number of <span class="emphasis"><em>logging channels</em></span>, each of
which has a <span class="emphasis"><em>logging level</em></span> which controls the verbosity of
log messages recorded for the channel. OpenJPA uses the following logging
channels:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">openjpa.Tool</code>: Messages issued by the OpenJPA command line
and Ant tools. Most messages are basic statements detailing which classes or
files the tools are running on. Detailed output is only available via the
logging category the tool belongs to, such as <code class="literal">openjpa.Enhance</code>
for the enhancer (see <a class="xref" href="#ref_guide_pc_enhance" title="2.&nbsp; Enhancement">Section&nbsp;2, &#8220;
Enhancement
&#8221;</a>) or <code class="literal">
openjpa.MetaData</code> for the mapping tool (see
<a class="xref" href="#ref_guide_mapping_mappingtool" title="1.&nbsp; Forward Mapping">Section&nbsp;1, &#8220;
Forward Mapping
&#8221;</a>). This logging category
is provided so that you can get a general idea of what a tool is doing without
having to manipulate logging settings that might also affect runtime behavior.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9216"></a>
<code class="literal">openjpa.Enhance</code>: Messages pertaining to enhancement and
runtime class generation.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9222"></a>
<code class="literal">openjpa.MetaData</code>: Details about the generation of metadata
and object-relational mappings.
</p>
</li><li class="listitem">
<p>
<code class="literal">openjpa.Runtime</code>: General OpenJPA runtime messages.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9231"></a>
<code class="literal">openjpa.Query</code>: Messages about queries. Query strings and any
parameter values, if applicable, will be logged to the <code class="literal">TRACE</code>
level at execution time. Information about possible performance concerns will be
logged to the <code class="literal">INFO</code> level.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9239"></a>
<code class="literal">openjpa.DataCache</code>: Messages from the L2 data cache plugins.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9245"></a>
<code class="literal">openjpa.jdbc.JDBC</code>: JDBC connection information. General JDBC
information will be logged to the <code class="literal">TRACE</code> level. Information
about possible performance concerns will be logged to the <code class="literal">INFO
</code> level.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9253"></a>
<code class="literal">openjpa.jdbc.SQL</code>: This is the most common logging channel to
use. Detailed information about the execution of SQL statements will be sent to
the <code class="literal">TRACE</code> level. It is useful to enable this channel if you
are curious about the exact SQL that OpenJPA issues to the datastore.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
The SQL issued to the database may contain sensitive information. By default the
parameter values used in the prepared statements generated by OpenJPA will not
be printed in the SQL log - instead you will see a ? for each value. The actual
values may be printed by adding <code class="literal">PrintParameters=True</code> to the
<a class="link" href="#openjpa.ConnectionFactoryProperties" title="5.15.&nbsp; openjpa.ConnectionFactoryProperties">
<code class="literal">openjpa.ConnectionFactoryProperties</code></a> property. Also
see <a class="link" href="#ref_guide_dbsetup_builtin" title="1.&nbsp; Using the OpenJPA DataSource"><code class="literal">Using the OpenJPA
DataSource</code></a>
</div><p>
</p>
<p>
When using the built-in OpenJPA logging facilities, you can enable SQL logging
by adding <code class="literal">SQL=TRACE</code> to your <code class="literal">openjpa.Log</code>
property.
</p>
<p>
OpenJPA can optionally reformat the logged SQL to make it easier to read. To
enable pretty-printing, add <code class="literal">PrettyPrint=true</code> to the
<a class="link" href="#openjpa.ConnectionFactoryProperties" title="5.15.&nbsp; openjpa.ConnectionFactoryProperties"><code class="literal">
openjpa.ConnectionFactoryProperties</code></a> property. You can control
how many columns wide the pretty-printed SQL will be with the <code class="literal">
PrettyPrintLineLength</code> property. The default line length is 60 columns.
</p>
<p>
While pretty printing makes things easier to read, it can make output harder to
process with tools like grep.
</p>
<p>
Pretty-printing properties configuration might look like so:
</p>
<pre class="programlisting">
&lt;property name="openjpa.Log" value="SQL=TRACE"/&gt;
&lt;property name="openjpa.ConnectionFactoryProperties"
value="PrettyPrint=true, PrettyPrintLineLength=72"/&gt;
</pre>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9277"></a>
<code class="literal">openjpa.jdbc.SQLDiag</code>: This logging channel provides additional
information about entity actitvies such as create, find, update or delete, and eager
loading of relation or field properties. If you enable this channel, it is recommended
that <code class="literal">openjpa.jdbc.SQL</code> channel is also enabled.
The additional trace can help you relate the entity activities to the execution of
SQL statements that OpenJPA issued to the datastore.
</p>
<p>
When using the built-in OpenJPA logging facilities, you can enable SQLDiag logging
by adding <code class="literal">SQLDiag=TRACE</code> to your <code class="literal">openjpa.Log</code>
property.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9287"></a>
<code class="literal">openjpa.jdbc.Schema</code>: Details about operations on the
database schema.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_logging_openjpa"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
OpenJPA Logging
</h2></div></div></div>
<a class="indexterm" name="d5e9293"></a>
<p>
By default, OpenJPA uses a basic logging framework with the following output
format:
</p>
<p>
<code class="literal">millis</code>&nbsp;&nbsp;<code class="literal">diagnostic context</code>&nbsp;&nbsp;<code class="literal">level</code>&nbsp;&nbsp;[<code class="literal">thread name</code>]&nbsp;&nbsp;<code class="literal">channel</code> - <code class="literal">message</code>
</p>
<p>
For example, when loading an application that uses OpenJPA, a message like the
following will be sent to the <code class="literal">openjpa.Runtime</code> channel:
</p>
<pre class="programlisting">
2107 INFO [main] openjpa.Runtime - Starting OpenJPA 2.2.0
</pre>
<p>
The default logging system accepts the following parameters:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">File</code>: The name of the file to log to, or <code class="literal">stdout
</code> or <code class="literal">stderr</code> to send messages to standard out and
standard error, respectively. By default, OpenJPA sends log messages to standard
error.
</p>
</li><li class="listitem">
<p>
<code class="literal">DefaultLevel</code>: The default logging level of unconfigured
channels. Recognized values are <code class="literal">TRACE, INFO, WARN, ERROR </code>
and <code class="literal">FATAL</code>. Defaults to <code class="literal">INFO</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">DiagnosticContext</code>: A string that will be prepended to all
log messages. If this is not supplied and an <code class="literal">openjpa.Id</code>
property value is available, that value will be used.
</p>
</li><li class="listitem">
<p>
<code class="literal">&lt;channel&gt;</code>: Using the last token of the
<a class="link" href="#ref_guide_logging_channels" title="1.&nbsp; Logging Channels">logging channel</a> name, you can
configure the log level to use for that channel. See the examples below.
</p>
</li></ul></div>
<div class="example" id="ref_guide_logging_openjpa_std_ex"><p class="title"><b>Example&nbsp;3.1.&nbsp;
Standard OpenJPA Log Configuration
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_logging_openjpa_sql_ex"><p class="title"><b>Example&nbsp;3.2.&nbsp;
Standard OpenJPA Log Configuration + All SQL Statements
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_logging_openjpa_file"><p class="title"><b>Example&nbsp;3.3.&nbsp;
Logging to a File
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.Log" value="File=/tmp/org.apache.openjpa.log, DefaultLevel=WARN, Runtime=INFO, Tool=INFO"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_logging_noop"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Disabling Logging
</h2></div></div></div>
<a class="indexterm" name="d5e9339"></a>
<p>
Disabling logging can be useful to analyze performance without any I/O overhead
or to reduce verbosity at the console. To do this, set the <code class="literal">openjpa.Log
</code> property to <code class="literal">none</code>.
</p>
<p>
Disabling logging permanently, however, will cause all warnings to be consumed.
We recommend using one of the more sophisticated mechanisms described in this
chapter.
</p>
</div>
<div class="section" id="ref_guide_logging_log4j"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Log4J
</h2></div></div></div>
<a class="indexterm" name="d5e9348"></a>
<p>
When <code class="literal">openjpa.Log</code> is set to <code class="literal">log4j</code>, OpenJPA
will delegate to Log4J for logging. In a standalone application, Log4J logging
levels are controlled by a resource named <code class="filename">log4j.properties</code>
, which should be available as a top-level resource (either at the top level of
a jar file, or in the root of one of the <code class="literal">CLASSPATH</code>
directories). When deploying to a web or EJB application server, Log4J
configuration is often performed in a <code class="filename">log4j.xml</code> file
instead of a properties file. For further details on configuring Log4J, please
see the <a class="ulink" href="http://logging.apache.org/log4j/1.2/manual.html" target="_top">Log4J
Manual</a>. We present an example <code class="filename">log4j.properties</code> file
below.
</p>
<div class="example" id="ref_guide_logging_log4j_ex"><p class="title"><b>Example&nbsp;3.4.&nbsp;
Standard Log4J Logging
</b></p><div class="example-contents">
<pre class="programlisting">
log4j.rootCategory=WARN, console
log4j.category.openjpa.Tool=INFO
log4j.category.openjpa.Runtime=INFO
log4j.category.openjpa.Remote=WARN
log4j.category.openjpa.DataCache=WARN
log4j.category.openjpa.MetaData=WARN
log4j.category.openjpa.Enhance=WARN
log4j.category.openjpa.Query=WARN
log4j.category.openjpa.jdbc.SQL=WARN
log4j.category.openjpa.jdbc.SQLDiag=WARN
log4j.category.openjpa.jdbc.JDBC=WARN
log4j.category.openjpa.jdbc.Schema=WARN
log4j.appender.console=org.apache.log4j.ConsoleAppender
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_logging_commons"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Apache Commons Logging
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_logging_jdk14">5.1.
JDK java.util.logging
</a></span></dt></dl></div>
<a class="indexterm" name="d5e9364"></a>
<p>
Set the <code class="literal">openjpa.Log</code> property to <code class="literal">commons</code> to
use the <a class="ulink" href="http://commons.apache.org/logging/" target="_top"> Apache
Commons Logging</a> thin library for issuing log messages. The
Commons Logging library act as a wrapper around a number of popular logging
APIs, including the
<a class="ulink" href="http://logging.apache.org/log4j/1.2/index.html" target="_top"> Jakarta Log4J
</a> project, and the native
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html" target="_top">
java.util.logging</a> package in JDK.
</p>
<p>
When using the Commons Logging framework in conjunction with Log4J,
configuration will be the same as was discussed in the Log4J section above.
</p>
<div class="section" id="ref_guide_logging_jdk14"><div class="titlepage"><div><div><h3 class="title">5.1.&nbsp;
JDK java.util.logging
</h3></div></div></div>
<a class="indexterm" name="d5e9376"></a>
<p>
When using JDK logging in conjunction with OpenJPA's Commons Logging
support, logging will proceed through Java's built-in logging provided by the
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html" target="_top">
java.util.logging</a> package. For details on configuring the built-in
logging system, please see the
<a class="ulink" href="http://download.oracle.com/javase/6/docs/technotes/guides/logging/overview.html" target="_top">
Java Logging Overview</a>.
</p>
<p>
By default, JDK's logging package looks in the <code class="filename">
JAVA_HOME/lib/logging.properties</code> file for logging configuration. This
can be overridden with the <code class="literal">java.util.logging.config.file</code>
system property. For example:
</p>
<pre class="programlisting">
java -Djava.util.logging.config.file=mylogging.properties com.company.MyClass
</pre>
<div class="example" id="ref_guide_logging_jdk14_propfile"><p class="title"><b>Example&nbsp;3.5.&nbsp;
JDK Log Properties
</b></p><div class="example-contents">
<pre class="programlisting">
# specify the handlers to create in the root logger
# (all loggers are children of the root logger)
# the following creates two handlers
handlers=java.util.logging.ConsoleHandler, java.util.logging.FileHandler
# set the default logging level for the root logger
.level=ALL
# set the default logging level for new ConsoleHandler instances
java.util.logging.ConsoleHandler.level=INFO
# set the default logging level for new FileHandler instances
java.util.logging.FileHandler.level=ALL
# set the default formatter for new ConsoleHandler instances
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
# set the default logging level for all OpenJPA logs
openjpa.Tool.level=INFO
openjpa.Runtime.level=INFO
openjpa.Remote.level=INFO
openjpa.DataCache.level=INFO
openjpa.MetaData.level=INFO
openjpa.Enhance.level=INFO
openjpa.Query.level=INFO
openjpa.jdbc.SQL.level=INFO
openjpa.jdbc.SQLDiag.level=INFO
openjpa.jdbc.JDBC.level=INFO
openjpa.jdbc.Schema.level=INFO
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_logging_slf4j"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
SLF4J
</h2></div></div></div>
<a class="indexterm" name="d5e9391"></a>
<p>
When <code class="literal">openjpa.Log</code> is set to <code class="literal">slf4j</code>, OpenJPA
will delegate to SLF4J API for logging, which provides several adapters or
a simple logging mechanism. For further details on logging adapters and
configuring SLF4J, please see the
<a class="ulink" href="http://www.slf4j.org/manual.html" target="_top">SLF4J website</a>.
</p>
<p>
Note, as SLF4J does not provide a <code class="literal">FATAL</code> log level the
<code class="literal">SLF4JLogFactory</code> will map it to the <code class="literal">ERROR</code>
log level.
</p>
</div>
<div class="section" id="ref_guide_logging_custom"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
Custom Log
</h2></div></div></div>
<a class="indexterm" name="d5e9404"></a>
<p>
If none of available logging systems meet your needs, you can configure the
logging system with a custom logger. You might use custom logging to integrate
with a proprietary logging framework used by some applications servers, or for
logging to a graphical component for GUI applications.
</p>
<p>
A custom logging framework must include an implementation of the
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/log/LogFactory.html" target="_top"><code class="classname">
org.apache.openjpa.lib.log.LogFactory</code></a> interface. We present
a custom <code class="classname">LogFactory</code> below.
</p>
<div class="example" id="ref_guide_logging_custom_ex"><p class="title"><b>Example&nbsp;3.6.&nbsp;
Custom Logging Class
</b></p><div class="example-contents">
<pre class="programlisting">
package com.xyz;
import org.apache.openjpa.lib.log.*;
public class CustomLogFactory
implements LogFactory {
private String _prefix = "CUSTOM LOG";
public void setPrefix(String prefix) {
_prefix = prefix;
}
public Log getLog(String channel) {
// Return a simple extension of AbstractLog that will log
// everything to the System.err stream. Note that this is
// roughly equivalent to OpenJPA's default logging behavior.
return new AbstractLog() {
protected boolean isEnabled(short logLevel) {
// log all levels
return true;
}
protected void log(short type, String message, Throwable t) {
// just send everything to System.err
System.err.println(_prefix + ": " + type + ": "
+ message + ": " + t);
}
};
}
}
</pre>
</div></div><br class="example-break">
<p>
To make OpenJPA use your custom log factory, set the
<a class="link" href="#openjpa.Log" title="5.44.&nbsp; openjpa.Log"><code class="literal">openjpa.Log</code></a> configuration
property to your factory's full class name. Because this property is a plugin
property (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a> ), you can also
pass parameters to your factory. For example, to use the example factory above
and set its prefix to "LOG MSG", you would set the <code class="literal">openjpa.Log
</code> property to the following string:
</p>
<pre class="programlisting">
com.xyz.CustomLogFactory(Prefix="LOG MSG")
</pre>
</div>
<div class="section" id="ref_guide_audit"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;OpenJPA Audit</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#d5e9423">8.1. Configuration</a></span></dt><dt><span class="section"><a href="#d5e9445">8.2. Developing custom auditing</a></span></dt></dl></div>
Transactional applications often require to audit changes in persistent objects.
OpenJPA can enable audit facility for all persistent entities in few simple steps.
<div class="section" id="d5e9423"><div class="titlepage"><div><div><h3 class="title">8.1.&nbsp;Configuration</h3></div></div></div>
<p><span class="emphasis"><em>Annotate Persistent Entity</em></span>
Any persistence entity can be enabled for audit by annotating with
<code class="literal">org.apache.openjpa.audit.Auditable</code>.
</p>
<pre class="programlisting">
@javax.persistence.Entity
@org.apache.openjpa.audit.Auditable
public class MyDomainObject { ...}
</pre>
<p>
This <code class="literal">Auditable</code> annotation enables auditing of creation, update or delete of
<code class="literal">MyDomainObject</code> instances. The <code class="literal">Auditable</code> annotation accepts
list of enumerated values <code class="literal">org.apache.openjpa.audit.AuditableOperation</code> namely
<code class="literal">CREATE</code>, <code class="literal">UPDATE</code> and <code class="literal">DELETE</code> to customize
only appropriate operations be audited. By deafult, all of the above operations are audited.
</p>
<p><span class="emphasis"><em>Configure Persistence Configuration</em></span>
The audit facility is invoked at runtime via configuration of <code class="literal">META-INF/persistence.xml</code>.
The following property configures auditing via a default auditor
</p>
<pre class="programlisting">&lt;property name="openjpa.Auditor" value="default"/&gt;</pre>
<p>
The default auditor does not do much. It simply prints each auditable instance with its latest and original
states on a standard console (or to a designated file).
</p>
<p>The <span class="emphasis"><em>latest</em></span> state of an instance designates the state which is commited to the
database.
The <span class="emphasis"><em>original</em></span>state designates the state when the instance entered the managed persistent
context. For example, when a new instance is persisted or a existing instance is loaded from the database.
</p>
</div>
<div class="section" id="d5e9445"><div class="titlepage"><div><div><h3 class="title">8.2.&nbsp;Developing custom auditing</h3></div></div></div>
<p>
For real use case, an application will prefer more than printing the changed instances. The application, in
such case, needs to implement <code class="literal">org.apache.openjpa.audit.Auditor</code> interface.
This simple interface has the following method:
</p>
<pre class="programlisting">
/**
* OpenJPA runtime will invoke this method with the given parameters
* within a transaction.
*
* @param broker the active persistence context.
* @param newObjects the set of auditable objects being created. Can be empty, but never null.
* @param updates the set of auditable objects being updated. Can be empty, but never null.
* @param deletes the set of auditable objects being deleted. Can be empty, but never null.
*/
public void audit(Broker broker, Collection&lt;Audited&gt; newObjects, Collection&lt;Audited&gt; updates,
Collection&lt;Audited&gt; deletes);
</pre>
<p>
OpenJPA runtime will invoke this method <span class="emphasis"><em>before</em></span> database commit. Via this callback method,
the application receives
the auditable instances in three separate collections of <code class="literal">org.apache.openjpa.audit.Auditable</code>.
An <code class="literal">Auditable</code> instance provides the latest and original state of a persistent object.
The latest object is
the same persistent instance to be committed. The original instance is a transient instance holding the
original state of the instance when it entered the managed context. The active persistence context
is also supplied in this callback method, so that an application may decide to persist the audit log
in the same database.
</p>
<p>
It is important to note that the original object can not be persisted in the same transaction, because
it has the same persistent identity of the latest object.
</p>
<p>
A single instance of implemented <code class="literal">org.apache.openjpa.audit.Auditor</code> interface
is available for a persistence unit. However, an application's own implementation of this interface
need not be thread-safe, because OpenJPA runtime guards against concurrent invocation of the
callback method.
</p>
<p>
The <code class="literal">org.apache.openjpa.audit.Auditor</code> interface is configurable. Hence any bean style
getter and setter method on its implementation will be populated as usual for any other OpenJPA plugin.
In the following example,
</p>
<pre class="programlisting">
&lt;property name="openjpa.Auditor" value="com.acme.Auditor(param2=10,param2='hello')"/&gt;
</pre>
<p>
An instance of <code class="literal">com.acme.Auditor</code> will be instantiated and if it has been style getter and
setter methods for <code class="literal">param1</code> and <code class="literal">param2</code>, then the respective setters
will be called with <code class="literal">10</code> and <code class="literal">"hello"</code> before the instance being used.
</p>
</div>
</div>
</div>
<div class="chapter" id="ref_guide_dbsetup"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;4.&nbsp;
JDBC
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_dbsetup_builtin">1.
Using the OpenJPA DataSource
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_auto">1.1.
Optional Connection Pooling
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_config">1.2.
Configuring the OpenJPA DataSource
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbcp">1.3.
Configuring Apache Commons DBCP
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_thirdparty">2.
Using a Third-Party DataSource
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_thirdparty_enlist">2.1.
Managed and XA DataSources
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSatRuntime">2.2. Setting the DataSource at runtime</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSPerEM">2.2.1. Using different DataSources for each EntityManager</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSBenefits">2.2.1.1. Benefits</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSLimitations">2.2.1.2. Limitations</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSError">2.2.1.3. Error handling</a></span></dt></dl></dd></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_sqlconn">3.
Runtime Access to DataSource
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport">4.
Database Support
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_dbdictprops">4.1.
DBDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_firebird">4.2.
FirebirdDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_mysql">4.3.
MySQLDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_oracle">4.4.
OracleDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_sybase">4.5.
SybaseDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_db2">4.6.
DB2 Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_delim_id">4.7.
Delimited Identifiers Support
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_dbsetup_isolation">5.
Setting the Transaction Isolation
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_sql92">6.
Setting the SQL Join Syntax
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_multidb">7.
Accessing Multiple Databases
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_retain">8.
Configuring the Use of JDBC Connections
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_stmtbatch">9.
Statement Batching
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_lrs">10.
Large Result Sets
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_def">11.
Default Schema
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_info">12.
Schema Reflection
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_schema_info_list">12.1.
Schemas List
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_info_factory">12.2.
Schema Factory
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_schema_schematool">13.
Schema Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_xml">14.
XML Schema Format
</a></span></dt></dl></div>
<a class="indexterm" name="d5e9468"></a>
<p>
OpenJPA uses a relational database for object persistence.
It communicates with the database using the Java DataBase Connectivity (JDBC)
APIs. This chapter describes how to configure OpenJPA to work with the JDBC
driver for your database, and how to access JDBC functionality at runtime.
</p>
<div class="section" id="ref_guide_dbsetup_builtin"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Using the OpenJPA DataSource
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_dbsetup_auto">1.1.
Optional Connection Pooling
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_config">1.2.
Configuring the OpenJPA DataSource
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbcp">1.3.
Configuring Apache Commons DBCP
</a></span></dt></dl></div>
<a class="indexterm" name="d5e9473"></a>
<a class="indexterm" name="d5e9476"></a>
<p>
OpenJPA defines a <code class="classname">org.apache.openjpa.jdbc.schema.DriverDataSource</code> interface, which provides a simple <code class="classname">javax.sql.DataSource</code> wrapper implementation for the normal cases where <code class="literal">openjpa.ConnectionDriverName</code> refers to a <code class="classname">java.sql.Driver</code>.
See <a class="link" href="#openjpa.jdbc.DriverDataSource" title="6.3.&nbsp; openjpa.jdbc.DriverDataSource">
<code class="literal">openjpa.jdbc.DriverDataSource</code></a> for the list of
provided implementations.
</p>
<div class="section" id="ref_guide_dbsetup_auto"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Optional Connection Pooling
</h3></div></div></div>
<a class="indexterm" name="d5e9488"></a>
<a class="indexterm" name="d5e9491"></a>
<p>
Starting with OpenJPA 2.1, a new <code class="classname">org.apache.openjpa.jdbc.schema.AutoDriverDataSource</code>
is provided as the default, which will automatically
select between the old <code class="classname">SimpleDriverDataSource</code> and a new
<code class="classname">DBCPDriverDataSource</code> implementation based on if
<a class="ulink" href="https://commons.apache.org/dbcp/" target="_top">Apache Commons DBCP2</a>
has been provided on the classpath and OpenJPA is not running in a container
managed mode or with managed transactions. Note, that only the
<code class="literal">openjpa-all.jar</code> includes Commons DBCP2, so you will need to
include the <code class="literal">commons-dbcp2.jar</code> from the OpenJPA binary
distribution if you are using the normal <code class="literal">openjpa.jar</code>.
</p>
<p>
To disable the automatic usage of Apache Commons DBCP when it is discovered
on the classpath, set
<code class="literal">openjpa.jdbc.DriverDataSource=simple</code>, which will revert
OpenJPA to the prior behavior of using <code class="classname">org.apache.openjpa.jdbc.schema.SimpleDriverDataSource</code>
</p>
<p>
To force usage of Apache Commons DBCP2, which will cause a fatal exception to
be thrown if it cannot be loaded from the classpath, set
<code class="literal">openjpa.jdbc.DriverDataSource=dbcp</code>, which will cause
OpenJPA to use <code class="classname">org.apache.commons.dbcp2.BasicDataSource</code>
</p>
</div>
<div class="section" id="ref_guide_dbsetup_config"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Configuring the OpenJPA DataSource
</h3></div></div></div>
<a class="indexterm" name="d5e9510"></a>
<p>
If you choose to use OpenJPA's <code class="classname">DataSource</code>,
then you must specify the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e9518"></a>
<code class="literal">openjpa.ConnectionUserName</code>: The JDBC user name for
connecting to the database.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9523"></a>
<code class="literal">openjpa.ConnectionPassword</code>: The JDBC password for the above
user.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9528"></a>
<code class="literal">openjpa.ConnectionURL</code>: The JDBC URL for the database.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9533"></a>
<code class="literal">openjpa.ConnectionDriverName</code>: The JDBC driver class.
</p>
</li></ul></div>
<p>
To configure advanced features, use the following optional
properties. The syntax of these property strings follows the syntax of OpenJPA
plugin parameters described in <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e9541"></a>
<a class="link" href="#openjpa.ConnectionProperties" title="5.19.&nbsp; openjpa.ConnectionProperties">
<code class="literal">openjpa.ConnectionProperties</code></a>: If the listed driver is an
instance of <code class="classname">java.sql.Driver</code>, this string will be parsed
into a <code class="classname">Properties</code> instance, which will then be used to
obtain database connections through the <code class="methodname">Driver.connect(String url,
Properties props)</code> method. If, on the other hand, the listed driver
is a <code class="classname"> javax.sql.DataSource</code>, the string will be treated
as a plugin properties string, and matched to the bean setter methods of the
<code class="classname">DataSource</code> instance.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9552"></a>
<a class="link" href="#openjpa.ConnectionFactoryProperties" title="5.15.&nbsp; openjpa.ConnectionFactoryProperties">
<code class="literal">openjpa.ConnectionFactoryProperties</code></a>: OpenJPA's built-in
<code class="classname">DataSource</code> allows you to set the following options via
this plugin string:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<a class="indexterm" name="d5e9560"></a>
<code class="literal">QueryTimeout</code>: The maximum number of seconds the JDBC driver
will wait for a statement to execute.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9566"></a>
<code class="literal">PrettyPrint</code>: Boolean indicating whether to pretty-print
logged SQL statements.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9572"></a>
<code class="literal">PrettyPrintLineLength</code>: The maximum number of characters in
each pretty-printed SQL line.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9578"></a>
<code class="literal">PrintParameters</code>: A boolean indicating whether SQL parameter
values will be included in exception text and when logging is enabled. Since
the parameter values may contain sensitive information the default value is
false.
</p>
</li></ul></div>
</li></ul></div>
<div class="example" id="ref_guide_dbsetup_builtin_ex"><p class="title"><b>Example&nbsp;4.1.&nbsp;
Properties for the OpenJPA DataSource
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.ConnectionUserName" value="user"/&gt;
&lt;property name="openjpa.ConnectionPassword" value="pass"/&gt;
&lt;property name="openjpa.ConnectionURL" value="jdbc:hsqldb:db-hypersonic"/&gt;
&lt;property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver"/&gt;
&lt;property name="openjpa.ConnectionFactoryProperties"
value="PrettyPrint=true, PrettyPrintLineLength=80, PrintParameters=true"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_dbsetup_dbcp"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Configuring Apache Commons DBCP
</h3></div></div></div>
<a class="indexterm" name="d5e9587"></a>
<p>
Additional Commons DBCP arguments can be provided in
<code class="literal">openjpa.connectionProperties</code>, such as:
</p><pre class="programlisting">
MaxTotal=10,MaxIdle=5,MinIdle=2,MaxWait=60000
</pre><p>
Please visit the Commons DBCP website for the entire list of
<a class="ulink" href="http://commons.apache.org/dbcp/configuration.html" target="_top">configuration options</a> and explanations.
</p>
</div>
</div>
<div class="section" id="ref_guide_dbsetup_thirdparty"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Using a Third-Party DataSource
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_dbsetup_thirdparty_enlist">2.1.
Managed and XA DataSources
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSatRuntime">2.2. Setting the DataSource at runtime</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSPerEM">2.2.1. Using different DataSources for each EntityManager</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSBenefits">2.2.1.1. Benefits</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSLimitations">2.2.1.2. Limitations</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSError">2.2.1.3. Error handling</a></span></dt></dl></dd></dl></dd></dl></div>
<a class="indexterm" name="d5e9596"></a>
<p>
You can use OpenJPA with any third-party <code class="classname">javax.sql.DataSource
</code>. There are multiple ways of telling OpenJPA about a <code class="classname">
DataSource</code>:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e9605"></a>
Set the <code class="classname">DataSource</code> into the map passed to <code class="methodname">
Persistence.createEntityManagerFactory</code> under the
<a class="link" href="#openjpa.ConnectionFactory" title="5.10.&nbsp; openjpa.ConnectionFactory"><code class="literal">openjpa.ConnectionFactory
</code></a> key.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9613"></a>
Bind the <code class="classname">DataSource</code> into JNDI, and then specify its
location in the <code class="literal">jta-data-source</code> or
<code class="literal">non-jta-data-source</code> element of the
<a class="link" href="#jpa_overview_persistence_xml" title="1.&nbsp; persistence.xml">JPA XML format</a> (depending on
whether the <code class="classname">DataSource</code> is managed by JTA), or in the
<a class="link" href="#openjpa.ConnectionFactoryName" title="5.12.&nbsp; openjpa.ConnectionFactoryName">
<code class="literal">openjpa.ConnectionFactoryName</code></a> property.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9624"></a>
Specify the full class name of the <code class="classname">DataSource</code>
implementation in the <a class="link" href="#openjpa.ConnectionDriverName" title="5.8.&nbsp; openjpa.ConnectionDriverName">
<code class="literal">openjpa.ConnectionDriverName</code></a> property in place of a JDBC
driver. In this configuration OpenJPA will instantiate an instance of the named
class via reflection. It will then configure the <code class="classname">DataSource
</code> with the properties in the
<a class="link" href="#openjpa.ConnectionProperties" title="5.19.&nbsp; openjpa.ConnectionProperties">
<code class="literal">openjpa.ConnectionProperties</code></a> setting.
</p>
</li></ul></div>
<p>
The features of OpenJPA's own <code class="classname">DataSource</code> can
also be used with third-party implementations. OpenJPA layers on top of the
third-party <code class="classname">DataSource</code> to provide the extra
functionality. To configure these features use the
<a class="link" href="#openjpa.ConnectionFactoryProperties" title="5.15.&nbsp; openjpa.ConnectionFactoryProperties">
<code class="literal">openjpa.ConnectionFactoryProperties</code></a> property described
in the previous section.
</p>
<div class="example" id="ref_guide_dbsetup_thirdparty_ex"><p class="title"><b>Example&nbsp;4.2.&nbsp;
Properties File for a Third-Party DataSource
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.ConnectionDriverName" value="oracle.jdbc.pool.OracleDataSource"/&gt;
&lt;property name="openjpa.ConnectionProperties"
value="PortNumber=1521, ServerName=saturn, DatabaseName=solarsid, DriverType=thin"/&gt;
&lt;property name="openjpa.ConnectionFactoryProperties" value="QueryTimeout=5000"/&gt;
</pre>
<p>
You can also force the Apache Commons DBCP BasicDataSource to be used for
connection pooling when provided on the classpath by substituting it as the
<code class="literal">ConnectionDriverName</code> and setting
<code class="literal">ConnectionProperties=DriverClassName</code> to the actual JDBC
driver value -
</p>
<pre class="programlisting">
&lt;property name="openjpa.ConnectionDriverName" value="org.apache.commons.dbcp.BasicDataSource"/&gt;
&lt;property name="openjpa.ConnectionProperties"
value="DriverClassName=oracle.jdbc.pool.OracleDataSource, PortNumber=1521, ServerName=saturn, DatabaseName=solarsid, DriverType=thin, MaxIdle=0"/&gt;
&lt;property name="openjpa.ConnectionFactoryProperties" value="QueryTimeout=5000"/&gt;
</pre>
</div></div><br class="example-break">
<div class="section" id="ref_guide_dbsetup_thirdparty_enlist"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
Managed and XA DataSources
</h3></div></div></div>
<a class="indexterm" name="d5e9646"></a>
<a class="indexterm" name="d5e9649"></a>
<p>
<a class="indexterm" name="d5e9653"></a>
Certain application servers automatically enlist their <code class="classname"> DataSource
</code>s in global transactions. When this is the case, OpenJPA should not
attempt to commit the underlying connection, leaving JDBC transaction completion
to the application server. To notify OpenJPA that your third-party <code class="classname">
DataSource</code> is managed by the application server, use the
<code class="literal">jta-data-source</code> element of your <code class="filename">
persistence.xml</code> file or set the
<a class="link" href="#openjpa.ConnectionFactoryMode" title="5.14.&nbsp; openjpa.ConnectionFactoryMode">
<code class="literal">openjpa.ConnectionFactoryMode</code></a> property to
<code class="literal">managed</code>.
</p>
<p>
Note that OpenJPA can only use managed <code class="classname">DataSource</code>s when
it is also integrating with the application server's managed transactions. Also
note that all XA <code class="classname">DataSource</code>s are enlisted, and you must
set this property when using any XA <code class="classname"> DataSource</code>.
</p>
<p>
When using a managed <code class="classname">DataSource</code>, you should also
configure a second unmanaged <code class="classname">DataSource</code> that OpenJPA can
use to perform tasks that are independent of the global transaction. The most
common of these tasks is updating the sequence table OpenJPA uses to generate
unique primary key values for your datastore identity objects. Configure the
second <code class="classname">DataSource</code> using the <code class="literal">non-jta-data-source
</code> <code class="filename">persistence.xml</code> element, or OpenJPA's various
"2" connection properties, such as <code class="literal">openjpa.ConnectionFactory2Name
</code> or <code class="literal">openjpa.Connection2DriverName</code>. These
properties are outlined in <a class="xref" href="#ref_guide_conf" title="Chapter&nbsp;2.&nbsp; Configuration">Chapter&nbsp;2, <i>
Configuration
</i></a>.
</p>
<div class="example" id="ref_guide_enterprise_xa_conf_ex"><p class="title"><b>Example&nbsp;4.3.&nbsp;
Managed DataSource Configuration
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;!-- managed DataSource --&gt;
&lt;jta-data-source&gt;java:/OracleXASource&lt;/jta-data-source&gt;
&lt;properties&gt;
&lt;!-- use OpenJPA's built-in DataSource for unmanaged connections --&gt;
&lt;property name="openjpa.Connection2UserName" value="scott"/&gt;
&lt;property name="openjpa.Connection2Password" value="tiger"/&gt;
&lt;property name="openjpa.Connection2URL" value="jdbc:oracle:thin:@CROM:1521:OpenJPADB"/&gt;
&lt;property name="openjpa.Connection2DriverName" value="oracle.jdbc.driver.OracleDriver"/&gt;
&lt;/properties&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_dbsetup_setDSatRuntime"><div class="titlepage"><div><div><h3 class="title">2.2.&nbsp;Setting the DataSource at runtime</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_dbsetup_setDSPerEM">2.2.1. Using different DataSources for each EntityManager</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_dbsetup_setDSBenefits">2.2.1.1. Benefits</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSLimitations">2.2.1.2. Limitations</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSError">2.2.1.3. Error handling</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e9680"></a>
<p>
As mentioned above, the JTA and Non-JTA DataSources may be passed in as configuration properties
at EntityManagerFactory creation. Either the JPA standard properties (
<code class="literal">javax.persistence.jtaDataSource</code>, <code class="literal">java.persistence.nonJtaDataSource</code>)
or their OpenJPA specific equivalents (<code class="literal">openjpa.ConnectionFactoryName</code>,
<code class="literal">openjpa.ConnectionFactory2Name</code>) may be used. One use case for this function is to
store production connection information in configuration files but override the value when testing.
</p>
<p>
</p><div class="example" id="d5e9689"><p class="title"><b>Example&nbsp;4.4.&nbsp;
Setting DataSource at Runtime
</b></p><div class="example-contents">
<pre class="programlisting">Map&lt;Object,Object&gt; props = new HashMap&lt;Object,Object&gt;();
props.put("javax.persistence.jtaDataSource", "jdbc/myDataSource");
props.put("javax.persistence.nonJtaDataSource", "jdbc/myNonJTADataSource");
emf = Persistence.createEntityManagerFactory("example", props);</pre>
</div></div><p><br class="example-break">
</p>
<div class="section" id="ref_guide_dbsetup_setDSPerEM"><div class="titlepage"><div><div><h4 class="title">2.2.1.&nbsp;Using different DataSources for each EntityManager</h4></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_dbsetup_setDSBenefits">2.2.1.1. Benefits</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSLimitations">2.2.1.2. Limitations</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_setDSError">2.2.1.3. Error handling</a></span></dt></dl></div>
<p>
The JPA specification allows the DataSource (ConnectionFactory) to be specified on the
EntityManagerFactory. OpenJPA extends this support and allows each EntityManager to override the
DataSource from the EntityManagerFactory. It's expected that the EntityManagerFactory will also be
configured with a valid JTA / Non-JTA DataSource. The DataSource configured on the
EntityManagerFactory will be used to obtain a DBDictionary and (rarely) to gather some information
about the database in use (e.g. version, JDBC driver version).
</p>
<p>
If the EntityManagerFactory is not configured with a valid DataSource there are
a few additional caveats.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>The <code class="literal">openjpa.DBDictionary</code> property must be
used to ensure the correct DBDictionary is used.</p></li><li class="listitem"><p>OpenJPA will always attempt to obtain a DataSource from JNDI
based on the configuration for the EntityManagerFactory. When a JNDI name is
specified on the EntityManager this lookup happens slightly earlier than
normal. If the lookup fails the JNDI name provided at EntityManager creation
will be set into the EntityManagerFactory's configuration and used in
subsequent attempts. </p></li></ul></div><p>
</p>
<div class="section" id="ref_guide_dbsetup_setDSBenefits"><div class="titlepage"><div><div><h5 class="title">2.2.1.1.&nbsp;Benefits</h5></div></div></div>
<p>
In effect this option allows a single set of entity definitions to be shared
between multiple database instances or schemas within an instance. This can be
highly beneficial when there are a large number of entity definitions (e.g. &gt;
200), or a large number of databases / schemas in use.
</p>
</div>
<div class="section" id="ref_guide_dbsetup_setDSLimitations"><div class="titlepage"><div><div><h5 class="title">2.2.1.2.&nbsp;Limitations</h5></div></div></div>
<p>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>The same database type and version must be used by each
EntityManager. OpenJPA will use the same DBDictionary for each
EntityManager and will make no attempt to alter SQL syntax
between EntityManager instances.
</p>
</li><li class="listitem"><p>It is the application's responsibility to ensure
that the schema is identical on each database.</p></li><li class="listitem"><p>The application may not specify schema names for
individual entities.</p></li><li class="listitem">
<p>The DataSource (ConnectionFactory) name may only be
specified when the EntityManager is created. The DataSource
may not be switched while an EntityManager is in use.
</p>
</li><li class="listitem"><p>The L2 cache (DataCache) should not be used if
different DataSources are specified for each EntityManager</p>
</li><li class="listitem"><p>SynchronizeMappings should not be used with this
feature.</p></li><li class="listitem"><p>Table and Sequence generators should not be used
with this feature.</p></li><li class="listitem"><p>It is not required, but is recommended that the
<code class="literal">openjpa.DBDictionary</code> property be specified when
using this feature</p></li></ul></div><p>
</p>
</div>
<div class="section" id="ref_guide_dbsetup_setDSError"><div class="titlepage"><div><div><h5 class="title">2.2.1.3.&nbsp;Error handling</h5></div></div></div>
<p>
If a JTA DataSource is not available when the EntityManager is created, an
<code class="literal">IllegalArgumentException</code> will be thrown.
The EntityManager will not fall back to the JTA DataSource defined in the
configuration.
</p>
<p>
The same logic applies if a Non-JTA DataSource is not available when the
EntityManager is created. OpenJPA will not fall back to the configured
Non-JTA DataSource.
</p>
</div>
</div>
</div>
</div>
<div class="section" id="ref_guide_dbsetup_sqlconn"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Runtime Access to DataSource
</h2></div></div></div>
<a class="indexterm" name="d5e9733"></a>
<a class="indexterm" name="d5e9736"></a>
<p>
The JPA standard defines how to access JDBC connections from enterprise beans.
OpenJPA also provides APIs to retrieve a connection directly from the <code class="classname">
EntityManagerFactory</code>'s <code class="classname">DataSource</code>.
</p>
<p>
The <code class="methodname">EntityManager.unwrap(java.sql.Connection.class)</code> method
returns an <code class="classname">EntityManager</code>'s connection. If the <code class="classname">
EntityManager</code> does not already have a connection, it will obtain
one. The returned connection is only guaranteed to be transactionally consistent
with other <code class="classname">EntityManager</code> operations if the <code class="classname">
EntityManager</code> is in a managed or non-optimistic transaction, if the
<code class="classname">EntityManager</code> has flushed in the current transaction, or
if you have used the <code class="methodname">OpenJPAEntityManager.beginStore</code>
method to ensure that a datastore transaction is in progress. Always close the
returned connection before attempting any other <code class="classname">EntityManager
</code> operations. OpenJPA will ensure that the underlying native
connection is not released if a datastore transaction is in progress.
</p>
<div class="example" id="ref_guide_dbsetup_conn_jpa"><p class="title"><b>Example&nbsp;4.5.&nbsp;
Using the EntityManager's Connection
</b></p><div class="example-contents">
<pre class="programlisting">
import java.sql.Connection;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
...
EntityManager em = emf.createEntityManager();
Connection conn = (Connection) em.unwrap(java.sql.Connection.class);
// do JDBC stuff
conn.close();
</pre>
</div></div><br class="example-break">
<p>
The example below shows how to use a connection directly from the <code class="classname">
DataSource</code>, rather than using an <code class="classname"> EntityManager
</code>'s connection.
</p>
<div class="example" id="ref_guide_dbsetup_conn_from_factory_jpa"><p class="title"><b>Example&nbsp;4.6.&nbsp;
Using the EntityManagerFactory's DataSource
</b></p><div class="example-contents">
<pre class="programlisting">
import java.sql.*;
import javax.sql.*;
import org.apache.openjpa.conf.*;
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManagerFactory kemf = OpenJPAPersistence.cast(emf);
OpenJPAConfiguration conf = kemf.getConfiguration();
DataSource dataSource = (DataSource) conf.getConnectionFactory();
Connection conn = dataSource.getConnection();
// do JDBC stuff
conn.close();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_dbsetup_dbsupport"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Database Support
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_dbsetup_dbdictprops">4.1.
DBDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_firebird">4.2.
FirebirdDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_mysql">4.3.
MySQLDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_oracle">4.4.
OracleDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_sybase">4.5.
SybaseDictionary Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_db2">4.6.
DB2 Properties
</a></span></dt><dt><span class="section"><a href="#ref_guide_dbsetup_dbsupport_delim_id">4.7.
Delimited Identifiers Support
</a></span></dt></dl></div>
<a class="indexterm" name="d5e9762"></a>
<a class="indexterm" name="d5e9764"></a>
<p>
OpenJPA can take advantage of any JDBC 2.x compliant
driver, making almost any major database a candidate for use. See our officially
supported database list in <a class="xref" href="#supported_databases" title="Appendix&nbsp;2.&nbsp; Supported Databases">Appendix&nbsp;2, <i>
Supported Databases
</i></a> for more
information. Typically, OpenJPA auto-configures its JDBC behavior and SQL
dialect for your database, based on the values of your connection-related
configuration properties.
</p>
<p>
If OpenJPA cannot detect what type of database you are using, or if you are
using an unsupported database, you will have to tell OpenJPA what
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/DBDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.DBDictionary</code></a> to use.
The <code class="classname">DBDictionary</code> abstracts away the differences between
databases. You can plug a dictionary into OpenJPA using the
<a class="link" href="#openjpa.jdbc.DBDictionary" title="6.2.&nbsp; openjpa.jdbc.DBDictionary"><code class="literal">openjpa.jdbc.DBDictionary
</code></a> configuration property. The built-in dictionaries are listed
below. If you are using an unsupported database, you may have to write your own
<code class="classname">DBDictionary</code> subclass, a simple process.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e9780"></a>
<code class="literal">access</code>: Dictionary for Microsoft Access. This is an alias
for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/AccessDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.AccessDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9787"></a>
<code class="literal">db2</code>: Dictionary for IBM's DB2 database. This is an alias for
the <a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/DB2Dictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.DB2Dictionary</code></a> class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9794"></a>
<code class="literal">derby</code>: Dictionary for the Apache Derby database. This is an
alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/DerbyDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.DerbyDictionary</code> class.
</a>
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9801"></a>
<code class="literal">empress</code>: Dictionary for Empress database This is an alias
for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/EmpressDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.EmpressDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9808"></a>
<code class="literal">foxpro</code>: Dictionary for Microsoft Visual FoxPro. This is an
alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/FoxProDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.FoxProDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9815"></a>
<code class="literal">h2</code>: Dictionary for the H2 Database Engine. This is an
alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/H2Dictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.H2Dictionary</code></a> class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9822"></a>
<code class="literal">hsql</code>: Dictionary for the Hypersonic SQL database. This is an
alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/HSQLDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.HSQLDictionary</code></a> class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9829"></a>
<code class="literal">informix</code>: Dictionary for the Informix database. This is an
alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/InformixDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.InformixDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9836"></a>
<code class="literal">ingres</code>: Dictionary for Ingres. This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/IngresDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.IngresDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9843"></a>
<code class="literal">jdatastore</code>: Dictionary for Borland JDataStore. This is an
alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/JDataStoreDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.JDataStoreDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9850"></a>
<code class="literal">mariadb</code>: Dictionary for the MariaDB database. This is an alias
for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/MariaDBDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.MariaDBDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9857"></a>
<code class="literal">mysql</code>: Dictionary for the MySQL database. This is an alias
for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/MySQLDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.MySQLDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9864"></a>
<code class="literal">oracle</code>: Dictionary for Oracle. This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/OracleDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.OracleDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9871"></a>
<code class="literal">pointbase</code>: Dictionary for Pointbase Embedded database. This
is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/PointbaseDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.PointbaseDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9878"></a>
<code class="literal">postgres</code>: Dictionary for PostgreSQL. This is an alias for
the <a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/PostgresDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.PostgresDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9885"></a>
<code class="literal">soliddb</code>: Dictionary for IBM's SolidDB database.
This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/SolidDBDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.SolidDBDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9892"></a>
<code class="literal">sqlserver</code>: Dictionary for Microsoft's SQL Server database.
This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/SQLServerDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.SQLServerDictionary</code></a>
class.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e9899"></a>
<code class="literal">sybase</code>: Dictionary for Sybase. This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/SybaseDictionary.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.SybaseDictionary</code></a>
class.
</p>
</li></ul></div>
<p>
The example below demonstrates how to set a dictionary and configure its
properties in your configuration file. The <code class="literal">DBDictionary</code>
property uses OpenJPA's <a class="link" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">plugin syntax
</a>.
</p>
<div class="example" id="ref_guide_dbsetup_dbdict"><p class="title"><b>Example&nbsp;4.7.&nbsp;
Specifying a DBDictionary
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.DBDictionary" value="hsql(SimulateLocking=true)"/&gt;
</pre>
</div></div><br class="example-break">
<div class="section" id="ref_guide_dbsetup_dbdictprops"><div class="titlepage"><div><div><h3 class="title">4.1.&nbsp;
DBDictionary Properties
</h3></div></div></div>
<p>
The standard dictionaries all recognize the following properties. These
properties will usually not need to be overridden, since the dictionary
implementation should use the appropriate default values for your database. You
typically won't use these properties unless you are designing your own
<code class="classname">DBDictionary</code> for an unsupported database.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem" id="DBDictionary.AllowsAliasInBulkClause">
<p>
<a class="indexterm" name="d5e9917"></a>
<code class="literal">AllowsAliasInBulkClause</code>:
When true, SQL delete and update statements may use table aliases.
</p>
</li><li class="listitem" id="DBDictionary.ArrayTypeName">
<p>
<a class="indexterm" name="d5e9923"></a>
<code class="literal">ArrayTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.ARRAY</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.AutoAssignClause">
<p>
<a class="indexterm" name="d5e9931"></a>
<code class="literal">AutoAssignClause</code>: The column definition clause to append to
a creation statement. For example, <code class="literal">"AUTO_INCREMENT"</code> for
MySQL. This property is set automatically in the dictionary, and should not need
to be overridden, and is only used when the schema is generated using the
<code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.AutoAssignTypeName">
<p>
<a class="indexterm" name="d5e9940"></a>
<a class="indexterm" name="d5e9943"></a>
<code class="literal">AutoAssignTypeName</code>:
The column type name for auto-increment
columns. For example, <code class="literal">"BIGSERIAL"</code> for PostgreSQL. This
property is set automatically in the dictionary and should not need to be
overridden. It is used only when the schema is generated using the
<code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.BatchLimit">
<p>
<a class="indexterm" name="d5e9952"></a>
<code class="literal">BatchLimit</code>:
The default batch limit for sending multiple SQL statements at once to the
database. A value of -1 indicates unlimited batching, and any positive integer
indicates the maximum number of SQL statements to batch together.
Defaults to 0 which disables batching.
</p>
</li><li class="listitem" id="DBDictionary.BigintTypeName">
<p>
<a class="indexterm" name="d5e9958"></a>
<code class="literal">BigintTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.BIGINT</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.BinaryTypeName">
<p>
<a class="indexterm" name="d5e9966"></a>
<code class="literal">BinaryTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.BINARY</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.BitTypeName">
<p>
<a class="indexterm" name="d5e9974"></a>
<code class="literal">BitTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.BIT</code>. This is used only when the schema is generated by
the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.BlobBufferSize">
<p>
<a class="indexterm" name="d5e9982"></a>
<code class="literal">BlobBufferSize</code>: This property establishes the buffer size in
the <code class="literal">INSERT/UPDATE</code> operations with an
<code class="literal">java.io.InputStream</code>. This is only used with OpenJPA's
<a class="xref" href="#ref_guide_streamsupport" title="7.11.&nbsp; LOB Streaming">Section&nbsp;7.11, &#8220;
LOB Streaming
&#8221;</a>. Defaults to 50000.
</p>
</li><li class="listitem" id="DBDictionary.BlobTypeName">
<p>
<a class="indexterm" name="d5e9991"></a>
<a class="indexterm" name="d5e9994"></a>
<code class="literal">BlobTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.BLOB</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.BooleanRepresentation">
<p>
<a class="indexterm" name="d5e10002"></a>
<code class="literal">BooleanRepresentation</code>:
The overridden default representation for <code class="literal">java.lang.Boolean</code> or
<code class="literal">boolean</code> fields in JPA Entities. A
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/BooleanRepresentation.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.sql.BooleanRepresentation</code></a>
describes how Boolean values in entities get mapped into the database by default.
Note that you additionally might need to define the <code class="literal">BooleanTypeName</code>
<code class="literal">BitTypeName</code> settings to fit your selected BooleanRepresenation.
</p>
</li><li class="listitem" id="DBDictionary.BooleanTypeName">
<p>
<a class="indexterm" name="d5e10014"></a>
<code class="literal">BooleanTypeName</code>:
The overridden default column type for
<code class="literal">java.sql.Types.BOOLEAN</code>. This is used only when the schema
is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.CastFunction">
<p>
<a class="indexterm" name="d5e10022"></a>
<code class="literal">CastFunction</code>:
The SQL function call to cast a value to another SQL type.
Use the tokens <code class="literal">{0}</code> and <code class="literal">{1}</code> to represent
the two arguments. The result of the function is convert the
<code class="literal">{0}</code> value to a <code class="literal">{1}</code> type.
The default is <code class="literal">"CAST({0} AS {1})"</code>.
</p>
</li><li class="listitem" id="DBDictionary.CatalogSeparator">
<p>
<a class="indexterm" name="d5e10033"></a>
<code class="literal">CatalogSeparator</code>: The string the database uses to delimit
between the schema name and the table name. This is typically <code class="literal">"."
</code>, which is the default.
</p>
</li><li class="listitem" id="DBDictionary.CharTypeName">
<p>
<a class="indexterm" name="d5e10040"></a>
<code class="literal">CharTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.CHAR</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.CharacterColumnSize">
<p>
<a class="indexterm" name="d5e10048"></a>
<code class="literal">CharacterColumnSize</code>: The default size of <code class="literal">varchar
</code> and <code class="literal">char</code> columns. Typically 255.
</p>
</li><li class="listitem" id="DBDictionary.ClobBufferSize">
<p>
<a class="indexterm" name="d5e10056"></a>
<code class="literal">ClobBufferSize</code>: This property establish the buffer size in
the <code class="literal">INSERT/UPDATE</code> operations with a
<code class="literal">java.io.Reader</code>. This is only used with OpenJPA's
<a class="xref" href="#ref_guide_streamsupport" title="7.11.&nbsp; LOB Streaming">Section&nbsp;7.11, &#8220;
LOB Streaming
&#8221;</a>. Defaults to 50000.
</p>
</li><li class="listitem" id="DBDictionary.ClobTypeName">
<p>
<a class="indexterm" name="d5e10065"></a>
<a class="indexterm" name="d5e10068"></a>
<code class="literal">ClobTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.CLOB</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.ClosePoolSQL">
<p>
<a class="indexterm" name="d5e10076"></a>
<code class="literal">ClosePoolSQL</code>:
A special command to issue to the database when shutting down the pool.
Usually the pool of connections to the database is closed when the
application is ending. For embedded databases, whose lifecycle is
coterminous with the application, there may be a special
command, usually <code class="literal">"SHUTDOWN"</code>,
that will cause the embedded database to close cleanly.
Defaults to <code class="literal">null</code>.
</p>
</li><li class="listitem" id="DBDictionary.ConcatenateFunction">
<p>
<a class="indexterm" name="d5e10084"></a>
<code class="literal">ConcatenateFunction</code>:
The SQL function call or operation to concatenate two strings.
Use the tokens <code class="literal">{0}</code> and <code class="literal">{1}</code> to represent
the two arguments. The result of the function or operation is to concatenate
the <code class="literal">{1}</code> string to the end of the <code class="literal">{0}</code>
string. Defaults to <code class="literal">"({0}||{1})"</code>.
</p>
</li><li class="listitem" id="DBDictionary.ConstraintNameMode">
<p>
<a class="indexterm" name="d5e10095"></a>
<code class="literal">ConstraintNameMode</code>: When creating constraints, whether to
put the constraint name before the definition (<code class="literal">"before"</code>),
just after the constraint type name (<code class="literal">"mid"</code>), or after the
constraint definition (<code class="literal">"after"</code>).
Defaults to <code class="literal">"before"</code>.
</p>
</li><li class="listitem" id="DBDictionary.CreatePrimaryKeys">
<p>
<a class="indexterm" name="d5e10105"></a>
<code class="literal">CreatePrimaryKeys</code>: When false, do not
create database primary keys for identifiers. Defaults to <code class="literal">true
</code>.
</p>
</li><li class="listitem" id="DBDictionary.CrossJoinClause">
<p>
<a class="indexterm" name="d5e10112"></a>
<code class="literal">CrossJoinClause</code>: The clause to use for a cross join
(cartesian product). Defaults to <code class="literal">"CROSS JOIN"</code>.
</p>
</li><li class="listitem" id="DBDictionary.CurrentDateFunction">
<p>
<a class="indexterm" name="d5e10119"></a>
<code class="literal">CurrentDateFunction</code>:
The SQL function call to obtain the current date from the database.
Defaults to <code class="literal">"CURRENT_DATE"</code>.
</p>
</li><li class="listitem" id="DBDictionary.CurrentTimeFunction">
<p>
<a class="indexterm" name="d5e10126"></a>
<code class="literal">CurrentTimeFunction</code>:
The SQL function call to obtain the current time from the database.
Defaults to <code class="literal">"CURRENT_TIME"</code>.
</p>
</li><li class="listitem" id="DBDictionary.CurrentTimestampFunction">
<p>
<a class="indexterm" name="d5e10133"></a>
<code class="literal">CurrentTimestampFunction</code>:
The SQL function call to obtain the current timestamp from the database.
Defaults to <code class="literal">"CURRENT_TIMESTAMP"</code>.
</p>
</li><li class="listitem" id="DBDictionary.DateFractionDigits">
<p>
<a class="indexterm" name="d5e10140"></a>
<code class="literal">DateFractionDigits</code>
Some databases support to store sub-second fraction values.
The digits to store can sometimes be configured.
This value defines the default number of digits to store in the database.
A <code class="code">dateFractionDigits=3</code> will e.g. lead to a <code class="code">DATETIME(3)</code> on some databases.
Note that this default can be overwritten to an integer value n per column via
<code class="code">@Column(scale=n)</code>.
A <code class="code">@Column(scale=-1)</code> will set the fraction digits to zero.
</p>
</li><li class="listitem" id="DBDictionary.DatePrecision">
<p>
<a class="indexterm" name="d5e10150"></a>
<code class="literal">DatePrecision</code>:
The database is able to store time values to this degree of precision,
which is expressed in nanoseconds.
This value is usually one million, meaning that the database is able
to store time values with a precision of one millisecond. Particular
databases may have more or less precision.
OpenJPA will round all time values to this degree of precision
before storing them in the database. This property can be set to one
of the following precisions:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">DECI</code>: 100000000
</p>
</li><li class="listitem">
<p>
<code class="literal">CENIT</code>: 10000000
</p>
</li><li class="listitem">
<p>
<code class="literal">MILLI (default precision)</code>: 1000000
</p>
</li><li class="listitem">
<p>
<code class="literal">MICRO</code>: 1000
</p>
</li><li class="listitem">
<p>
<code class="literal">NANO (max precision)</code>: 1
</p>
</li></ul></div>
</li><li class="listitem" id="DBDictionary.DateMillisecondBehavior">
<p>
<a class="indexterm" name="d5e10172"></a>
<code class="literal">DateMillisecondBehavior</code>:
When retrieving a <code class="literal">Date</code> value from a database which stores the value in
a TIMESTAMP column, the values retrieved will be rounded to the nearest
millisecond. So a date of '2010-01-01 12:00:00.687701' stored in the
database will become '2010-01-01 12:00:00.688' in the <code class="literal">Date</code> field of the
entity. The following date stored in the database as '9999-12-31 23:59:59.9999'
will become '10000-01-01 00:00:00.000'. This rounding may not be desirable. With this
property, a user has options which will direct OpenJPA how to handle the milliseconds. This
property can be set to one of the enums defined in
<code class="literal">DBDictionary.DateMillisecondBehaviors</code>. The options defined in
<code class="literal">DBDictionary.DateMillisecondBehaviors</code> are as follows:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">DateMillisecondBehaviors.ROUND</code>: This is the default. The
<code class="literal">Date</code> will be rounded to the nearest millisecond, as described above.
</p>
</li><li class="listitem">
<p>
<code class="literal">DateMillisecondBehaviors.DROP</code>: The milliseconds will be dropped, thus
rounding is not performed. As an example, a date of '2010-01-01 12:00:00.687701' stored in the
database will become '2010-01-01 12:00:00.000' in the <code class="literal">Date</code> field of the
entity.
</p>
</li><li class="listitem">
<p>
<code class="literal">DateMillisecondBehaviors.RETAIN</code>: The milliseconds will not be rounded, but will
be retained. As an example, a date of '2010-01-01 12:00:00.687701' stored in the
database will become '2010-01-01 12:00:00.687' in the <code class="literal">Date</code> field of the
entity.
</p>
</li></ul></div><p>
</p>
</li><li class="listitem" id="DBDictionary.DateTypeName">
<p>
<a class="indexterm" name="d5e10195"></a>
<code class="literal">DateTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.DATE</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.DecimalTypeName">
<p>
<a class="indexterm" name="d5e10203"></a>
<code class="literal">DecimalTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.DECIMAL</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.DelimitedCase">
<p>
<a class="indexterm" name="d5e10211"></a>
<code class="literal">DelimitedCase</code>: The case to use when querying the database
about identifiers that have been delimited. It defaults to preserving the
case of the originally specified name. Available values are:
<code class="literal">upper, lower, preserve.</code>
</p>
</li><li class="listitem" id="DBDictionary.DisableAlterSeqenceIncrementBy">
<p>
<a class="indexterm" name="d5e10218"></a>
<code class="literal">DisableAlterSeqenceIncrementBy</code>: OpenJPA attempts to execute
an ALTER SEQUENCE....INCREMENT BY SQL statement for a user defined sequence. This
is done to ensure that the 'allocationSize' value defined by the entity's sequence,
or default value, matches the sequence defined in the database. For example, with
an allocationSize of 1000 for a sequence named 'SEQ_JPASAMPLE', the following SQL
will be generated (the SQL might vary slightly depending on the databases):
<code class="literal">ALTER SEQUENCE SEQ_JPASAMPLE INCREMENT BY 1000</code>. If the user
executing this command doesn't have permissions to execute the command, it will
fail and in turn OpenJPA will disable sequence caching. If a user wants to disable
this SQL command, this property can be set to true. However, the user must ensure
that the entities defined sequence is kept in synch with the sequence defined in the
database. Defaults to false.
</p>
</li><li class="listitem" id="DBDictionary.DisableSchemaFactoryColumnTypeErrors">
<p>
<a class="indexterm" name="d5e10225"></a>
<code class="literal">DisableSchemaFactoryColumnTypeErrors</code>: When something other than the default
SchemaFactory is used, up-front mapping validation is performed against the database schema. As
part of the validation, OpenJPA will verify a persistence class column's type against the column type
defined in the database schema. If a mismatch is found, OpenJPA will throw an exception to flag the
mismatch types and will not allow processing to continue. This can be limiting, especially if the
JDBC driver and/or database can properly handle the mismatch. Set this property to true to disable
column type mismatch errors. Defaults to false.
</p>
</li><li class="listitem" id="DBDictionary.DistinctCountColumnSeparator">
<p>
<a class="indexterm" name="d5e10231"></a>
<code class="literal">DistinctCountColumnSeparator</code>: The string the database uses
to delimit between column expressions in a <code class="literal">SELECT COUNT(DISTINCT
column-list)</code> clause. Defaults to <code class="literal">null</code>
for most databases, meaning that
multiple columns in a distinct COUNT clause are not supported.
</p>
</li><li class="listitem" id="DBDictionary.DistinctTypeName">
<p>
<a class="indexterm" name="d5e10239"></a>
<code class="literal">DistinctTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.DISTINCT</code>. This is used only when the schema
is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.DoubleTypeName">
<p>
<a class="indexterm" name="d5e10247"></a>
<code class="literal">DoubleTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.DOUBLE</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.DriverVendor">
<p>
<a class="indexterm" name="d5e10255"></a>
<code class="literal">DriverVendor</code>: The vendor of the particular JDBC driver you
are using. Some dictionaries must alter their behavior depending on the driver
vendor. Dictionaries usually detect the driver vendor and set this property
themselves. See the <code class="literal">VENDOR_XXX</code> constants defined in the
<code class="classname">DBDictionary</code> Javadoc for available options.
</p>
</li><li class="listitem" id="DBDictionary.DropTableSQL">
<p>
<a class="indexterm" name="d5e10263"></a>
<code class="literal">DropTableSQL</code>:
The SQL statement used to drop a table. Use the token <code class="literal">{0}</code>
as the argument for the table name.
Defaults to <code class="literal">"DROP TABLE {0}"</code>.
</p>
</li><li class="listitem" id="DBDictionary.FixedSizeTypeNames">
<p>
<a class="indexterm" name="d5e10271"></a>
<code class="literal">FixedSizeTypeNames</code>:
A comma separated list of additional database types that have a size
defined by the database. In other words, when a column of a fixed
size type is declared, its size cannot be defined by the user. Common
examples would be <code class="literal">DATE</code>, <code class="literal">FLOAT</code>,
and <code class="literal">INTEGER</code>.
Each database dictionary has its own internal set of fixed size type names
that include the names mentioned here and many others.
Names added to this property are added to the dictionary's internal set.
Defaults to <code class="literal">null</code>.
</p>
</li><li class="listitem" id="DBDictionary.FloatTypeName">
<p>
<a class="indexterm" name="d5e10281"></a>
<code class="literal">FloatTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.FLOAT</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.ForUpdateClause">
<p>
<a class="indexterm" name="d5e10289"></a>
<a class="indexterm" name="d5e10292"></a>
<code class="literal">ForUpdateClause</code>: The clause to append to <code class="literal">SELECT
</code> statements to issue queries that obtain pessimistic locks. Defaults
to <code class="literal">"FOR UPDATE"</code>.
</p>
</li><li class="listitem" id="DBDictionary.GetStringVal">
<p>
<a class="indexterm" name="d5e10300"></a>
<a class="indexterm" name="d5e10303"></a>
<code class="literal">GetStringVal</code>:
A special function to return the value of an XML
column in a select statement. For example, Oracle uses
<code class="literal">".getClobVal()"</code>, as in
<code class="literal">"SELECT t0.xmlcol.getClobVal() FROM xmltab t0"</code>.
Defaults to the empty string.
</p>
</li><li class="listitem" id="DBDictionary.InClauseLimit">
<p>
<a class="indexterm" name="d5e10311"></a>
<code class="literal">InClauseLimit</code>:
The maximum number of elements in an <code class="literal">IN</code> clause. OpenJPA
works around cases where the limit is exceeded. Defaults to -1 meaning
no limit.
</p>
</li><li class="listitem" id="DBDictionary.InitializationSQL">
<p>
<a class="indexterm" name="d5e10318"></a>
<a class="indexterm" name="d5e10321"></a>
<code class="literal">InitializationSQL</code>: A piece of SQL to issue against the
database whenever a connection is retrieved from the <code class="classname">DataSource
</code>.
</p>
</li><li class="listitem" id="DBDictionary.InnerJoinClause">
<p>
<a class="indexterm" name="d5e10328"></a>
<code class="literal">InnerJoinClause</code>: The clause to use for an inner join.
Defaults to <code class="literal">"INNER JOIN"</code>.
</p>
</li><li class="listitem" id="DBDictionary.IntegerTypeName">
<p>
<a class="indexterm" name="d5e10335"></a>
<code class="literal">IntegerTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.INTEGER</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.JavaObjectTypeName">
<p>
<a class="indexterm" name="d5e10343"></a>
<code class="literal">JavaObjectTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.JAVAOBJECT</code>. This is used only when the schema
is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.JoinSyntax">
<p>
<a class="indexterm" name="d5e10351"></a>
<code class="literal">JoinSyntax</code>: The SQL join syntax to use in select statements.
See <a class="xref" href="#ref_guide_dbsetup_sql92" title="6.&nbsp; Setting the SQL Join Syntax">Section&nbsp;6, &#8220;
Setting the SQL Join Syntax
&#8221;</a>.
</p>
</li><li class="listitem" id="DBDictionary.LastGeneratedKeyQuery">
<p>
<a class="indexterm" name="d5e10358"></a>
<code class="literal">LastGeneratedKeyQuery</code>: The query to issue to obtain the last
automatically generated key for an auto-increment column. For example,
<code class="literal">"SELECT LAST_INSERT_ID()"</code> for MySQL. This property is set
automatically in the dictionary, and should not need to be overridden.
If <code class="literal">SupportsGetGeneratedKeys</code> is true, the query will not
be issued but a more efficient JDBC 3.0 mechanism for obtaining generated
keys will be used instead.
</p>
</li><li class="listitem" id="DBDicationary.LeadingDelimiter">
<p>
<a class="indexterm" name="d5e10367"></a>
<code class="literal">LeadingDelimiter</code>: The characters to use as the leading delimiter
for a delimited identifier. The default value is a double quote,
<code class="literal">(")</code>. See
<a class="xref" href="#ref_guide_dbsetup_dbsupport_delim_id" title="4.7.&nbsp; Delimited Identifiers Support">Section&nbsp;4.7, &#8220;
Delimited Identifiers Support
&#8221;</a> for
the default value for some specific databases.
</p>
</li><li class="listitem" id="DBDictionary.LongVarbinaryTypeName">
<p>
<a class="indexterm" name="d5e10375"></a>
<code class="literal">LongVarbinaryTypeName</code>: The overridden default column type
for <code class="literal">java.sql.Types.LONGVARBINARY</code>. This is used only when the
schema is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.LongVarcharTypeName">
<p>
<a class="indexterm" name="d5e10383"></a>
<code class="literal">LongVarcharTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.LONGVARCHAR</code>. This is used only when the
schema is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.MaxAutoAssignNameLength">
<p>
<a class="indexterm" name="d5e10391"></a>
<code class="literal">MaxAutoAssignNameLength</code>: Set this property to the maximum
length of the sequence name used for auto-increment columns. Names longer than
this value are truncated. Defaults to 31.
</p>
</li><li class="listitem" id="DBDictionary.MaxColumnNameLength">
<p>
<a class="indexterm" name="d5e10397"></a>
<code class="literal">MaxColumnNameLength</code>: The maximum number of characters in a
column name. Defaults to 128.
</p>
</li><li class="listitem" id="DBDictionary.MaxConstraintNameLength">
<p>
<a class="indexterm" name="d5e10403"></a>
<code class="literal">MaxConstraintNameLength</code>: The maximum number of characters in
a constraint name. Defaults to 128.
</p>
</li><li class="listitem" id="DBDictionary.MaxEmbeddedBlobSize">
<p>
<a class="indexterm" name="d5e10409"></a>
<code class="literal">MaxEmbeddedBlobSize</code>:
When greater than -1, the maximum size of a <code class="literal">BLOB</code> value
that can be sent directly to the database within an insert or update statement.
Values whose size is greater than <code class="literal">MaxEmbeddedBlobSize</code> force
OpenJPA to work around this limitation. A value of -1 means that there is
no limitation. Defaults to -1.
</p>
</li><li class="listitem" id="DBDictionary.MaxEmbeddedClobSize">
<p>
<a class="indexterm" name="d5e10417"></a>
<code class="literal">MaxEmbeddedClobSize</code>:
When greater than -1, the maximum size of a <code class="literal">CLOB</code> value
that can be sent directly to the database within an insert or update statement.
Values whose size is greater than <code class="literal">MaxEmbeddedClobSize</code> force
OpenJPA to work around this limitation. A value of -1 means that there is
no limitation. Defaults to -1.
</p>
</li><li class="listitem" id="DBDictionary.MaxIndexNameLength">
<p>
<a class="indexterm" name="d5e10425"></a>
<a class="indexterm" name="d5e10428"></a>
<code class="literal">MaxIndexNameLength</code>: The maximum number of characters in an
index name. Defaults to 128.
</p>
</li><li class="listitem" id="DBDictionary.MaxIndexesPerTable">
<p>
<a class="indexterm" name="d5e10434"></a>
<code class="literal">MaxIndexesPerTable</code>: The maximum number of indexes that can
be placed on a single table. Defaults to no limit.
</p>
</li><li class="listitem" id="DBDictionary.MaxTableNameLength">
<p>
<a class="indexterm" name="d5e10440"></a>
<code class="literal">MaxTableNameLength</code>: The maximum number of characters in a
table name. Defaults to 128.
</p>
</li><li class="listitem" id="DBDictionary.NameConcatenator">
<p>
<a class="indexterm" name="d5e10446"></a>
<code class="literal">NameConcatenator</code>: The value used when names are concatenated to
create a generated name. The default value is the underscore <code class="literal">"_"</code>.
</p>
</li><li class="listitem" id="DBDictionary.NextSequenceQuery">
<p>
<a class="indexterm" name="d5e10453"></a>
<code class="literal">NextSequenceQuery</code>: A SQL string for obtaining a native
sequence value. May use a placeholder of <code class="literal">{0}</code> for the variable
sequence name and <code class="literal">{1}</code> for sequence increment.
Defaults to a database-appropriate value. For example,
<code class="literal">"SELECT {0}.NEXTVAL FROM DUAL"</code> for Oracle database.
</p>
</li><li class="listitem" id="DBDictionary.NullTypeName">
<p>
<a class="indexterm" name="d5e10462"></a>
<code class="literal">NullTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.NULL</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.NumericTypeName">
<p>
<a class="indexterm" name="d5e10470"></a>
<code class="literal">NumericTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.NUMERIC</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.OtherTypeName">
<p>
<a class="indexterm" name="d5e10478"></a>
<code class="literal">OtherTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.OTHER</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.OuterJoinClause">
<p>
<a class="indexterm" name="d5e10486"></a>
<code class="literal">OuterJoinClause</code>: The clause to use for an left outer join.
Defaults to <code class="literal">"LEFT OUTER JOIN"</code>.
</p>
</li><li class="listitem" id="DBDictionary.Platform">
<p>
<a class="indexterm" name="d5e10493"></a>
<code class="literal">Platform</code>:
The name of the database that this dictionary targets.
Defaults to <code class="literal">"Generic"</code>, but all dictionaries override this
value.
</p>
</li><li class="listitem" id="DBDictionary.RangePosition">
<p>
<a class="indexterm" name="d5e10500"></a>
<code class="literal">RangePosition</code>:
Indicates where to specify in the SQL select statement the range, if any,
of the result rows to be returned.
When limiting the number of returned result rows to a subset of all those
that satisfy the query's conditions, the position of the range clause
varies by database.
Defaults to 0, meaning that the range
is expressed at the end of the select statement but before any locking clause.
See the RANGE_XXX constants defined in <code class="classname">DBDictionary</code>.
</p>
</li><li class="listitem" id="DBDictionary.RealTypeName">
<p>
<a class="indexterm" name="d5e10507"></a>
<code class="literal">RealTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.REAL</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.RefTypeName">
<p>
<a class="indexterm" name="d5e10515"></a>
<code class="literal">RefTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.REF</code>. This is used only when the schema is generated by
the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.RequiresAliasForSubselect">
<p>
<a class="indexterm" name="d5e10523"></a>
<a class="indexterm" name="d5e10526"></a>
<code class="literal">RequiresAliasForSubselect</code>: When true, the database
requires that subselects in a FROM clause be assigned an alias.
</p>
</li><li class="listitem" id="DBDictionary.RequiresAutoCommitForMetadata">
<p>
<a class="indexterm" name="d5e10533"></a>
<code class="literal">RequiresAutoCommitForMetadata</code>: When true, the JDBC driver
requires that autocommit be enabled before any schema interrogation operations
can take place.
</p>
</li><li class="listitem" id="DBDictionary.RequiresCastForComparisons">
<p>
<a class="indexterm" name="d5e10540"></a>
<code class="literal">RequiresCastForComparisons</code>:
When true, comparisons of two values of different types or
of two literals requires a cast in the generated SQL.
Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.RequiresCastForMathFunctions">
<p>
<a class="indexterm" name="d5e10547"></a>
<code class="literal">RequiresCastForMathFunctions</code>:
When true, math operations on two values of different types or
on two literals requires a cast in the generated SQL.
Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.RequiresConditionForCrossJoin">
<p>
<a class="indexterm" name="d5e10554"></a>
<code class="literal">RequiresConditionForCrossJoin</code>: Some databases require that
there always be a conditional statement for a cross join. If set, this parameter
ensures that there will always be some condition to the join clause.
</p>
</li><li class="listitem" id="DBDictionary.RequiresTargetForDelete">
<p>
<a class="indexterm" name="d5e10560"></a>
<code class="literal">RequiresTargetForDelete</code>:
When true, the database requires a target for delete statements. Defaults
to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.ReservedWords">
<p>
<a class="indexterm" name="d5e10567"></a>
<code class="literal">ReservedWords</code>: A comma-separated list of reserved words for
this database, beyond the standard SQL92 keywords.
</p>
</li><li class="listitem" id="DBDictionary.SchemaCase">
<p>
<a class="indexterm" name="d5e10573"></a>
<code class="literal">SchemaCase</code>: The case to use when querying the database
metadata about schema components. Defaults to making all names upper case.
Available values are: <code class="literal">upper, lower, preserve</code>.
</p>
</li><li class="listitem" id="DBDictionary.SearchStringEscape">
<p>
<a class="indexterm" name="d5e10581"></a>
<code class="literal">SearchStringEscape</code>:
The default escape character used when generating SQL <code class="literal">LIKE</code>
clauses. The escape character is used to escape the wildcard meaning of the
<code class="literal">_</code> and <code class="literal">%</code> characters.
Note: since JPQL provides the ability to define the escape character in
the query, this setting is primarily used when translating other query
languages, such as JDOQL. Defaults to <code class="literal">"\\"</code>
(a single backslash in Java speak).
</p>
</li><li class="listitem" id="DBDictionary.RequiresSearchStringEscapeForLike">
<p>
<a class="indexterm" name="d5e10591"></a>
<code class="literal">RequiresSearchStringEscapeForLike</code>:
When true, the database requires an escape string for queries that use
<code class="literal">LIKE</code>. The escape string can be specified using
<code class="literal">searchStringEscape</code>. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SelectWords">
<p>
<a class="indexterm" name="d5e10600"></a>
<code class="literal">SelectWords</code>: A comma-separated list of keywords which may be
used to start a SELECT statement for this database. If an application executes
a native SQL statement which begins with SelectWords OpenJPA will treat the
statement as a SELECT statement rather than an UPDATE statement.
</p>
</li><li class="listitem" id="DBDictionary.SequenceNameSQL">
<p>
<a class="indexterm" name="d5e10606"></a>
<code class="literal">SequenceNameSQL</code>:
Additional phrasing to use with <code class="literal">SequenceSQL</code>.
Defaults to <code class="literal">null</code>.
</p>
</li><li class="listitem" id="DBDictionary.SequenceSQL">
<p>
<a class="indexterm" name="d5e10615"></a>
<code class="literal">SequenceSQL</code>:
General structure of the SQL query to use when interrogating the database
for sequence names.
As there is no standard way to obtain sequence names,
it defaults to <code class="literal">null</code>.
</p>
</li><li class="listitem" id="DBDictionary.SequenceSchemaSQL">
<p>
<a class="indexterm" name="d5e10623"></a>
<code class="literal">SequenceSchemaSQL</code>:
Additional phrasing to use with <code class="literal">SequenceSQL</code>.
Defaults to <code class="literal">null</code>.
</p>
</li><li class="listitem" id="DBDictionary.SimulateLocking">
<p>
<a class="indexterm" name="d5e10632"></a>
<code class="literal">SimulateLocking</code>: Some databases do not support pessimistic
locking, which will result in an exception when you attempt a
transaction while using the pessimistic lock manager.
Setting this property to <code class="literal">true</code> suppresses the
locking of rows in the database, thereby allowing pessimistic transactions
even on databases that do not support locking. At the same time, setting this
property to <code class="literal">true</code> means that you do not obtain the semantics
of a pessimistic
transaction with the database. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SmallintTypeName">
<p>
<a class="indexterm" name="d5e10641"></a>
<code class="literal">SmallintTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.SMALLINT</code>. This is used only when the schema
is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.StorageLimitationsFatal">
<p>
<a class="indexterm" name="d5e10649"></a>
<code class="literal">StorageLimitationsFatal</code>: When true, any data
truncation/rounding that is performed by the dictionary in order to store a
value in the database will be treated as a fatal error, rather than just issuing
a warning.
</p>
</li><li class="listitem" id="DBDictionary.StoreCharsAsNumbers">
<p>
<a class="indexterm" name="d5e10655"></a>
<code class="literal">StoreCharsAsNumbers</code>: Set this property to <code class="literal">false
</code> to store Java <code class="literal">char</code> fields as <code class="literal">CHAR
</code> values rather than numbers. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.StoreLargeNumbersAsStrings">
<p>
<a class="indexterm" name="d5e10665"></a>
<code class="literal">StoreLargeNumbersAsStrings</code>: When true, the dictionary
prefers to store Java fields of
type <code class="classname">BigInteger</code> and <code class="classname">BigDecimal</code>
as string values in the database. Likewise, the dictionary will instruct
the mapping tool to map these Java types to character columns.
Because some databases have limitations on the number of digits that can
be stored in a numeric column (for example, Oracle can only store 38
digits), this option may be necessary for some applications.
Note that this option may prevent OpenJPA from executing meaningful numeric
queries against the columns. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.StringLengthFunction">
<p>
<a class="indexterm" name="d5e10674"></a>
<code class="literal">StringLengthFunction</code>: Name of the SQL function for getting
the length of a string. Use the token <code class="literal">{0}</code> to represent the
argument.
</p>
</li><li class="listitem" id="DBDictionary.StructTypeName">
<p>
<a class="indexterm" name="d5e10681"></a>
<code class="literal">StructTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.STRUCT</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.SubstringFunctionName">
<p>
<a class="indexterm" name="d5e10689"></a>
<code class="literal">SubstringFunctionName</code>: Name of the SQL function for getting
the substring of a string.
</p>
</li><li class="listitem" id="DBDictionary.SupportsAlterTableWithAddColumn">
<p>
<a class="indexterm" name="d5e10695"></a>
<code class="literal">SupportsAlterTableWithAddColumn</code>: When true, the database
supports adding a new column in an ALTER TABLE statement.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsAlterTableWithDropColumn">
<p>
<a class="indexterm" name="d5e10702"></a>
<code class="literal">SupportsAlterTableWithDropColumn</code>: When true, the database
supports dropping a column in an ALTER TABLE statement.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsAutoAssign">
<p>
<a class="indexterm" name="d5e10709"></a>
<code class="literal">SupportsAutoAssign</code>:
When true, the database supports auto-assign columns, where the value of
column is assigned upon insertion of the row into the database.
Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsCascadeDeleteAction">
<p>
<a class="indexterm" name="d5e10716"></a>
<code class="literal">SupportsCascadeDeleteAction</code>: When true, the database supports
the <code class="literal">CASCADE</code> delete action on foreign keys.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsCascadeUpdateAction">
<p>
<a class="indexterm" name="d5e10724"></a>
<code class="literal">SupportsCascadeUpdateAction</code>:
When true, the database supports the <code class="literal">CASCADE</code>
update action on foreign keys. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsComments">
<p>
<a class="indexterm" name="d5e10732"></a>
<code class="literal">SupportsComments</code>:
When true, comments can be associated with the table in the table creation
statement. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsCorrelatedSubselect">
<p>
<a class="indexterm" name="d5e10739"></a>
<code class="literal">SupportsCorrelatedSubselect</code>:
When true, the database supports correlated subselects. Correlated
subselects are select statements nested within select statements that
refers to a column in the outer select statement. For performance
reasons, correlated subselects are generally a last resort.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsDefaultDeleteAction">
<p>
<a class="indexterm" name="d5e10746"></a>
<code class="literal">SupportsDefaultDeleteAction</code>: When true, the database supports
the <code class="literal">SET DEFAULT</code> delete action on foreign keys.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsDefaultUpdateAction">
<p>
<a class="indexterm" name="d5e10754"></a>
<code class="literal">SupportsDefaultUpdateAction</code>:
When true, the database supports the <code class="literal">SET DEFAULT</code> update
action on foreign keys. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsDeferredConstraints">
<p>
<a class="indexterm" name="d5e10762"></a>
<code class="literal">SupportsDeferredConstraints</code>: When true, the database
supports deferred constraints. The
database supports deferred constraints by checking for constraint
violations when the transaction commits, rather than checking for
violations immediately after receiving each SQL statement within the
transaction. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsDelimitedIdentifiers">
<p>
<a class="indexterm" name="d5e10769"></a>
<code class="literal">SupportsDelimitedIdentifiers</code>: When true, the database
supports delimited identifiers. It defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsForeignKeys">
<p>
<a class="indexterm" name="d5e10776"></a>
<code class="literal">SupportsForeignKeys</code>: When true, the database supports foreign
keys. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsForeignKeysComposite">
<p>
<a class="indexterm" name="d5e10783"></a>
<code class="literal">SupportsForeignKeysComposite</code>: When true, the database supports
composite foreign keys. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsGetGeneratedKeys">
<p>
<a class="indexterm" name="d5e10790"></a>
<code class="literal">SupportsGetGeneratedKeys</code>: When true, OpenJPA will use
<code class="methodname">java.sql.Statement.getGeneratedKeys</code> method to obtain
values of auto-increment columns. When false, a query specified by
<code class="literal">LastGeneratedKeyQuery</code> will be used for that purpose.
If not set, the value will be auto-detected by querying the JDBC driver.
Setting the value to true requires that the JDBC
driver supports version 3.0 or higher of the JDBC specification
and supports the <code class="methodname">java.sql.Statement.getGeneratedKeys</code>
method.
</p>
</li><li class="listitem" id="DBDictionary.SupportsHaving">
<p>
<a class="indexterm" name="d5e10800"></a>
<code class="literal">SupportsHaving</code>: When true, the database supports HAVING
clauses in selects.
</p>
</li><li class="listitem" id="DBDictionary.SupportsLockingWithDistinctClause">
<p>
<a class="indexterm" name="d5e10807"></a>
<code class="literal">SupportsLockingWithDistinctClause</code>: When true, the
database supports <code class="literal">FOR UPDATE</code> select clauses with
<code class="literal">DISTINCT</code> clauses.
</p>
</li><li class="listitem" id="DBDictionary.SupportsLockingWithInnerJoin">
<p>
<a class="indexterm" name="d5e10815"></a>
<code class="literal">SupportsLockingWithInnerJoin</code>: When true, the database
supports <code class="literal">FOR UPDATE</code> select clauses with inner join queries.
</p>
</li><li class="listitem" id="DBDictionary.SupportsLockingWithMultipleTables">
<p>
<a class="indexterm" name="d5e10822"></a>
<code class="literal">SupportsLockingWithMultipleTables</code>: When true, the
database supports <code class="literal">FOR UPDATE</code> select clauses that select from
multiple tables.
</p>
</li><li class="listitem" id="DBDictionary.SupportsLockingWithOrderClause">
<p>
<a class="indexterm" name="d5e10829"></a>
<code class="literal">SupportsLockingWithOrderClause</code>: When true, the database
supports <code class="literal">FOR UPDATE</code> select clauses with <code class="literal">ORDER BY
</code> clauses.
</p>
</li><li class="listitem" id="DBDictionary.SupportsLockingWithOuterJoin">
<p>
<a class="indexterm" name="d5e10837"></a>
<code class="literal">SupportsLockingWithOuterJoin</code>: When true, the database
supports <code class="literal">FOR UPDATE</code> select clauses with outer join queries.
</p>
</li><li class="listitem" id="DBDictionary.SupportsLockingWithSelectRange">
<p>
<a class="indexterm" name="d5e10844"></a>
<code class="literal">SupportsLockingWithSelectRange</code>: When true, the database
supports <code class="literal">FOR UPDATE</code> select clauses with queries that select a
range of data using <code class="literal">LIMIT</code>, <code class="literal">TOP</code> or the
database equivalent. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsModOperator">
<p>
<a class="indexterm" name="d5e10854"></a>
<code class="literal">SupportsModOperator</code>:
When true, the database supports the modulus operator (<code class="literal">%</code>)
instead of the <code class="literal">MOD</code> function.
Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsMultipleNontransactionalResultSets">
<p>
<code class="literal">SupportsMultipleNontransactionalResultSets</code>: When true, a
nontransactional connection is capable of having multiple open
<code class="classname">ResultSet</code> instances.
</p>
</li><li class="listitem" id="DBDictionary.SupportsNullDeleteAction">
<p>
<a class="indexterm" name="d5e10867"></a>
<code class="literal">SupportsNullDeleteAction</code>: When true, the database supports
the <code class="literal">SET NULL</code> delete action on foreign keys.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsNullTableForGetColumns">
<p>
<a class="indexterm" name="d5e10875"></a>
<code class="literal">SupportsNullTableForGetColumns</code>: When true, the database
supports passing a <code class="literal">null</code> parameter to <code class="methodname">
DatabaseMetaData.getColumns</code> as an optimization to get information
about all the tables. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsNullTableForGetImportedKeys">
<p>
<a class="indexterm" name="d5e10885"></a>
<code class="literal">SupportsNullTableForGetImportedKeys</code>: When true, the
database supports passing a <code class="literal">null</code> parameter to <code class="methodname">
DatabaseMetaData.getImportedKeys</code> as an optimization to get
information about all the tables. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsNullTableForGetIndexInfo">
<p>
<a class="indexterm" name="d5e10895"></a>
<code class="literal">SupportsNullTableForGetIndexInfo</code>: When true, the database
supports passing a <code class="literal">null</code> parameter to <code class="methodname">
DatabaseMetaData.getIndexInfo</code> as an optimization to get information
about all the tables. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsNullTableForGetPrimaryKeys">
<p>
<a class="indexterm" name="d5e10905"></a>
<code class="literal">SupportsNullTableForGetPrimaryKeys</code>: When true, the
database supports passing a <code class="literal">null</code> parameter to <code class="methodname">
DatabaseMetaData.getPrimaryKeys</code> as an optimization to get
information about all the tables. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsNullUpdateAction">
<p>
<a class="indexterm" name="d5e10915"></a>
<code class="literal">SupportsNullUpdateAction</code>:
When true, the database supports the <code class="literal">SET NULL</code> update
action on foreign keys. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsQueryTimeout">
<p>
<a class="indexterm" name="d5e10923"></a>
<code class="literal">SupportsQueryTimeout</code>: When true, the JDBC driver supports
calls to <code class="methodname"> java.sql.Statement.setQueryTimeout</code>.
</p>
</li><li class="listitem" id="DBDictionary.AllowQueryTimeoutOnFindUpdate">
<p>
<a class="indexterm" name="d5e10931"></a>
<code class="literal">AllowQueryTimeoutOnFindUpdate</code>: The JPA Specification defines the
javax.persistence.query.timeout, in milliseconds, as a hint to the provider. The hint
is used for Query operations. This property, when set to true, will allow the query timeout hint
to apply to EntityManager operations. For example, when a 'find' is executed and the resultant
entity updated, the query timeout will apply to the SQL update operation. This property defaults
to false.
</p>
</li><li class="listitem" id="DBDictionary.SupportsRestrictDeleteAction">
<p>
<a class="indexterm" name="d5e10938"></a>
<code class="literal">SupportsRestrictDeleteAction</code>: When true, the database
supports the <code class="literal">RESTRICT</code> delete action on foreign keys.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsRestrictUpdateAction">
<p>
<a class="indexterm" name="d5e10946"></a>
<code class="literal">SupportsRestrictUpdateAction</code>:
When true, the database supports the <code class="literal">RESTRICT</code> update
action on foreign keys. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsSchemaForGetColumns">
<p>
<a class="indexterm" name="d5e10954"></a>
<code class="literal">SupportsSchemaForGetColumns</code>: When false, the database
driver does not support using the schema name for schema reflection on column
names.
</p>
</li><li class="listitem" id="DBDictionary.SupportsSchemaForGetTables">
<p>
<a class="indexterm" name="d5e10961"></a>
<code class="literal">SupportsSchemaForGetTables</code>: If false, then the database
driver does not support using the schema name for schema reflection on table
names.
</p>
</li><li class="listitem" id="DBDictionary.SupportsSelectEndIndex">
<p>
<a class="indexterm" name="d5e10968"></a>
<code class="literal">SupportsSelectEndIndex</code>: When true, the database can create a
select that is limited to the first N results.
</p>
</li><li class="listitem" id="DBDictionary.SupportsSelectForUpdate">
<p>
<a class="indexterm" name="d5e10975"></a>
<code class="literal">SupportsSelectForUpdate</code>: When true, the database supports
<code class="literal">SELECT</code> statements with a pessimistic locking
(<code class="literal">FOR UPDATE</code>) clause. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsSelectStartIndex">
<p>
<a class="indexterm" name="d5e10984"></a>
<code class="literal">SupportsSelectStartIndex</code>: When true, the database can create a
select that skips the first N results.
</p>
</li><li class="listitem" id="DBDictionary.SupportsSimpleCaseExpression">
<p>
<a class="indexterm" name="d5e10991"></a>
<code class="literal">SupportsSimpleCaseExpression</code>: When true, the database supports
the simple form of <code class="literal">CASE</code> expression:
<code class="literal">CASE &lt;a&gt; WHEN &lt;b&gt; THEN &lt;c&gt; WHEN &lt;d&gt; THEN &lt;e&gt; ELSE &lt;f&gt; END</code>.
When false, the general form of <code class="literal">CASE</code> expression will be used:
<code class="literal">CASE WHEN &lt;a&gt; = &lt;b&gt; THEN &lt;c&gt; WHEN &lt;a&gt; = &lt;d&gt; THEN &lt;e&gt; ELSE &lt;f&gt; END</code>.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsSubselect">
<p>
<a class="indexterm" name="d5e11002"></a>
<a class="indexterm" name="d5e11005"></a>
<code class="literal">SupportsSubselect</code>: When true, the database supports subselects
in queries.
</p>
</li><li class="listitem" id="DBDictionary.SupportsTimestampNanos">
<p>
<a class="indexterm" name="d5e11012"></a>
<code class="literal">SupportsTimestampNanos</code>: When true, the database supports
nanoseconds with TIMESTAMP columns.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsUniqueConstraints">
<p>
<a class="indexterm" name="d5e11018"></a>
<code class="literal">SupportsUniqueConstraints</code>: When true, the database supports
unique constraints. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="DBDictionary.SupportsXMLColumn">
<p>
<a class="indexterm" name="d5e11025"></a>
<code class="literal">SupportsXMLColumn</code>:
When true, the database supports an XML column type. See
<a class="xref" href="#ref_guide_xmlmapping" title="7.10.&nbsp; XML Column Mapping">Section&nbsp;7.10, &#8220;
XML Column Mapping
&#8221;</a>
for information on using this capability. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.SystemSchemas">
<p>
<a class="indexterm" name="d5e11033"></a>
<code class="literal">SystemSchemas</code>: A comma-separated list of schema names that
should be ignored.
</p>
</li><li class="listitem" id="DBDictionary.SystemTables">
<p>
<a class="indexterm" name="d5e11040"></a>
<code class="literal">SystemTables</code>: A comma-separated list of table names that
should be ignored.
</p>
</li><li class="listitem" id="DBDictionary.TableForUpdateClause">
<p>
<a class="indexterm" name="d5e11047"></a>
<a class="indexterm" name="d5e11050"></a>
<code class="literal">TableForUpdateClause</code>: The clause to append to the end of
each table alias in queries that obtain pessimistic locks.
Defaults to <code class="literal">null</code>.
</p>
</li><li class="listitem" id="DBDictionary.tableLengthIncludesSchema">
<p>
<a class="indexterm" name="d5e11057"></a>
<code class="literal">tableLengthIncludesSchema</code>: Whether the max length for a table name includes the table's schema.
Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.TableTypes">
<p>
<a class="indexterm" name="d5e11064"></a>
<code class="literal">TableTypes</code>: Comma-separated list of table types to use when
looking for tables during schema reflection, as defined in the <code class="methodname">
java.sql.DatabaseMetaData.getTableInfo</code> JDBC method. An example is:
<code class="literal">"TABLE,VIEW,ALIAS"</code>. Defaults to <code class="literal">"TABLE"</code>.
</p>
</li><li class="listitem" id="DBDictionary.TimeTypeName">
<p>
<a class="indexterm" name="d5e11074"></a>
<code class="literal">TimeTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.TIME</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.TimestampTypeName">
<p>
<a class="indexterm" name="d5e11082"></a>
<code class="literal">TimestampTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.TIMESTAMP</code>. This is used only when the schema
is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.TinyintTypeName">
<p>
<a class="indexterm" name="d5e11090"></a>
<code class="literal">TinyintTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.TINYINT</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.ToLowerCaseFunction">
<p>
<a class="indexterm" name="d5e11098"></a>
<code class="literal">ToLowerCaseFunction</code>: Name of the SQL function for converting
a string to lower case. Use the token <code class="literal">{0}</code> to represent the
argument.
</p>
</li><li class="listitem" id="DBDictionary.ToUpperCaseFunction">
<p>
<a class="indexterm" name="d5e11105"></a>
<code class="literal">ToUpperCaseFunction</code>: SQL function call for converting a
string to upper case. Use the token <code class="literal">{0}</code> to represent the
argument.
</p>
</li><li class="listitem" id="DBDicationary.TrailingDelimiter">
<p>
<a class="indexterm" name="d5e11112"></a>
<code class="literal">TrailingDelimiter</code>: The characters to use as the trailing delimiter
for a delimited identifier. The default value is a double quote,
<code class="literal">(")</code>. See
<a class="xref" href="#ref_guide_dbsetup_dbsupport_delim_id" title="4.7.&nbsp; Delimited Identifiers Support">Section&nbsp;4.7, &#8220;
Delimited Identifiers Support
&#8221;</a> for
the default value for some specific databases.
</p>
</li><li class="listitem" id="DBDictionary.TrimBothFunction">
<p>
<a class="indexterm" name="d5e11120"></a>
<code class="literal">TrimBothFunction</code>:
The SQL function call to trim any number of a particular character
from both the start and end of a string.
Note: some databases do not support specifying the character in which
case only spaces or whitespace can be trimmed.
Use the token <code class="literal">{1}</code> when possible to represent the character,
and the token <code class="literal">{0}</code> to represent the string.
Defaults to <code class="literal">"TRIM(BOTH {1} FROM {0})"</code>.
</p>
</li><li class="listitem" id="DBDictionary.TrimLeadingFunction">
<p>
<a class="indexterm" name="d5e11129"></a>
<code class="literal">TrimLeadingFunction</code>:
The SQL function call to trim any number of a particular character
from the start of a string.
Note: some databases do not support specifying the character in which
case only spaces or whitespace can be trimmed.
Use the token <code class="literal">{1}</code> when possible to represent the character,
and the token <code class="literal">{0}</code> to represent the string.
Defaults to <code class="literal">"TRIM(LEADING {1} FROM {0})"</code>.
</p>
</li><li class="listitem" id="DBDictionary.TrimStringColumns">
<p>
<a class="indexterm" name="d5e11138"></a>
<code class="literal">TrimStringColumns</code>: When <code class="literal">true</code>, the resulting String from
<code class="methodname">ResultSet.getString</code> will be trimmed of trailing white space. Defaults
to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.TrimTrailingFunction">
<p>
<a class="indexterm" name="d5e11147"></a>
<code class="literal">TrimTrailingFunction</code>:
The SQL function call to trim any number of a particular character
from the end of a string.
Note: some databases do not support specifying the character in which
case only spaces or whitespace can be trimmed.
Use the token <code class="literal">{1}</code> when possible to represent the character,
and the token <code class="literal">{0}</code> to represent the string.
Defaults to <code class="literal">"TRIM(TRAILING {1} FROM {0})"</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseGetBestRowIdentifierForPrimaryKeys">
<p>
<a class="indexterm" name="d5e11156"></a>
<code class="literal">UseGetBestRowIdentifierForPrimaryKeys</code>: When true,
metadata queries will use <code class="methodname">DatabaseMetaData.getBestRowIdentifier
</code> to obtain information about primary keys, rather than <code class="methodname">
DatabaseMetaData.getPrimaryKeys</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseGetBytesForBlobs">
<p>
<a class="indexterm" name="d5e11165"></a>
<code class="literal">UseGetBytesForBlobs</code>: When true, <code class="methodname">
ResultSet.getBytes</code> will be used to obtain blob data rather than
<code class="methodname">ResultSet.getBinaryStream</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseGetObjectForBlobs">
<p>
<a class="indexterm" name="d5e11173"></a>
<code class="literal">UseGetObjectForBlobs</code>: When true, <code class="methodname">
ResultSet.getObject</code> will be used to obtain blob data rather than
<code class="methodname">ResultSet.getBinaryStream</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseGetStringForClobs">
<p>
<a class="indexterm" name="d5e11181"></a>
<code class="literal">UseGetStringForClobs</code>: When true, <code class="methodname">
ResultSet.getString</code> will be used to obtain clob data rather than
<code class="methodname">ResultSet.getCharacterStream</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseJDBC4SetBinaryStream">
<p>
<a class="indexterm" name="d5e11189"></a>
<code class="literal">UseJDBC4SetBinaryStream</code>: When true, an attempt will be made to obtain
a JDBC 4.0 version of <code class="methodname">PreparedStatement.setBinaryStream</code>.
When false, a <code class="methodname">setBinaryStream</code> is used which takes the length of the
stream. OpenJPA uses a -1 for the length since OpenJPA doesn't know the length of the stream.
A few JDBC drivers check the length and throw an exception when the length is less than zero.
When this property is set to true, and an applicable JDK and JDBC 4.0 driver is available, a
version of <code class="methodname">setBinaryStream</code> will be used which does not take a length.
The default value of this property is true.
</p>
</li><li class="listitem" id="DBDictionary.UseNativeSequenceCache">
<p>
<a class="indexterm" name="d5e11198"></a>
<code class="literal">UseNativeSequenceCache</code>: This property was introduced in
the 2.1.2 release to indicate (when set to <code class="literal">false</code>) that OpenJPA
should not use the <code class="literal">CACHE</code> clause when creating a native sequence; instead
the <code class="literal">INCREMENT BY</code> clause gets its value equal to the allocationSize
property. In the 2.2.0 release, code was added to allow said functionality by
default (see OPENJPA-1376).
For forward compatibility, this property still remains, however it has
been deprecated and will eventually be removed. Setting this property
has no effect and any occurrence of it should be removed.
</p>
</li><li class="listitem" id="DBDictionary.UseSchemaName">
<p>
<a class="indexterm" name="d5e11207"></a>
<code class="literal">UseSchemaName</code>: If <code class="literal">false</code>, then avoid
including the schema name in table name references. Defaults to <code class="literal">true
</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseSetBytesForBlobs">
<p>
<a class="indexterm" name="d5e11215"></a>
<code class="literal">UseSetBytesForBlobs</code>: When true, <code class="methodname">
PreparedStatement.setBytes</code> will be used to set blob data, rather
than <code class="methodname">PreparedStatement.setBinaryStream</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseSetStringForClobs">
<p>
<a class="indexterm" name="d5e11223"></a>
<code class="literal">UseSetStringForClobs</code>: When true, <code class="methodname">
PreparedStatement.setString</code> will be used to set clob data, rather
than <code class="methodname">PreparedStatement.setCharacterStream</code>.
</p>
</li><li class="listitem" id="DBDictionary.UseWildCardForCount">
<p>
<a class="indexterm" name="d5e11231"></a>
<code class="literal">UseWildCardForCount</code>: When true, the JPQL <code class="literal">COUNT</code>
aggregate function will be translated into SQL <code class="literal">COUNT(*)</code> expression
if the SQL query does not involve joins. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem" id="DBDictionary.ValidationSQL">
<p>
<a class="indexterm" name="d5e11240"></a>
<a class="indexterm" name="d5e11243"></a>
<code class="literal">ValidationSQL</code>: The SQL used to validate that a connection is
still in a valid state. For example, <code class="literal">"SELECT SYSDATE FROM DUAL"
</code> for Oracle.
</p>
</li><li class="listitem" id="DBDictionary.VarbinaryTypeName">
<p>
<a class="indexterm" name="d5e11250"></a>
<code class="literal">VarbinaryTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.VARBINARY</code>. This is used only when the schema
is generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.VarcharTypeName">
<p>
<a class="indexterm" name="d5e11258"></a>
<code class="literal">VarcharTypeName</code>: The overridden default column type for
<code class="literal">java.sql.Types.VARCHAR</code>. This is used only when the schema is
generated by the <code class="literal">mappingtool</code>.
</p>
</li><li class="listitem" id="DBDictionary.XmlTypeName">
<p>
<a class="indexterm" name="d5e11266"></a>
<code class="literal">XmlTypeName</code>:
The column type name for XML columns. This
property is set automatically in the dictionary and should not need to be
overridden. It is used only when the schema is generated using the
<code class="literal">mappingtool</code>. Defaults to <code class="literal">"XML"</code>.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_dbsetup_dbsupport_firebird"><div class="titlepage"><div><div><h3 class="title">4.2.&nbsp;
FirebirdDictionary Properties
</h3></div></div></div>
<a class="indexterm" name="d5e11274"></a>
<p>
The <code class="literal">firebird</code> dictionary understands the following additional
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem" id="FirebirdDictionary.FirebirdVersion">
<p>
<a class="indexterm" name="d5e11282"></a>
<code class="literal">FirebirdVersion</code>: The database version OpenJPA connects to.
This property affects the SQL statements executed by OpenJPA.
Available values are: 15, 20 and 21
- they indicate Firebird versions 1.5, 2.0 and 2.1 respectively.
If not set, the value will be auto-detected.
</p>
</li><li class="listitem" id="FirebirdDictionary.IndexedVarcharMaxSizeFB15">
<p>
<a class="indexterm" name="d5e11288"></a>
<code class="literal">IndexedVarcharMaxSizeFB15</code>: Firebird 1.5 imposes
tight limits on index size. In particular, an indexed
<code class="literal">VARCHAR</code> column size cannot exceed 252.
When <a class="link" href="#ref_guide_mapping_mappingtool" title="1.&nbsp; Forward Mapping">schema is created</a>,
OpenJPA will use this property to reduce the size
of indexed <code class="literal">VARCHAR</code> columns.
Defaults to 252 but you might want to decrease this value if multi-column
indexes are used. If the Firebird version is 2.0 or later or
schema creation is not used, this property does not matter.
</p>
</li><li class="listitem" id="FirebirdDictionary.RangeSyntax">
<p>
<a class="indexterm" name="d5e11297"></a>
<code class="literal">RangeSyntax</code>: Firebird 2.0 and later support two
ways of handling queries that select a range of data:
<code class="literal">"FIRST &lt;p&gt; SKIP &lt;q&gt;"</code> and
<code class="literal">"ROWS &lt;m&gt; TO &lt;n&gt;"</code>. Earlier versions support only
<code class="literal">"FIRST &lt;p&gt; SKIP &lt;q&gt;"</code> syntax.
This property determines the syntax to be used.
Available values are:
<code class="literal">"firstskip"</code> and <code class="literal">"rows"</code>.
Defaults to using <code class="literal">"ROWS &lt;m&gt; TO &lt;n&gt;"</code> if the
Firebird version is 2.0 or later, and
<code class="literal">"FIRST &lt;p&gt; SKIP &lt;q&gt;"</code> otherwise.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_dbsetup_dbsupport_mysql"><div class="titlepage"><div><div><h3 class="title">4.3.&nbsp;
MySQLDictionary Properties
</h3></div></div></div>
<a class="indexterm" name="d5e11310"></a>
<p>
The <code class="literal">mysql</code> dictionary also understands the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem" id="MySQLDictionary.DateFractionDigits">
<p>
<a class="indexterm" name="d5e11318"></a>
<code class="literal">DateFractionDigits</code>:
Since MySQL 5.8 a timestamp (<code class="code">DATETIME</code>) can store up to 6 sub-second fractions.
The default in MySQL and OpenJPA is 0 for backward compatibility reasons.
This default can be changed by setting <code class="literal">DateFractionDigits</code> to the number of
sub-second fraction digits to be stored. This will e.g. result in a <code class="code">DATETIME(6)</code> column.
The number of fraction digits to be generated can also be tweaked via the
<code class="code">@Column(scale=n)</code> annotation, where n is the number of digits.
This setting has primarily an impact on the generated SQL.
</p>
</li><li class="listitem" id="MySQLDictionary.DriverDeserializesBlobs">
<p>
<a class="indexterm" name="d5e11328"></a>
<code class="literal">DriverDeserializesBlobs</code>: Many older MySQL drivers
automatically deserialize BLOBs on calls to
<code class="methodname">ResultSet.getObject</code>. The
<code class="classname">MySQLDictionary</code> overrides the standard <code class="methodname">
DBDictionary.getBlobObject</code> method to take this into account.
Defaults to <code class="literal">true</code> if driver version is less than 5.0,
<code class="literal">false</code> otherwise. If your driver deserializes
automatically, you may want to set this property to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="MySQLDictionary.TableType">
<p>
<a class="indexterm" name="d5e11340"></a>
<code class="literal">TableType</code>: The MySQL table type to use when creating tables.
Defaults to <code class="literal">"innodb"</code>.
</p>
</li><li class="listitem" id="MySQLDictionary.UseClobs">
<p>
<a class="indexterm" name="d5e11347"></a>
<code class="literal">UseClobs</code>: Some older versions of MySQL do not handle CLOBs
correctly. To disable CLOB functionality, set this to <code class="literal">false</code>.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem" id="MySQLDictionary.OptimizeMultiTableDeletes">
<p>
<a class="indexterm" name="d5e11355"></a>
<code class="literal">OptimizeMultiTableDeletes</code>: MySQL as of version 4.0.0
supports multiple tables in <code class="literal">DELETE</code> statements. When
this option is set, OpenJPA will use that syntax when doing bulk deletes
from multiple tables. This can happen when the
<code class="literal">deleteTableContents</code> <code class="literal">SchemaTool</code>
action is used. (See <a class="xref" href="#ref_guide_schema_schematool" title="13.&nbsp; Schema Tool">Section&nbsp;13, &#8220;
Schema Tool
&#8221;</a> for
more info about <code class="literal">deleteTableContents</code>.) Defaults to
<code class="literal">false</code>, since the statement may fail if using InnoDB
tables and delete constraints.
</p>
</li></ul></div>
<p>
Starting with Connector/J 3.1.7, MySQL supports a variant of the driver
<code class="literal">com.mysql.jdbc.ReplicationDriver</code> that automatically sends
queries to a read/write master, or a failover or round-robin load balanced set
of slaves based on the state of read-only status of the connection.
See <a class="ulink" href="http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-replication-connection.html" target="_top">
MySQL Reference</a> for more details.
</p>
<p>
This replication feature can be used transparently with OpenJPA application by
following configuration:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">openjpa.ConnectionDriverName: com.mysql.jdbc.ReplicationDriver</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">openjpa.ConnectionFactoryProperties: autoReconnect=true,roundRobinLoadBalance=true</code>
</p>
<p>
OpenJPA will use a read-only connection with replicated database configuration
and will automatically switch the connection to a non-readonly mode if the
transaction is writing to the database.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_dbsetup_dbsupport_oracle"><div class="titlepage"><div><div><h3 class="title">4.4.&nbsp;
OracleDictionary Properties
</h3></div></div></div>
<a class="indexterm" name="d5e11379"></a>
<p>
The <code class="literal">oracle</code> dictionary understands the following additional
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem" id="OracleDictionary.UseTriggersForAutoAssign">
<p>
<a class="indexterm" name="d5e11387"></a>
<a class="indexterm" name="d5e11390"></a>
<code class="literal">UseTriggersForAutoAssign</code>: When true, OpenJPA will allow
simulation of auto-increment columns by the use of Oracle triggers. OpenJPA will
assume that the current sequence value from the sequence specified in the
<code class="literal">AutoAssignSequenceName</code> parameter will hold the value of the
new primary key for rows that have been inserted. For more details on
auto-increment support, see <a class="xref" href="#ref_guide_pc_oid_pkgen_autoinc" title="4.4.&nbsp; Autoassign / Identity Strategy Caveats">Section&nbsp;4.4, &#8220;
Autoassign / Identity Strategy Caveats
&#8221;</a>
.
</p>
</li><li class="listitem" id="OracleDictionary.AutoAssignSequenceName">
<p>
<a class="indexterm" name="d5e11399"></a>
<a class="indexterm" name="d5e11402"></a>
<code class="literal">AutoAssignSequenceName</code>: The global name of the sequence that
OpenJPA will assume to hold the value of primary key value for rows that use
auto-increment. If left unset, OpenJPA will use a sequence named <code class="literal">
"&lt;table name&gt;_&lt;column name&gt;_SEQ"</code>.
</p>
</li><li class="listitem" id="OracleDictionary.MaxEmbeddedBlobSize">
<p>
<a class="indexterm" name="d5e11410"></a>
<a class="indexterm" name="d5e11413"></a>
<code class="literal">MaxEmbeddedBlobSize</code>: Oracle is unable to persist BLOBs using
the embedded update method when BLOBs get over a certain size. The size depends
on database configuration, e.g. encoding. This property defines the maximum size
BLOB to persist with the embedded method. Defaults to 4000 bytes.
</p>
</li><li class="listitem" id="OracleDictionary.MaxEmbeddedClobSize">
<p>
<a class="indexterm" name="d5e11419"></a>
<a class="indexterm" name="d5e11422"></a>
<code class="literal">MaxEmbeddedClobSize</code>: Oracle is unable to persist CLOBs using
the embedded update method when CLOBs get over a certain size. The size depends
on database configuration, e.g. encoding. This property defines the maximum size
CLOB to persist with the embedded method. Defaults to 4000 characters.
</p>
</li><li class="listitem" id="OracleDictionary.SupportsSetClob">
<p>
<code class="literal">SupportsSetClob</code>: This property was used in releases previous
to OpenJPA 2.2.0
to indicate that OpenJPA should attempt to use a Reader-based JDBC 4.0 method to
set CLOB or XML data. It allowed XMLType and CLOB values larger than 4000 bytes
to be used. For OpenJPA 2.2.0 and later releases, code was added to allow said
functionality by default (see OPENJPA-1691). For forward compatibility, this
property still remains, however it has been deprecated and will eventually be
removed. Setting this property has no effect and any occurrence of it should
be removed.
</p>
</li><li class="listitem" id="OracleDictionary.UseSetFormOfUseForUnicode">
<p>
<code class="literal">UseSetFormOfUseForUnicode</code>: Prior to Oracle 10i, statements
executed against unicode capable columns (the <code class="literal">NCHAR</code>,
<code class="literal">NVARCHAR</code>, <code class="literal">NCLOB</code> Oracle types) required
special handling to be able to store unicode values. Setting this property to
<code class="literal">true</code> (the default) will cause OpenJPA to attempt to detect when the column is
one of these types, and if so, will attempt to correctly configure the statement
using the <code class="methodname"> OraclePreparedStatement.setFormOfUse</code>. For
more details, see the Oracle
<a class="ulink" href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14225/ch7progrunicode.htm#i1006858" target="_top">
JDBC Programming with Unicode</a>. Note that this can only work if OpenJPA is able to
access the underlying <code class="classname">OraclePreparedStatement</code> instance,
which may not be possible when using some third-party datasources. If OpenJPA
detects that this is the case, a warning will be logged.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_dbsetup_dbsupport_sybase"><div class="titlepage"><div><div><h3 class="title">4.5.&nbsp;
SybaseDictionary Properties
</h3></div></div></div>
<a class="indexterm" name="d5e11441"></a>
<p>
The <code class="literal">sybase</code> dictionary understands the following additional
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem" id="SybaseDictionary.IgnoreNumericTruncation">
<p>
<a class="indexterm" name="d5e11449"></a>
<code class="literal">IgnoreNumericTruncation</code>: If true, Sybase will ignore numeric
truncation on SQL operations. Otherwise, if numeric truncation is detected,
the operation will fail.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_dbsetup_dbsupport_db2"><div class="titlepage"><div><div><h3 class="title">4.6.&nbsp;
DB2 Properties
</h3></div></div></div>
<a class="indexterm" name="d5e11455"></a>
<p>
The <code class="literal">db2</code> dictionary understands the following additional
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem" id="DB2Dictionary.AppendExtendedExceptionText">
<p>
<a class="indexterm" name="d5e11463"></a>
<code class="literal">AppendExtendedExceptionText</code>: If false, OpenJPA will not call back to the database to
get extended exception text.
</p>
</li><li class="listitem" id="DB2Dictionary.SupportsRowNum">
<p>
<a class="indexterm" name="d5e11469"></a>
<code class="literal">SupportsRowNum</code>: If true, OpenJPA will use <code class="literal">ROWNUM</code> facility
for range based queries that set an offset and/or limit via <code class="literal">setFirstResult()</code>
and <code class="literal">setMaxResult()</code> query methods. This property must be set to <code class="literal">true</code>
alongwith <span style="color: red">&lt;lietral&gt;SupportsSelectStartIndex&lt;/lietral&gt;</span> and <span style="color: red">&lt;lietral&gt;SupportsSelectEndIndex&lt;/lietral&gt;</span>.
By default, <code class="literal">SupportsRowNum</code> is set to <code class="literal">false</code>.
It is appropriate to set <code class="literal">SupportsRowNum</code> to <code class="literal">true</code> only when
DB2 version being used is 9.7 or later.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_dbsetup_dbsupport_delim_id"><div class="titlepage"><div><div><h3 class="title">4.7.&nbsp;
Delimited Identifiers Support
</h3></div></div></div>
<p>
OpenJPA provides support for delimited identifiers as defined in the JPA 2.0 specification.
Identifiers can either be automatically delimited or individually manually
delimited. To have OpenJPA automatically delimit identifiers, add the
<code class="literal">&lt;delimited-identifiers/&gt;</code> tag
to the mapping file as documented in the JPA specification.
</p>
<p>
You can manually delimit individual identifiers either in the annotations or in the
definitions in the mapping file. To delimit an identifier element in an annotation,
surround it with double quotes. In a mapping file, add
<code class="literal">&amp;quote;</code> to both the beginning and end of the element.
</p>
<p>
When delimited identifiers has been specified, OpenJPA will delimit SQL identifiers
in the generated SQL statements. It will use database-specific delimiters as defined
in the appropriate database dictionary. By default, the leading and trailing
delimiters are both double quotes, <code class="literal">(")</code>. Different defaults for other
dictionaries provided by OpenJPA are in the following table.
</p>
<div class="table" id="d5e11491"><p class="title"><b>Table&nbsp;4.1.&nbsp;
Default delimiters for delimited identifiers
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Default delimiters for delimited identifiers&#xA; " border="1"><colgroup><col align="left" class="dict"><col align="left" class="lead"><col align="left" class="trail"></colgroup><thead><tr><th align="left">
Dictionary
</th><th align="left">
Leading Delimiter
</th><th align="left">
Trailing Delimiter
</th></tr></thead><tbody><tr><td align="left">
MySQLDictionary
</td><td align="center">
`
</td><td align="center">
`
</td></tr><tr><td align="left">
AccessDictionary
</td><td align="center">
[
</td><td align="center">
]
</td></tr></tbody></table>
</div></div><br class="table-break">
<p>
Some databases support more than one set of delimiters, often based on configuration.
If you need values different than the default values, you can set the
<a class="link" href="#DBDicationary.LeadingDelimiter"><code class="literal">LeadingDelimiter</code></a>
and the
<a class="link" href="#DBDicationary.TrailingDelimiter"><code class="literal">TrailingDelimiter</code></a>
dictionary properties.
</p>
<p>
You can specify whether or not the particular database that you are using supports delimited
identifiers by setting the
<a class="link" href="#DBDictionary.SupportsDelimitedIdentifiers"><code class="literal">SupportsDelimitedIdentifiers</code></a>
dictionary property. If this value is set to <code class="literal">false</code>, identifiers will not be automatically
delimited, even if the <code class="literal">&lt;delimited-identifiers/&gt;</code> tag is specified
in the mapping file.
</p>
<p>
<code class="literal">Limitation:</code> The <code class="literal">columnDefinition</code> elements in identifiers
are not automatically delimited by OpenJPA when using the
<code class="literal">&lt;delimited-identifiers/&gt;</code> tag
in the mapping file. If you want these to be delimited, you must manually delimit them in
the annotation or mapping file definitions.
</p>
</div>
</div>
<div class="section" id="ref_guide_dbsetup_isolation"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Setting the Transaction Isolation
</h2></div></div></div>
<a class="indexterm" name="d5e11527"></a>
<a class="indexterm" name="d5e11530"></a>
<a class="indexterm" name="d5e11533"></a>
<p>
OpenJPA typically retains the default transaction isolation level of the JDBC
driver. However, you can specify a transaction isolation level to use through
the <a class="link" href="#openjpa.jdbc.TransactionIsolation" title="6.18.&nbsp; openjpa.jdbc.TransactionIsolation"><code class="literal">
openjpa.jdbc.TransactionIsolation</code></a> configuration property. The
following is a list of standard isolation levels. Note that not all databases
support all isolation levels.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">default</code>: Use the JDBC driver's default isolation level.
OpenJPA uses this option if you do not explicitly specify any other.
</p>
</li><li class="listitem">
<p>
<code class="literal">none</code>: No transaction isolation.
</p>
</li><li class="listitem">
<p>
<code class="literal">read-committed</code>: Dirty reads are prevented; non-repeatable
reads and phantom reads can occur.
</p>
</li><li class="listitem">
<p>
<code class="literal">read-uncommitted</code>: Dirty reads, non-repeatable reads and
phantom reads can occur.
</p>
</li><li class="listitem">
<p>
<code class="literal">repeatable-read</code>: Dirty reads and non-repeatable reads are
prevented; phantom reads can occur.
</p>
</li><li class="listitem">
<p>
<code class="literal">serializable</code>: Dirty reads, non-repeatable reads, and phantom
reads are prevented.
</p>
</li></ul></div>
<div class="example" id="ref_guide_dbsetup_isoex"><p class="title"><b>Example&nbsp;4.8.&nbsp;
Specifying a Transaction Isolation
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.TransactionIsolation" value="repeatable-read"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_dbsetup_sql92"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
Setting the SQL Join Syntax
</h2></div></div></div>
<a class="indexterm" name="d5e11562"></a>
<a class="indexterm" name="d5e11565"></a>
<p>
Object queries often involve using SQL joins behind the scenes. You can
configure OpenJPA to use either SQL 92-style join syntax, in which joins are
placed in the SQL FROM clause, the traditional join syntax, in which join
criteria are part of the WHERE clause, or a database-specific join syntax
mandated by the <a class="link" href="#ref_guide_dbsetup_dbdict" title="Example&nbsp;4.7.&nbsp; Specifying a DBDictionary"><code class="classname">
DBDictionary</code></a>. OpenJPA only supports outer joins when using
SQL 92 syntax or a database-specific syntax with outer join support.
</p>
<p>
The <a class="link" href="#openjpa.jdbc.DBDictionary" title="6.2.&nbsp; openjpa.jdbc.DBDictionary"><code class="literal">
openjpa.jdbc.DBDictionary</code></a> plugin accepts the <code class="literal">
JoinSyntax</code> property to set the system's default syntax. The available
values are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">traditional</code>: Traditional SQL join syntax; outer joins are
not supported.
</p>
</li><li class="listitem">
<p>
<code class="literal">database</code>: The database's native join syntax. Databases that
do not have a native syntax will default to one of the other options.
</p>
</li><li class="listitem">
<p>
<code class="literal">sql92</code>: ANSI SQL92 join syntax. Outer joins are supported.
Not all databases support this syntax.
</p>
</li></ul></div>
<p>
You can change the join syntax at runtime through the OpenJPA fetch
configuration API, which is described in <a class="xref" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">Chapter&nbsp;9, <i>
Runtime Extensions
</i></a>.
</p>
<div class="example" id="ref_guide_dbsetup_sql92_conf"><p class="title"><b>Example&nbsp;4.9.&nbsp;
Specifying the Join Syntax Default
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.DBDictionary" value="JoinSyntax=sql92"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_dbsetup_sql92_fetch"><p class="title"><b>Example&nbsp;4.10.&nbsp;
Specifying the Join Syntax at Runtime
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.jdbc.*;
...
Query q = em.createQuery("select m from Magazine m where m.title = 'JDJ'");
OpenJPAQuery kq = OpenJPAPersistence.cast(q);
JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan();
fetch.setJoinSyntax(JoinSyntax.SQL92);
List results = q.getResultList();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_dbsetup_multidb"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
Accessing Multiple Databases
</h2></div></div></div>
<a class="indexterm" name="d5e11595"></a>
<p>
Through the properties we've covered thus far, you can configure each
<code class="classname">EntityManagerFactory</code> to access a different
database. If your application accesses multiple databases, we recommend that you
maintain a separate persistence unit for each one. This will allow you to easily
load the appropriate resource for each database at runtime, and to give the
correct configuration file to OpenJPA's command-line tools during development.
</p>
</div>
<div class="section" id="ref_guide_dbsetup_retain"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;
Configuring the Use of JDBC Connections
</h2></div></div></div>
<a class="indexterm" name="d5e11602"></a>
<p>
In its default configuration, OpenJPA obtains JDBC connections on an as-needed
basis. OpenJPA <code class="classname">EntityManager</code>s do not retain a connection
to the database unless they are in a datastore transaction or there are open
<code class="classname">Query</code> results that are using a live JDBC result set. At
all other times, including during optimistic transactions, <code class="classname">
EntityManager</code>s request a connection for each query, then
immediately release the connection back to the pool.
</p>
<p>
<a class="indexterm" name="d5e11610"></a>
In some cases, it may be more efficient to retain connections for longer periods
of time. You can configure OpenJPA's use of JDBC connections through the
<a class="link" href="#openjpa.ConnectionRetainMode" title="5.25.&nbsp; openjpa.ConnectionRetainMode"><code class="literal">
openjpa.ConnectionRetainMode</code></a> configuration property. The
property accepts the following values:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">always</code>: Each <code class="classname">EntityManager</code> obtains a
single connection and uses it until the <code class="classname">EntityManager</code>
closes. Great care should be taken when using this property if the application
cannot close the EntityManager (i.e. container-managed EntityManagers in a JEE
Application Server). In this case the connection will remain open for an
undefined time and the application may not be able to recover from a terminated
connection (for example, if a TCP/IP timeout severs the connection to the database).
For this reason the <code class="literal">always</code> option should not be used with
container-managed EntityManagers.
</p>
</li><li class="listitem">
<p>
<code class="literal">transaction</code>: A connection is obtained when each transaction
begins (optimistic or datastore), and is released when the transaction
completes. Non-transactional connections are obtained on-demand.
</p>
</li><li class="listitem">
<p>
<code class="literal">on-demand</code>: Connections are obtained only when needed. This
option is equivalent to the <code class="literal">transaction</code> option when datastore
transactions are used. For optimistic transactions, though, it means that a
connection will be retained only for the duration of the datastore flush and
commit process.
</p>
</li></ul></div>
<p>
You can also specify the connection retain mode of individual <code class="classname">
EntityManager</code>s when you retrieve them from the <code class="classname">
EntityManagerFactory</code>. See
<a class="xref" href="#ref_guide_runtime_emfactory" title="2.1.&nbsp; OpenJPAEntityManagerFactory">Section&nbsp;2.1, &#8220;
OpenJPAEntityManagerFactory
&#8221;</a> for details.
</p>
<p>
<a class="indexterm" name="d5e11633"></a>
The <a class="link" href="#openjpa.FlushBeforeQueries" title="5.36.&nbsp; openjpa.FlushBeforeQueries"><code class="literal">
openjpa.FlushBeforeQueries</code></a> configuration property controls
another aspect of connection usage: whether to flush transactional changes
before executing object queries. This setting only applies to queries that would
otherwise have to be executed in-memory because the
<a class="link" href="#openjpa.IgnoreChanges" title="5.37.&nbsp; openjpa.IgnoreChanges"><code class="literal">IgnoreChanges</code></a>
property is set to false and the query may involve objects that have been
changed in the current transaction. Legal values are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">true</code>: Always flush rather than executing the query
in-memory. If the current transaction is optimistic, OpenJPA will begin a
non-locking datastore transaction. This is the default.
</p>
</li><li class="listitem">
<p>
<code class="literal">false</code>: Never flush before a query.
</p>
</li><li class="listitem">
<p>
<code class="literal">with-connection</code>: Flush only if the <code class="classname">EntityManager
</code> has already established a dedicated connection to the datastore,
otherwise execute the query in-memory.
This option is useful if you use long-running optimistic transactions and want
to ensure that these transactions do not consume database resources until
commit. OpenJPA's behavior with this option is dependent on the transaction
status and mode, as well as the configured connection retain mode described
earlier in this section.
</p>
</li></ul></div>
<p>
The flush mode can also be varied at runtime using the OpenJPA fetch
configuration API, discussed in <a class="xref" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">Chapter&nbsp;9, <i>
Runtime Extensions
</i></a>.
</p>
<p>
<a class="indexterm" name="d5e11653"></a>
The table below describes the behavior of automatic flushing in various
situations. In all cases, flushing will only occur if OpenJPA detects that you
have made modifications in the current transaction that may affect the query's
results.
</p>
<div class="table" id="d5e11656"><p class="title"><b>Table&nbsp;4.2.&nbsp;
OpenJPA Automatic Flush Behavior
</b></p><div class="table-contents">
<table class="table" summary="&#xA; OpenJPA Automatic Flush Behavior&#xA; " border="1"><colgroup><col align="left" class="col1"><col align="left" class="col2"><col align="left" class="col3"><col align="left" class="col4"><col align="left" class="col5"></colgroup><thead><tr><th align="left">
</th><th align="left">
FlushBeforeQueries = false
</th><th align="left">
FlushBeforeQueries = true
</th><th align="left">
FlushBeforeQueries = with-connection;
ConnectionRetainMode = on-demand
</th><th align="left">
FlushBeforeQueries = with-connection;
ConnectionRetainMode = transaction or always
</th></tr></thead><tbody><tr><td align="left">
<span class="bold"><strong>
IgnoreChanges = true
</strong></span>
</td><td align="left">
no flush
</td><td align="left">
no flush
</td><td align="left">
no flush
</td><td align="left">
no flush
</td></tr><tr><td align="left">
<span class="bold"><strong>
IgnoreChanges = false; no tx active
</strong></span>
</td><td align="left">
no flush
</td><td align="left">
no flush
</td><td align="left">
no flush
</td><td align="left">
no flush
</td></tr><tr><td align="left">
<span class="bold"><strong>
IgnoreChanges = false; datastore tx active
</strong></span>
</td><td align="left">
no flush
</td><td align="left">
flush
</td><td align="left">
flush
</td><td align="left">
flush
</td></tr><tr><td align="left">
<span class="bold"><strong>
IgnoreChanges = false; optimistic tx active
</strong></span>
</td><td align="left">
no flush
</td><td align="left">
flush
</td><td align="left">
no flush unless <code class="methodname">flush</code> has already been invoked
</td><td align="left">
flush
</td></tr></tbody></table>
</div></div><br class="table-break">
<div class="example" id="ref_guide_dbsetup_sql92_retain_conf"><p class="title"><b>Example&nbsp;4.11.&nbsp;
Specifying Connection Usage Defaults
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.ConnectionRetainMode" value="on-demand"/&gt;
&lt;property name="openjpa.FlushBeforeQueries" value="true"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_dbsetup_sql92_retain_runtime"><p class="title"><b>Example&nbsp;4.12.&nbsp;
Specifying Connection Usage at Runtime
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
// obtaining an em with a certain connection retain mode
Map props = new HashMap();
props.put("openjpa.ConnectionRetainMode", "always");
EntityManager em = emf.createEntityManager(props);
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_dbsetup_stmtbatch"><div class="titlepage"><div><div><h2 class="title" style="clear: both">9.&nbsp;
Statement Batching
</h2></div></div></div>
<a class="indexterm" name="d5e11709"></a>
<a class="indexterm" name="d5e11711"></a>
<p>
In addition to connection pooling and prepared statement caching, OpenJPA
employs statement batching to speed up JDBC updates. Statement batching is
enabled by default for any JDBC driver that supports it. When batching is on,
OpenJPA automatically orders its SQL statements to maximize the size of each
batch. This can result in large performance gains for transactions that modify
a lot of data.
</p>
<p>
You configure statement batching through the system DBDictionary, which is
controlled by the openjpa.jdbc.DBDictionary configuration property. You can
enable the statement batching by setting the batchLimit in the value. The batch
limit is the maximum number of statements OpenJPA will ever batch
together. A value has the following meaning:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-1</code>: Unlimited number of statements for a batch.
</p>
</li><li class="listitem">
<p>
<code class="literal">0</code>: Disable batch support. This is the default for most
dictionaries.
</p>
</li><li class="listitem">
<p>
<code class="literal">any positive number</code>: Maximum number of statements for a batch.
</p>
</li></ul></div><p>
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
By default, the batch support is based on each Dictionary to define the default
batch limit. Currently only DB2 and Oracle dictionaries are set the default
batch limit to 100. The default batch limit for the rest of the dictionaries is set
to zero (disabled).
</p>
</div><p>
</p>
<p>
The example below shows how to enable and disable statement batching via
your configuration properties.
</p>
<div class="example" id="ref_guide_dbsetup_stmtbatch_exmple1"><p class="title"><b>Example&nbsp;4.13.&nbsp;
Enable SQL statement batching
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.DBDictionary" value="db2(batchLimit=25)"/&gt;
&lt;property name="openjpa.jdbc.DBDictionary" value="oracle(batchLimit=-1)"/&gt;
Or
&lt;property name="openjpa.jdbc.DBDictionary" value="batchLimit=25"/&gt;
&lt;property name="openjpa.jdbc.DBDictionary" value="batchLimit=-1"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_dbsetup_stmtbatch_exmple2"><p class="title"><b>Example&nbsp;4.14.&nbsp;
Disable SQL statement batching
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.DBDictionary" value="db2(batchLimit=0)"/&gt;
Or
&lt;property name="openjpa.jdbc.DBDictionary" value="batchLimit=0"/&gt;
</pre>
</div></div><br class="example-break">
<p>
By default, org.apache.openjpa.jdbc.kernel.BatchingConstraintUpdateManager
is the default statement batching implementation. OPENJPA also
provides another update manager
org.apache.openjpa.jdbc.kernel.BatchingOperationOrderUpdateManager for the
statements that required ordering. You can plug-in this update manager through
the "openjpa.jdbc.UpdateManager" property. Or you can plug-in your own
statement batching implementation by providing the implementation that extends
from AbstractUpdateManager, ConstraitUpdateManager or OperationOrderUpdateManager.
Add this implementation
class as a property in the persistence.xml file. For example, a custom
statement batching implementation mycomp.MyUpdateManager extends
ConstraitUpdateManager. You specify this implementation in the persistence.xml
file as the following example:
</p>
<div class="example" id="ref_guide_dbsetup_stmtbatch_exmple3"><p class="title"><b>Example&nbsp;4.15.&nbsp;
Plug-in custom statement batching implementation
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.UpdateManager" value="mycomp.MyUpdateManager"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_dbsetup_lrs"><div class="titlepage"><div><div><h2 class="title" style="clear: both">10.&nbsp;
Large Result Sets
</h2></div></div></div>
<a class="indexterm" name="d5e11742"></a>
<a class="indexterm" name="d5e11744"></a>
<p>
By default, OpenJPA uses standard forward-only JDBC result sets, and completely
instantiates the results of database queries on execution. When using a JDBC
driver that supports version 2.0 or higher of the JDBC specification, however,
you can configure OpenJPA to use scrolling result sets that may not bring all
results into memory at once. You can also configure the number of result objects
OpenJPA keeps references to, allowing you to traverse potentially enormous
amounts of data without exhausting JVM memory.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
You can also configure on-demand loading for individual collection and map
fields via large result set proxies. See
<a class="xref" href="#ref_guide_pc_scos_proxy_lrs" title="6.4.2.&nbsp; Large Result Set Proxies">Section&nbsp;6.4.2, &#8220;
Large Result Set Proxies
&#8221;</a>.
</p>
</div>
<p>
Use the following properties to configure OpenJPA's handling of result sets:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e11756"></a>
<a class="link" href="#openjpa.FetchBatchSize" title="5.33.&nbsp; openjpa.FetchBatchSize"><code class="literal">openjpa.FetchBatchSize</code>
</a>: The number of objects to instantiate at once when traversing a result
set. This number will be set as the fetch size on JDBC <code class="classname">Statement
</code> objects used to obtain result sets. It also factors in to the
number of objects OpenJPA will maintain a hard reference to when traversing a
query result.
</p>
<p>
The fetch size defaults to -1, meaning all results will be instantiated
immediately on query execution. A value of 0 means to use the JDBC driver's
default batch size. Thus to enable large result set handling, you must set this
property to 0 or to a positive number.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e11764"></a>
<a class="link" href="#openjpa.jdbc.ResultSetType" title="6.11.&nbsp; openjpa.jdbc.ResultSetType"><code class="literal"> openjpa.jdbc.ResultSetType
</code></a>: The type of result set to use when executing database
queries. This property accepts the following values, each of which corresponds
exactly to the same-named <code class="classname">java.sql.ResultSet</code> constant:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">forward-only</code>: This is the default.
</p>
</li><li class="listitem">
<p>
<code class="literal">scroll-sensitive</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">scroll-insensitive</code>
</p>
</li></ul></div>
<p>
Different JDBC drivers treat the different result set types differently. Not all
drivers support all types.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e11782"></a>
<a class="link" href="#openjpa.jdbc.FetchDirection" title="6.5.&nbsp; openjpa.jdbc.FetchDirection"><code class="literal">
openjpa.jdbc.FetchDirection</code></a>: The expected order in which you
will access the query results. This property affects the type of data structure
OpenJPA will use to hold the results, and is also given to the JDBC driver in
case it can optimize for certain access patterns. This property accepts the
following values, each of which corresponds exactly to the same-named
<code class="classname">java.sql.ResultSet</code> FETCH constant:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">forward</code>: This is the default.
</p>
</li><li class="listitem">
<p>
<code class="literal">reverse</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">unknown</code>
</p>
</li></ul></div>
<p>
Not all drivers support all fetch directions.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e11800"></a>
<a class="link" href="#openjpa.jdbc.LRSSize" title="6.7.&nbsp; openjpa.jdbc.LRSSize"><code class="literal"> openjpa.jdbc.LRSSize</code>
</a>: The strategy OpenJPA will use to determine the size of result sets.
This property is <span class="bold"><strong>only</strong></span> used if you change the
fetch batch size from its default of -1, so that OpenJPA begins to use on-demand
result loading. Available values are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">query</code>: This is the default. The first time you ask for the
size of a query result, OpenJPA will perform a <code class="literal">SELECT COUNT(*)
</code> query to determine the number of expected results. Note that
depending on transaction status and settings, this can mean that the reported
size is slightly different than the actual number of results available.
</p>
</li><li class="listitem">
<p>
<code class="literal">last</code>: If you have chosen a scrollable result set type, this
setting will use the <code class="methodname">ResultSet.last</code> method to move to
the last element in the result set and get its index. Unfortunately, some JDBC
drivers will bring all results into memory in order to access the last one. Note
that if you do not choose a scrollable result set type, then this will behave
exactly like <code class="literal">unknown</code>. The default result set type is
<code class="literal">forward-only</code>, so you must change the result set type in
order for this property to have an effect.
</p>
</li><li class="listitem">
<p>
<code class="literal">unknown</code>: Under this setting OpenJPA will return <code class="literal">
Integer.MAX_VALUE</code> as the size for any query result that uses on-demand
loading.
</p>
</li></ul></div>
</li></ul></div>
<div class="example" id="ref_guide_dbsetup_lrs_def"><p class="title"><b>Example&nbsp;4.16.&nbsp;
Specifying Result Set Defaults
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.FetchBatchSize" value="20"/&gt;
&lt;property name="openjpa.jdbc.ResultSetType" value="scroll-insensitive"/&gt;
&lt;property name="openjpa.jdbc.FetchDirection" value="forward"/&gt;
&lt;property name="openjpa.jdbc.LRSSize" value="last"/&gt;
</pre>
</div></div><br class="example-break">
<p>
Many <a class="link" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">OpenJPA runtime components</a> also
have methods to configure these properties on a case-by-case basis through their
fetch configuration. See <a class="xref" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">Chapter&nbsp;9, <i>
Runtime Extensions
</i></a>.
</p>
<div class="example" id="ref_guide_dbsetup_lrs_runtime"><p class="title"><b>Example&nbsp;4.17.&nbsp;
Specifying Result Set Behavior at Runtime
</b></p><div class="example-contents">
<pre class="programlisting">
import java.sql.*;
import org.apache.openjpa.persistence.jdbc.*;
...
Query q = em.createQuery("select m from Magazine m where m.title = 'JDJ'");
OpenJPAQuery kq = OpenJPAPersistence.cast(q);
JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan();
fetch.setFetchBatchSize(20);
fetch.setResultSetType(ResultSetType.SCROLL_INSENSITIVE);
fetch.setFetchDirection(FetchDirection.FORWARD);
fetch.setLRSSizeAlgorithm(LRSSizeAlgorithm.LAST);
List results = q.getResultList();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_schema_def"><div class="titlepage"><div><div><h2 class="title" style="clear: both">11.&nbsp;
Default Schema
</h2></div></div></div>
<a class="indexterm" name="d5e11831"></a>
<p>
It is common to duplicate a database model in multiple schemas. You may have one
schema for development and another for production, or different database users
may access different schemas. OpenJPA facilitates these patterns with the
<a class="link" href="#openjpa.jdbc.Schema" title="6.12.&nbsp; openjpa.jdbc.Schema"><code class="literal">openjpa.jdbc.Schema</code>
</a> configuration property. This property establishes a default schema for
any unqualified table names, allowing you to leave schema names out of your
mapping definitions.
</p>
<p>
The <code class="literal">Schema</code> property also establishes the default schema for
new tables created through OpenJPA tools, such as the mapping tool covered in
<a class="xref" href="#ref_guide_mapping_mappingtool" title="1.&nbsp; Forward Mapping">Section&nbsp;1, &#8220;
Forward Mapping
&#8221;</a>.
</p>
<p>
If the entities are mapped to the same table name but with different schema
name within one <code class="literal">PersistenceUnit</code> intentionally, and the
strategy of <code class="literal">GeneratedType.AUTO</code> is used to generate the ID
for each entity, a schema name for each entity must be explicitly declared
either through the annotation or the mapping.xml file. Otherwise, the mapping
tool only creates the tables for those entities with the schema names under
each schema. In addition, there will be only one
<code class="literal">OPENJPA_SEQUENCE_TABLE</code> created for all the entities within
the <code class="literal">PersistenceUnit</code> if the entities are not identified
with the schema name.
Read <a class="xref" href="#ref_guide_sequence" title="6.&nbsp; Generators">Section&nbsp;6, &#8220;
Generators
&#8221;</a> in the Reference Guide.
</p>
</div>
<div class="section" id="ref_guide_schema_info"><div class="titlepage"><div><div><h2 class="title" style="clear: both">12.&nbsp;
Schema Reflection
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_schema_info_list">12.1.
Schemas List
</a></span></dt><dt><span class="section"><a href="#ref_guide_schema_info_factory">12.2.
Schema Factory
</a></span></dt></dl></div>
<a class="indexterm" name="d5e11848"></a>
<p>
OpenJPA needs information about your database schema for two reasons. First, it
can use schema information at runtime to validate that your schema is compatible
with your persistent class definitions. Second, OpenJPA requires schema
information during development so that it can manipulate the schema to match
your object model. OpenJPA uses the <code class="literal">SchemaFactory</code> interface
to provide runtime mapping information, and the <code class="classname">SchemaTool
</code> for development-time data. Each is presented below.
</p>
<div class="section" id="ref_guide_schema_info_list"><div class="titlepage"><div><div><h3 class="title">12.1.&nbsp;
Schemas List
</h3></div></div></div>
<a class="indexterm" name="d5e11856"></a>
<a class="indexterm" name="d5e11858"></a>
<p>
By default, schema reflection acts on all the schemas your JDBC driver can
"see". You can limit the schemas and tables OpenJPA acts on with the <code class="literal">
openjpa.jdbc.Schemas</code> configuration property. This property accepts a
comma-separated list of schemas and tables. To list a schema, list its name. To
list a table, list its full name in the form <code class="literal">
&lt;schema-name&gt;.&lt;table-name&gt;</code>. If a table does not have a
schema or you do not know its schema, list its name as <code class="literal">
.&lt;table-name&gt;</code> (notice the preceding '.'). For example, to list
the <code class="literal">BUSOBJS</code> schema, the <code class="literal">ADDRESS</code> table in
the <code class="literal">GENERAL</code> schema, and the <code class="literal">SYSTEM_INFO</code>
table, regardless of what schema it is in, use the string:
</p>
<pre class="programlisting">
BUSOBJS,GENERAL.ADDRESS,.SYSTEM_INFO
</pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Some databases are case-sensitive with respect to schema and table names.
Oracle, for example, requires names in all upper case.
</p>
</div>
</div>
<div class="section" id="ref_guide_schema_info_factory"><div class="titlepage"><div><div><h3 class="title">12.2.&nbsp;
Schema Factory
</h3></div></div></div>
<a class="indexterm" name="d5e11874"></a>
<p>
OpenJPA relies on the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/SchemaFactory.html" target="_top">
<code class="classname">openjpa.jdbc.SchemaFactory</code></a> interface for runtime
schema information. You can control the schema factory OpenJPA uses through the
<code class="literal">openjpa.jdbc.SchemaFactory</code> property. There are several
built-in options to choose from:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">dynamic</code>: This is the default setting. It is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/DynamicSchemaFactory.html" target="_top">
<code class="classname">
org.apache.openjpa.jdbc.schema.DynamicSchemaFactory</code></a>. The
<code class="classname">DynamicSchemaFactory</code> is the most performant
schema factory, because it does not validate mapping information against the
database. Instead, it assumes all object-relational mapping information is
correct, and dynamically builds an in-memory representation of the schema from
your mapping metadata. When using this factory, it is important that your
mapping metadata correctly represent your database's foreign key constraints so
that OpenJPA can order its SQL statements to meet them.
</p>
</li><li class="listitem">
<p>
<code class="literal">native</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/LazySchemaFactory.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.schema.LazySchemaFactory</code></a>
. As persistent classes are loaded by the application, OpenJPA reads their
metadata and object-relational mapping information. This factory uses the
<code class="classname">java.sql.DatabaseMetaData</code> interface to reflect on the
schema and ensure that it is consistent with the mapping data being read.
Use this factory if you want up-front validation that your mapping metadata is
consistent with the database during development. This factory accepts the
following important properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">ForeignKeys</code>: Set to <code class="literal">true</code> to automatically
read foreign key information during schema validation.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<code class="literal">table</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/TableSchemaFactory.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.schema.TableSchemaFactory</code></a>
. This schema factory stores schema information as an XML document in a database
table it creates for this purpose. If your JDBC driver doesn't support the
<code class="classname">java.sql.DatabaseMetaData</code> standard interface, but you
still want some schema validation to occur at runtime, you might use this
factory. It is not recommended for most users, though, because it is easy for
the stored XML schema definition to get out-of-synch with the actual database.
This factory accepts the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">Table</code>: The name of the table to create to store schema
information. Defaults to <code class="literal">OPENJPA_SCHEMA</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">PrimaryKeyColumn</code>: The name of the table's numeric primary
key column. Defaults to <code class="literal">ID</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">SchemaColumn</code>: The name of the table's string column for
holding the schema definition as an XML string. Defaults to <code class="literal">SCHEMA_DEF
</code>.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<code class="literal">file</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/FileSchemaFactory.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.schema.FileSchemaFactory</code></a>
. This factory is a lot like the <code class="classname">TableSchemaFactory</code>, and
has the same advantages and disadvantages. Instead of storing its XML schema
definition in a database table, though, it stores it in a file. This factory
accepts the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">File</code>: The resource name of the XML schema file. By default,
the factory looks for a resource called <code class="filename"> package.schema</code>,
located in any top-level directory of the <code class="literal">CLASSPATH</code> or in the
top level of any jar in your <code class="literal">CLASSPATH</code>.
</p>
</li></ul></div>
</li></ul></div>
<p>
You can switch freely between schema factories at any time. The XML file format
used by some factories is detailed in <a class="xref" href="#ref_guide_schema_xml" title="14.&nbsp; XML Schema Format">Section&nbsp;14, &#8220;
XML Schema Format
&#8221;</a>
. As with any OpenJPA plugin, you can also implement your own schema
factory if you have needs not met by the existing options.
</p>
</div>
</div>
<div class="section" id="ref_guide_schema_schematool"><div class="titlepage"><div><div><h2 class="title" style="clear: both">13.&nbsp;
Schema Tool
</h2></div></div></div>
<a class="indexterm" name="d5e11935"></a>
<a class="indexterm" name="d5e11938"></a>
<a class="indexterm" name="d5e11942"></a>
<a class="indexterm" name="d5e11946"></a>
<p>
Most users will only access the schema tool indirectly, through the interfaces
provided by other tools. You may find, however, that the schema tool is a
powerful utility in its own right. The schema tool has two functions:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
To reflect on the current database schema, optionally translating it to an XML
representation for further manipulation.
</p>
</li><li class="listitem">
<p>
To take in an XML schema definition, calculate the differences between the XML
and the existing database schema, and apply the necessary changes to make the
database match the XML.
</p>
</li></ol></div>
<p>
The <a class="link" href="#ref_guide_schema_xml" title="14.&nbsp; XML Schema Format">XML format</a> used by the schema
tool abstracts away the differences between SQL dialects used by different
database vendors. The tool also automatically adapts its SQL to meet foreign key
dependencies. Thus the schema tool is useful as a general way to manipulate
schemas.
</p>
<p>
You can invoke the schema tool through its Java class,
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/schema/SchemaTool.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.schema.SchemaTool</code></a>. In
addition to the universal flags of the <a class="link" href="#ref_guide_conf" title="Chapter&nbsp;2.&nbsp; Configuration">
configuration framework</a>, the schema tool accepts the following command
line arguments:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-ignoreErrors/-i &lt;true/t | false/f&gt;</code>: If <code class="literal">false
</code>, an exception will be thrown if the tool encounters any database
errors. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-file/-f &lt;stdout | output file&gt;</code>: Use this option to
write a SQL script for the planned schema modifications, rather them committing
them to the database. When used in conjunction with the <code class="literal">export
</code> or <code class="literal">reflect</code> actions, the named file will be used to
write the exported schema XML. If the file names a resource in the <code class="literal">
CLASSPATH</code>, data will be written to that resource. Use <code class="literal">stdout
</code> to write to standard output. Defaults to <code class="literal">stdout</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-openjpaTables/-ot &lt;true/t | false/f&gt;</code>: When reflecting
on the schema, whether to reflect on tables and sequences whose names start with
<code class="literal">OPENJPA_</code>. Certain OpenJPA components may use such tables -
for example, the <code class="literal">table</code> schema factory option covered in
<a class="xref" href="#ref_guide_schema_info_factory" title="12.2.&nbsp; Schema Factory">Section&nbsp;12.2, &#8220;
Schema Factory
&#8221;</a>. When using other
actions, <code class="literal">openjpaTables</code> controls whether these tables can be
dropped. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-rollbackBeforeDDL/-rbddl &lt;true/t | false/f&gt;</code>: Set this option to
<code class="literal">true</code> to send an initail rollback on the connection before any DDL statement is sent.
</p>
</li><li class="listitem">
<p>
<code class="literal">-dropTables/-dt &lt;true/t | false/f&gt;</code>: Set this option to
<code class="literal">true</code> to drop tables that appear to be unused during <code class="literal">
retain</code> and <code class="literal">refresh</code> actions. Defaults to <code class="literal">
true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-dropSequences/-dsq &lt;true/t | false/f&gt;</code>: Set this
option to <code class="literal">true</code> to drop sequences that appear to be unused
during <code class="literal">retain</code> and <code class="literal">refresh</code> actions.
Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-sequences/-sq &lt;true/t | false/f&gt;</code>: Whether to
manipulate sequences. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-indexes/-ix &lt;true/t | false/f&gt;</code>: Whether to manipulate
indexes on existing tables. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-primaryKeys/-pk &lt;true/t | false/f&gt;</code>: Whether to
manipulate primary keys on existing tables. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-foreignKeys/-fk &lt;true/t | false/f&gt;</code>: Whether to
manipulate foreign keys on existing tables. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-record/-r &lt;true/t | false/f&gt;</code>: Use <code class="literal">false
</code> to prevent writing the schema changes made by the tool to the current
<a class="link" href="#ref_guide_schema_info_factory" title="12.2.&nbsp; Schema Factory"><code class="literal">schema
factory</code></a>. Defaults to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-schemas/-s &lt;schema list&gt;</code>: A list of schema and table
names that OpenJPA should access during this run of the schema tool. This is
equivalent to setting the <a class="link" href="#openjpa.jdbc.Schemas" title="6.14.&nbsp; openjpa.jdbc.Schemas">
openjpa.jdbc.Schemas</a> property for a single run.
</p>
</li></ul></div>
<p>
The schema tool also accepts an <code class="literal">-action</code> or <code class="literal">-a
</code> flag. Multiple actions can be composed in a comma-separated list.
The available actions are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">add</code>: This is the default action if you do not specify one.
It brings the schema up-to-date with the given XML document by adding tables,
columns, indexes, etc. This action never drops any schema components.
</p>
</li><li class="listitem">
<p>
<code class="literal">retain</code>: Keep all schema components in the given XML
definition, but drop the rest from the database. This action never adds any
schema components.
</p>
</li><li class="listitem">
<p>
<code class="literal">drop</code>: Drop all schema components in the schema XML. Tables
will only be dropped if they would have 0 columns after dropping all columns
listed in the XML.
</p>
</li><li class="listitem">
<p>
<code class="literal">refresh</code>: Equivalent to <code class="literal">retain</code>, then
<code class="literal">add</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">build</code>: Generate SQL to build a schema matching the one in
the given XML file. Unlike <code class="literal">add</code>, this option does not take
into account the fact that part of the schema defined in the XML file might
already exist in the database. Therefore, this action is typically used in
conjunction with the <code class="literal">-file</code> flag to write a SQL script. This
script can later be used to recreate the schema in the XML.
</p>
</li><li class="listitem">
<p>
<code class="literal">reflect</code>: Generate an XML representation of the current
database schema.
</p>
</li><li class="listitem">
<p>
<code class="literal">createDB</code>: Generate SQL to re-create the current database.
This action is typically used in conjunction with the <code class="literal">-file</code>
flag to write a SQL script that can be used to recreate the current schema on a
fresh database.
</p>
</li><li class="listitem">
<p>
<code class="literal">dropDB</code>: Generate SQL to drop the current database. Like
<code class="literal">createDB</code>, this action can be used with the <code class="literal">-file
</code> flag to script a database drop rather than perform it.
</p>
</li><li class="listitem">
<p>
<code class="literal">import</code>: Import the given XML schema definition into the
current schema factory. Does nothing if the factory does not store a record of
the schema.
</p>
</li><li class="listitem">
<p>
<code class="literal">export</code>: Export the current schema factory's stored schema
definition to XML. May produce an empty file if the factory does not store a
record of the schema.
</p>
</li><li class="listitem">
<p>
<code class="literal">deleteTableContents</code>: Execute SQL to delete all rows from
all tables that OpenJPA knows about.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
The schema tool manipulates tables, columns, indexes, constraints, and
sequences. It cannot create or drop the database schema objects in which the
tables reside, however. If your XML documents refer to named database schemas,
those schemas must exist.
</p>
</div>
<p>
We present some examples of schema tool usage below.
</p>
<div class="example" id="ref_guide_schema_schematool_create"><p class="title"><b>Example&nbsp;4.18.&nbsp;
Schema Creation
</b></p><div class="example-contents">
<a class="indexterm" name="d5e12077"></a>
<p>
Add the necessary schema components to the database to match the given XML
document, but don't drop any data:
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.schema.SchemaTool targetSchema.xml
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_schema_schematool_script"><p class="title"><b>Example&nbsp;4.19.&nbsp;
SQL Scripting
</b></p><div class="example-contents">
<p>
Repeat the same action as the first example, but this time don't change the
database. Instead, write any planned changes to a SQL script:
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.schema.SchemaTool -f script.sql targetSchema.xml
</pre>
<p>
Write a SQL script that will re-create the current database:
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.schema.SchemaTool -a createDB -f script.sql
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_schema_schematool_table_cleanup"><p class="title"><b>Example&nbsp;4.20.&nbsp;
Table Cleanup
</b></p><div class="example-contents">
<a class="indexterm" name="d5e12090"></a>
<a class="indexterm" name="d5e12093"></a>
<p>
Refresh the schema and delete all contents of all tables that OpenJPA
knows about:
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.schema.SchemaTool -a refresh,deleteTableContents
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_schema_schematool_drop"><p class="title"><b>Example&nbsp;4.21.&nbsp;
Schema Drop
</b></p><div class="example-contents">
<p>
Drop the current database:
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.schema.SchemaTool -a dropDB
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_schema_schematool_reflect"><p class="title"><b>Example&nbsp;4.22.&nbsp;
Schema Reflection
</b></p><div class="example-contents">
<a class="indexterm" name="d5e12104"></a>
<p>
Write an XML representation of the current schema to file <code class="filename">schema.xml
</code>.
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.schema.SchemaTool -a reflect -f schema.xml
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_schema_xml"><div class="titlepage"><div><div><h2 class="title" style="clear: both">14.&nbsp;
XML Schema Format
</h2></div></div></div>
<a class="indexterm" name="d5e12113"></a>
<p>
The <a class="link" href="#ref_guide_schema_schematool" title="13.&nbsp; Schema Tool">schema tool</a> and
<a class="link" href="#ref_guide_schema_info_factory" title="12.2.&nbsp; Schema Factory"> schema factories</a> all use
the same XML format to represent database schema. The Document Type Definition
(DTD) for schema information is presented below, followed by examples of schema
definitions in XML.
</p>
<pre class="programlisting">
&lt;!ELEMENT schemas (schema)+&gt;
&lt;!ELEMENT schema (table|sequence)+&gt;
&lt;!ATTLIST schema name CDATA #IMPLIED&gt;
&lt;!ELEMENT sequence EMPTY&gt;
&lt;!ATTLIST sequence name CDATA #REQUIRED&gt;
&lt;!ATTLIST sequence initial-value CDATA #IMPLIED&gt;
&lt;!ATTLIST sequence increment CDATA #IMPLIED&gt;
&lt;!ATTLIST sequence allocate CDATA #IMPLIED&gt;
&lt;!ELEMENT table (column|index|pk|fk|unique)+&gt;
&lt;!ATTLIST table name CDATA #REQUIRED&gt;
&lt;!ELEMENT column EMPTY&gt;
&lt;!ATTLIST column name CDATA #REQUIRED&gt;
&lt;!ATTLIST column type (array | bigint | binary | bit | blob | char | clob
| date | decimal | distinct | double | float | integer | java_object
| longvarbinary | longvarchar | null | numeric | other | real | ref
| smallint | struct | time | timestamp | tinyint | varbinary | varchar)
#REQUIRED&gt;
&lt;!ATTLIST column not-null (true|false) "false"&gt;
&lt;!ATTLIST column auto-assign (true|false) "false"&gt;
&lt;!ATTLIST column default CDATA #IMPLIED&gt;
&lt;!ATTLIST column size CDATA #IMPLIED&gt;
&lt;!ATTLIST column decimal-digits CDATA #IMPLIED&gt;
&lt;!-- the type-name attribute can be used when you want OpenJPA to --&gt;
&lt;!-- use a particular SQL type declaration when creating the --&gt;
&lt;!-- column. It is up to you to ensure that this type is --&gt;
&lt;!-- compatible with the JDBC type used in the type attribute. --&gt;
&lt;!ATTLIST column type-name CDATA #IMPLIED&gt;
&lt;!-- the 'column' attribute of indexes, pks, and fks can be used --&gt;
&lt;!-- when the element has only one column (or for foreign keys, --&gt;
&lt;!-- only one local column); in these cases the on/join child --&gt;
&lt;!-- elements can be omitted --&gt;
&lt;!ELEMENT index (on)*&gt;
&lt;!ATTLIST index name CDATA #REQUIRED&gt;
&lt;!ATTLIST index column CDATA #IMPLIED&gt;
&lt;!ATTLIST index unique (true|false) "false"&gt;
&lt;!-- the 'logical' attribute of pks should be set to 'true' if --&gt;
&lt;!-- the primary key does not actually exist in the database, --&gt;
&lt;!-- but the given column should be used as a primary key for --&gt;
&lt;!-- O-R purposes --&gt;
&lt;!ELEMENT pk (on)*&gt;
&lt;!ATTLIST pk name CDATA #IMPLIED&gt;
&lt;!ATTLIST pk column CDATA #IMPLIED&gt;
&lt;!ATTLIST pk logical (true|false) "false"&gt;
&lt;!ELEMENT on EMPTY&gt;
&lt;!ATTLIST on column CDATA #REQUIRED&gt;
&lt;!-- fks with a delete-action of 'none' are similar to logical --&gt;
&lt;!-- pks; they do not actually exist in the database, but --&gt;
&lt;!-- represent a logical relation between tables (or their --&gt;
&lt;!-- corresponding Java classes) --&gt;
&lt;!ELEMENT fk (join)*&gt;
&lt;!ATTLIST fk name CDATA #IMPLIED&gt;
&lt;!ATTLIST fk deferred (true|false) "false"&gt;
&lt;!ATTLIST fk to-table CDATA #REQUIRED&gt;
&lt;!ATTLIST fk column CDATA #IMPLIED&gt;
&lt;!ATTLIST fk delete-action (cascade|default|exception|none|null) "none"&gt;
&lt;!ELEMENT join EMPTY&gt;
&lt;!ATTLIST join column CDATA #REQUIRED&gt;
&lt;!ATTLIST join to-column CDATA #REQUIRED&gt;
&lt;!ATTLIST join value CDATA #IMPLIED&gt;
&lt;!-- unique constraint --&gt;
&lt;!ELEMENT unique (on)*&gt;
&lt;!ATTLIST unique name CDATA #IMPLIED&gt;
&lt;!ATTLIST unique column CDATA #IMPLIED&gt;
&lt;!ATTLIST unique deferred (true|false) "false"&gt;
</pre>
<div class="example" id="ref_guide_schema_xml_basic"><p class="title"><b>Example&nbsp;4.23.&nbsp;
Basic Schema
</b></p><div class="example-contents">
<p>
A very basic schema definition.
</p>
<pre class="programlisting">
&lt;schemas&gt;
&lt;schema&gt;
&lt;sequence name="S_ARTS"/&gt;
&lt;table name="ARTICLE"&gt;
&lt;column name="TITLE" type="varchar" size="255" not-null="true"/&gt;
&lt;column name="AUTHOR_FNAME" type="varchar" size="28"&gt;
&lt;column name="AUTHOR_LNAME" type="varchar" size="28"&gt;
&lt;column name="CONTENT" type="clob"&gt;
&lt;/table&gt;
&lt;table name="AUTHOR"&gt;
&lt;column name="FIRST_NAME" type="varchar" size="28" not-null="true"&gt;
&lt;column name="LAST_NAME" type="varchar" size="28" not-null="true"&gt;
&lt;/table&gt;
&lt;/schema&gt;
&lt;/schemas&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_schema_xml_full"><p class="title"><b>Example&nbsp;4.24.&nbsp;
Full Schema
</b></p><div class="example-contents">
<p>
Expansion of the above schema with primary keys, constraints, and indexes, some
of which span multiple columns.
</p>
<pre class="programlisting">
&lt;schemas&gt;
&lt;schema&gt;
&lt;sequence name="S_ARTS"/&gt;
&lt;table name="ARTICLE"&gt;
&lt;column name="TITLE" type="varchar" size="255" not-null="true"/&gt;
&lt;column name="AUTHOR_FNAME" type="varchar" size="28"&gt;
&lt;column name="AUTHOR_LNAME" type="varchar" size="28"&gt;
&lt;column name="CONTENT" type="clob"&gt;
&lt;pk column="TITLE"/&gt;
&lt;fk to-table="AUTHOR" delete-action="exception"&gt;
&lt;join column="AUTHOR_FNAME" to-column="FIRST_NAME"/&gt;
&lt;join column="AUTHOR_LNAME" to-column="LAST_NAME"/&gt;
&lt;/fk&gt;
&lt;index name="ARTICLE_AUTHOR"&gt;
&lt;on column="AUTHOR_FNAME"/&gt;
&lt;on column="AUTHOR_LNAME"/&gt;
&lt;/index&gt;
&lt;/table&gt;
&lt;table name="AUTHOR"&gt;
&lt;column name="FIRST_NAME" type="varchar" size="28" not-null="true"&gt;
&lt;column name="LAST_NAME" type="varchar" size="28" not-null="true"&gt;
&lt;pk&gt;
&lt;on column="FIRST_NAME"/&gt;
&lt;on column="LAST_NAME"/&gt;
&lt;/pk&gt;
&lt;/table&gt;
&lt;/schema&gt;
&lt;/schemas&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="chapter" id="ref_guide_pc"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;5.&nbsp;
Persistent Classes
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_pc_pcclasses">1.
Persistent Class List
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance">2.
Enhancement
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_enhance_build">2.1.
Enhancing at Build Time
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime_container">2.2.
Enhancing JPA Entities on Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime">2.3.
Enhancing at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_dynamic">2.4.
Enhancing Dynamically at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_unenhanced_types">2.5.
Omitting the OpenJPA enhancer
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_interfaces">3. Managed Interfaces</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid">4.
Object Identity
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_oid_datastore">4.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_entitypk">4.2.
Entities as Identity Fields
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_application">4.3.
Application Identity Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_pkgen_autoinc">4.4.
Autoassign / Identity Strategy Caveats
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_inverses">5.
Managed Inverses
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos">6.
Persistent Fields
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_scos_restore">6.1.
Restoring State
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_order">6.2.
Typing and Ordering
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_calendar_timezone">6.3.
Calendar Fields and TimeZones
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy">6.4.
Proxies
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_smart">6.4.1.
Smart Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_lrs">6.4.2.
Large Result Set Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_custom">6.4.3.
Custom Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_serial">6.4.4.
Serialization
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_extern">6.5.
Externalization
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_extern_values">6.5.1.
External Values
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_fetch">7.
Fetch Groups
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_fetch_custom">7.1.
Custom Fetch Groups
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_conf">7.2.
Custom Fetch Group Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_single_field">7.3.
Per-field Fetch Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_impl">7.4.
Implementation Notes
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_perfpack_eager">8.
Eager Fetching
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_perfpack_eager_conf">8.1.
Configuring Eager Fetching
</a></span></dt><dt><span class="section"><a href="#ref_guide_perfpack_eager_consider">8.2.
Eager Fetching Considerations and Limitations
</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e12130"></a>
<p>
Persistent class basics are covered in <a class="xref" href="#jpa_overview_pc" title="Chapter&nbsp;4.&nbsp; Entity">Chapter&nbsp;4, <i>
Entity
</i></a>
of the JPA Overview. This chapter details the persistent class features OpenJPA
offers beyond the core JPA specification.
</p>
<div class="section" id="ref_guide_pc_pcclasses"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Persistent Class List
</h2></div></div></div>
<a class="indexterm" name="d5e12136"></a>
<a class="indexterm" name="d5e12139"></a>
<p>
Unlike many ORM products, OpenJPA does not need to know about all of your
persistent classes at startup. OpenJPA discovers new persistent classes
automatically as they are loaded into the JVM; in fact you can introduce new
persistent classes into running applications under OpenJPA. However, there are
certain situations in which providing OpenJPA with a persistent class list is
helpful:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
OpenJPA must be able to match entity names in JPQL queries to persistent
classes. OpenJPA automatically knows the entity names of any persistent classes
already loaded into the JVM. To match entity names to classes that have not been
loaded, however, you must supply a persistent class list.
</p>
</li><li class="listitem">
<p>
When OpenJPA manipulates classes in a persistent inheritance hierarchy, OpenJPA
must be aware of all the classes in the hierarchy. If some of the classes have
not been loaded into the JVM yet, OpenJPA may not know about them, and queries
may return incorrect results.
</p>
</li><li class="listitem">
<p>
If you configure OpenJPA to create the needed database schema on startup (see
<a class="xref" href="#ref_guide_mapping_synch" title="1.3.&nbsp; Runtime Forward Mapping">Section&nbsp;1.3, &#8220;
Runtime Forward Mapping
&#8221;</a>), OpenJPA must know all of your
persistent classes up-front.
</p>
</li></ul></div>
<p>
When any of these conditions are a factor in your JPA application, use the
<code class="literal">class</code>, <code class="literal">mapping-file</code>, and <code class="literal">
jar-file</code> elements of JPA's standard XML format to list your persistent
classes. See <a class="xref" href="#jpa_overview_persistence_xml" title="1.&nbsp; persistence.xml">Section&nbsp;1, &#8220;
persistence.xml
&#8221;</a> for details.
</p>
<p>
Alternately, you can tell OpenJPA to search through your classpath for
persistent types. This is described in more detail in
<a class="xref" href="#ref_guide_meta_factory" title="1.&nbsp; Metadata Factory">Section&nbsp;1, &#8220;
Metadata Factory
&#8221;</a>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Listing persistent classes (or their metadata or jar files) is an all-or-nothing
endeavor. If your persistent class list is non-empty, OpenJPA will assume that
any unlisted class is not persistent.
</p>
</div>
</div>
<div class="section" id="ref_guide_pc_enhance"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Enhancement
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_pc_enhance_build">2.1.
Enhancing at Build Time
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime_container">2.2.
Enhancing JPA Entities on Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_runtime">2.3.
Enhancing at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_dynamic">2.4.
Enhancing Dynamically at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_enhance_unenhanced_types">2.5.
Omitting the OpenJPA enhancer
</a></span></dt></dl></div>
<a class="indexterm" name="d5e12161"></a>
<a class="indexterm" name="d5e12163"></a>
<p>
In order to provide optimal runtime performance, flexible lazy loading, and
efficient, immediate dirty tracking, OpenJPA can use an <span class="emphasis"><em>enhancer
</em></span>. An enhancer is a tool that automatically adds code to your
persistent classes after you have written them. The enhancer post-processes the
bytecode generated by your Java compiler, adding the necessary fields and
methods to implement the required persistence features. This bytecode
modification perfectly preserves the line numbers in stack traces and is
compatible with Java debuggers. In fact, the only change to debugging
is that the persistent setter and getter methods of entity classes using
property access will be prefixed with <code class="literal">pc</code> in stack traces and
step-throughs. For example, if your entity has a <code class="methodname">getId</code>
method for persistent property <code class="literal">id</code>, and that method throws an
exception, the stack trace will report the exception from method <code class="methodname">
pcgetId</code>. The line numbers, however, will correctly correspond to
the <code class="methodname">getId</code> method in your source file.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="339"><tr><td><img src="img/enhancement.png"></td></tr></table></div>
<p>
The diagram above illustrates the compilation of a persistent class.
</p>
<p>
You can add the OpenJPA enhancer to your build process, or use Java 1.5's
instrumentation features to transparently enhance persistent classes when they
are loaded into the JVM. The following sections describe each option.
</p>
<div class="section" id="ref_guide_pc_enhance_build"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
Enhancing at Build Time
</h3></div></div></div>
<a class="indexterm" name="d5e12180"></a>
<p>
The enhancer can be invoked at build time
via its Java class, <code class="classname">
org.apache.openjpa.enhance.PCEnhancer</code>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
You can also enhance via Ant; see
<a class="xref" href="#ref_guide_integration_enhance" title="1.2.&nbsp; Enhancer Ant Task">Section&nbsp;1.2, &#8220;
Enhancer Ant Task
&#8221;</a>.
</p>
</div>
<div class="example" id="ref_guide_pc_enhance_enhancer"><p class="title"><b>Example&nbsp;5.1.&nbsp;
Using the OpenJPA Enhancer
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.enhance.PCEnhancer Magazine.java
</pre>
</div></div><br class="example-break">
<p>
The enhancer accepts the standard set of command-line arguments defined by the
configuration framework (see <a class="xref" href="#ref_guide_conf_devtools" title="3.&nbsp; Command Line Configuration">Section&nbsp;3, &#8220;
Command Line Configuration
&#8221;</a> ),
along with the following flags:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-directory/-d &lt;output directory&gt;</code>: Path to the output
directory. If the directory does not match the enhanced class' package, the
package structure will be created beneath the directory. By default, the
enhancer overwrites the original <code class="filename">.class</code> file.
</p>
</li><li class="listitem">
<p>
<code class="literal">-enforcePropertyRestrictions/-epr &lt;true/t | false/f&gt;</code>:
Whether to throw an exception when it appears that a property access entity is
not obeying the restrictions placed on property access. Defaults to false.
</p>
</li><li class="listitem">
<p>
<code class="literal">-addDefaultConstructor/-adc &lt;true/t | false/f&gt;</code>: The
spec requires that all persistent classes define a no-arg constructor. This flag
tells the enhancer whether to add a protected no-arg constructor to any
persistent classes that don't already have one. Defaults to <code class="literal">
true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-tmpClassLoader/-tcl &lt;true/t | false/f&gt;</code>: Whether to
load persistent classes with a temporary class loader. This allows other code to
then load the enhanced version of the class within the same JVM. Defaults to
<code class="literal">true</code>. Try setting this flag to <code class="literal">false</code> as a
debugging step if you run into class loading problems when running the enhancer.
</p>
</li></ul></div>
<p>
Each additional argument to the enhancer must be one of the following:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The full name of a class.
</p>
</li><li class="listitem">
<p>
The .java file for a class.
</p>
</li><li class="listitem">
<p>
The <code class="filename">.class</code> file of a class.
</p>
</li></ul></div>
<p>
If you do not supply any arguments to the enhancer, it will run on the classes
in your persistent class list (see <a class="xref" href="#ref_guide_pc_pcclasses" title="1.&nbsp; Persistent Class List">Section&nbsp;1, &#8220;
Persistent Class List
&#8221;</a>).
You must, however, supply the classpath you wish the enhancer to run with. This
classpath must include, at minimum, the openjpa jar(s), persistence.xml and
the target classes.
</p>
<p>
You can run the enhancer over classes that have already been enhanced, in which
case it will not further modify the class. You can also run it over classes that
are not persistence-capable, in which case it will treat the class as
persistence-aware. Persistence-aware classes can directly manipulate the
persistent fields of persistence-capable classes.
</p>
<p>
Note that the enhancement process for subclasses introduces dependencies on the
persistent parent class being enhanced. This is normally not problematic;
however, when running the enhancer multiple times over a subclass whose parent
class is not yet enhanced, class loading errors can occur. In the event of a
class load error, simply re-compile and re-enhance the offending classes.
</p>
</div>
<div class="section" id="ref_guide_pc_enhance_runtime_container"><div class="titlepage"><div><div><h3 class="title">2.2.&nbsp;
Enhancing JPA Entities on Deployment
</h3></div></div></div>
<a class="indexterm" name="d5e12225"></a>
<p>
The Java EE specification includes hooks to automatically enhance JPA entities
when they are deployed into a container. Thus, if you are using a Java EE-compliant application server,
OpenJPA will enhance your entities automatically
at runtime. Note that if you prefer build-time enhancement, OpenJPA's runtime
enhancer will correctly recognize and skip pre-enhanced classes.
</p>
<p>
If your application server does not support the Java EE enhancement hooks,
consider using the build-time enhancement described above, or the more general
runtime enhancement described in the next section.
</p>
</div>
<div class="section" id="ref_guide_pc_enhance_runtime"><div class="titlepage"><div><div><h3 class="title">2.3.&nbsp;
Enhancing at Runtime
</h3></div></div></div>
<a class="indexterm" name="d5e12233"></a>
<p>
OpenJPA includes a <span class="emphasis"><em>Java agent</em></span> for automatically enhancing
persistent classes as they are loaded into the JVM. Java agents are classes that
are invoked prior to your application's <code class="methodname">main</code> method.
OpenJPA's agent uses JVM hooks to intercept all class loading to enhance classes
that have persistence metadata before the JVM loads them.
</p>
<p>
Searching for metadata for every class loaded by the JVM can slow application
initialization. One way to speed things up is to take advantage of the optional
persistent class list described in <a class="xref" href="#ref_guide_pc_pcclasses" title="1.&nbsp; Persistent Class List">Section&nbsp;1, &#8220;
Persistent Class List
&#8221;</a>. If
you declare a persistent class list, OpenJPA will only search for
metadata for classes in that list.
</p>
<p>
To employ the OpenJPA agent, invoke <code class="literal">java</code> with the <code class="literal">
-javaagent</code> set to the path to your OpenJPA jar file.
</p>
<div class="example" id="ref_guide_pc_enhance_runtime_ex"><p class="title"><b>Example&nbsp;5.2.&nbsp;
Using the OpenJPA Agent for Runtime Enhancement
</b></p><div class="example-contents">
<pre class="programlisting">
java -javaagent:/home/dev/openjpa/lib/openjpa.jar com.xyz.Main
</pre>
</div></div><br class="example-break">
<p>
You can pass settings to the agent using OpenJPA's plugin syntax (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>). The agent accepts the long
form of any of the standard configuration options
(<a class="xref" href="#ref_guide_conf_devtools" title="3.&nbsp; Command Line Configuration">Section&nbsp;3, &#8220;
Command Line Configuration
&#8221;</a> ). It also accepts the following
options, the first three of which correspond exactly to the same-named
options of the enhancer tool described in
<a class="xref" href="#ref_guide_pc_enhance_build" title="2.1.&nbsp; Enhancing at Build Time">Section&nbsp;2.1, &#8220;
Enhancing at Build Time
&#8221;</a>:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">addDefaultConstructor</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">enforcePropertyRestrictions</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">scanDevPath</code>: Boolean indicating whether to scan the
classpath for persistent types if none have been configured. If you do not
specify a persistent types list and do not set this option to true, OpenJPA will
check whether each class loaded into the JVM is persistent, and enhance it
accordingly. This may slow down class load times significantly.
</p>
</li><li class="listitem">
<p>
<code class="literal">classLoadEnhancement</code>: Boolean controlling whether OpenJPA
load-time class enhancement should be available in this JVM execution. Default:
<code class="literal">true</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">runtimeRedefinition</code>: Boolean controlling whether OpenJPA
class redefinition should be available in this JVM execution. Default:
<code class="literal">true</code>
</p>
</li></ul></div>
<div class="example" id="ref_guide_pc_enhance_runtime_opt_ex"><p class="title"><b>Example&nbsp;5.3.&nbsp;
Passing Options to the OpenJPA Agent
</b></p><div class="example-contents">
<pre class="programlisting">
java -javaagent:/home/dev/openjpa/lib/openjpa.jar=addDefaultConstructor=false com.xyz.Main
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_pc_enhance_dynamic"><div class="titlepage"><div><div><h3 class="title">2.4.&nbsp;
Enhancing Dynamically at Runtime
</h3></div></div></div>
<p>
If a javaagent is not provided via the command line and
OpenJPA is running on the Oracle 1.6 SDK or IBM 1.6 JDK (SR8+), OpenJPA
will attempt to dynamically load the Enhancer that was
mentioned in the previous section. This support is
provided as an ease of use feature and it is not recommended
for use in a production system. Using this method of
enhancement has the following caveats:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The dynamic runtime enhancer is plugged into
the JVM during creation of the
EntityManagerFactory. Any Entity classes that
are loaded before the EntityManagerFactory is
created will not be enhanced.
</p>
</li><li class="listitem">
<p>
The command line javaagent settings are not
configurable when using this method of
enhancement.
</p>
</li><li class="listitem">
<p>
Just as with the Javaagent approach, if you
declare a persistent class list, then OpenJPA
will only search for metadata and try to
enhance the listed classes.
</p>
</li></ul></div>
<p>
When then dynamic enhancer is loaded, the following
informational message is logged:
</p><pre class="programlisting">
[java] jpa.enhancement INFO [main] openjpa.Runtime - OpenJPA dynamically loaded the class enhancer. Any classes that were not enhanced at build time will be enhanced when they are loaded by the JVM.
</pre><p>
</p>
<p>
Setting the property openjpa.DynamicEnhancementAgent to false
will disable this function.
</p>
</div>
<div class="section" id="ref_guide_pc_enhance_unenhanced_types"><div class="titlepage"><div><div><h3 class="title">2.5.&nbsp;
Omitting the OpenJPA enhancer
</h3></div></div></div>
<a class="indexterm" name="d5e12288"></a>
<p>
OpenJPA does not require that the enhancer be run. If you do not run the
enhancer, OpenJPA will fall back to one of several possible alternatives for
state tracking, depending on the execution environment.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<span class="emphasis"><em>Deploy-time enhancement</em></span>: if you are running your
application inside a Java EE container, or another environment that supports
the JPA container contract, then OpenJPA will automatically perform class
transformation at deploy time.
</p></li><li class="listitem"><p>
<span class="emphasis"><em>Java 6 class retransformation</em></span>: if you are running your
application in a Java 6 environment, OpenJPA will attempt to dynamically
register a <code class="literal">ClassTransformer</code> that will redefine your
persistent classes on the fly to track access to persistent data. Additionally,
OpenJPA will create a subclass for each of your persistent classes. When
you execute a query or traverse a relation, OpenJPA will return an instance
of the subclass. This means that the <code class="literal">instanceof</code> operator
will work as expected, but <code class="literal">o.getClass()</code> will return the
subclass instead of the class that you wrote.
</p>
<p>
You do not need to do anything at all to get this behavior. OpenJPA will
automatically detect whether or not the execution environment is capable of
Java 6 class retransformation.
</p></li><li class="listitem"><p>
<span class="emphasis"><em>Java 5 class redefinition</em></span>: if you are running your
application in a Java 5 environment, and you specify the OpenJPA javaagent,
OpenJPA will use Java 5 class redefinition to redefine any persistent classes
that are not enhanced by the OpenJPA javaagent. Aside from the requirement
that you specify a javaagent on the command line, this behavior is exactly the
same as the Java 6 class retransformation behavior. Of course, since the
OpenJPA javaagent performs enhancement by default, this will only be available
if you set the <code class="literal">classLoadEnhancement</code> javaagent flag to
<code class="literal">false</code>, or on any classes that are skipped by the OpenJPA
runtime enhancement process for some reason.
</p></li><li class="listitem"><p>
<span class="emphasis"><em>Runtime Unenhanced Classes</em></span>: AKA state comparison and
subclassing. If you are running
in a Java 5 environment without a javaagent, or in a Java 6 environment that
does not support class retransformation, OpenJPA will still create subclasses
as outlined above. However, in some cases, OpenJPA may not be able to receive
notifications when you read or write persistent data.
</p>
<p>
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
Runtime Unenhanced Classes has some known limitations which are discussed below
and documented in JIRA issue tracker on the OpenJPA website. As a result this option is
disabled by default. Support for this method of automatic enhancement may be
enabled via the <a class="xref" href="#openjpa.RuntimeUnenhancedClasses" title="5.65.&nbsp;openjpa.RuntimeUnenhancedClasses">Section&nbsp;5.65, &#8220;openjpa.RuntimeUnenhancedClasses&#8221;</a> option.
</div><p>
</p>
<p>
To enable Runtime Unenhanced Classes for a specific persistence unit, add the following property to persistence.xml:
</p><pre class="programlisting">
&lt;properties&gt;
. . .
&lt;property name="openjpa.RuntimeUnenhancedClasses" value="supported"/&gt;
. . .
&lt;properties&gt;
</pre><p>
</p>
<p>
If you are using <span class="emphasis"><em>property access</em></span> for your persistent data,
then OpenJPA will be able to track all accesses for instances that you load
from the database, but not for instances that you create. This is because
OpenJPA will create new instances of its dynamically-generated subclass when
it loads data from the database. The dynamically-generated subclass has
code in the setters and getters that notify OpenJPA about persistent data
access. This means that new instances that you create will be subject to
state-comparison checks (see discussion below) to compute which fields to
write to the database, and that OpenJPA will ignore requests to evict
persistent data from such instances. In practice, this is not a particularly
bad limitation, since OpenJPA already knows that it must insert all field
values for new instances. So, this is only really an issue if you flush
changes to the database while inserting new records; after such a flush,
OpenJPA will need to hold potentially-unneeded hard references to the
new-flushed instances.
</p>
<p>
If you are using <span class="emphasis"><em>field access</em></span> for your persistent data,
then OpenJPA will not be able to track accesses for any instances, including
ones that you load from the database. So, OpenJPA will perform state-comparison
checks to determine which fields are dirty. These state comparison checks are
costly in two ways. First, there is a performance penalty at flush / commit
time, since OpenJPA must walk through every field of every instance to determine
which fields of which records are dirty. Second, there is a memory penalty,
since OpenJPA must hold hard references to all instances that were loaded at
any time in a given transaction, and since OpenJPA must keep a copy of all
the initial values of the loaded data for later comparison. Additionally,
OpenJPA will ignore requests to evict persistent state for these types of
instances. Finally, the default lazy loading configuration will be ignored for
single-valued fields (one-to-one, many-to-one, and any other non-collection
or non-map field that has a lazy loading configuration). If you use fetch
groups or programmatically configure your fetch plan, OpenJPA will obey these
directives, but will be unable to lazily load any data that you exclude from
loading. As a result of these limitations, it is not recommended that you use
field access if you are not either running the enhancer or using OpenJPA with
a javaagent or in a Java 6 environment.
</p></li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_pc_interfaces"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;Managed Interfaces</h2></div></div></div>
<a class="indexterm" name="d5e12323"></a>
<p>
OpenJPA's managed interface feature allows you to define your object model
entirely in terms of interfaces, instead of concrete classes. To use this
feature, you must annotate your managed interfaces with the
<code class="classname">ManagedInterface</code> annotation, and use the
<code class="literal">OpenJPAEntityManager.createInstance(Class)</code> method to
create new records. Note that <code class="literal">createInstance()</code> returns
unmanaged instances; you must pass them to
<code class="literal">EntityManager.persist()</code> to store them in the database.
</p>
<pre class="programlisting">
@ManagedInterface
public interface PersonIface {
@Id @GeneratedValue
int getId();
void setId(int id);
// implicitly persistent per JPA property rules
String getName();
void setName(String name);
}
</pre>
<pre class="programlisting">
OpenJPAEntityManager em = ...;
PersonIface person = em.createInstance(PersonIface.class);
person.setName("Homer Simpson");
em.getTransaction().begin();
em.persist(person);
em.getTransaction().commit();
</pre>
</div>
<div class="section" id="ref_guide_pc_oid"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Object Identity
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_pc_oid_datastore">4.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_entitypk">4.2.
Entities as Identity Fields
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_application">4.3.
Application Identity Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_oid_pkgen_autoinc">4.4.
Autoassign / Identity Strategy Caveats
</a></span></dt></dl></div>
<a class="indexterm" name="d5e12335"></a>
<p>
OpenJPA makes several enhancements to JPA's standard entity identity.
</p>
<div class="section" id="ref_guide_pc_oid_datastore"><div class="titlepage"><div><div><h3 class="title">4.1.&nbsp;
Datastore Identity
</h3></div></div></div>
<a class="indexterm" name="d5e12340"></a>
<p>
The JPA specification requires you to declare one or more identity fields in
your persistent classes. OpenJPA fully supports this form of object identity,
called <span class="emphasis"><em>application</em></span> identity. OpenJPA, however, also
supports <span class="emphasis"><em>datastore</em></span> identity. In datastore identity, you do
not declare any primary key fields. OpenJPA manages the identity of your
persistent objects for you through a surrogate key in the database.
</p>
<p>
You can control how your JPA datastore identity value is generated through
OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/DataStoreId.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.DataStoreId</code></a> class
annotation. This annotation has <code class="literal">strategy</code> and <code class="literal">
generator</code> properties that mirror the same-named properties on the
standard <code class="classname">javax.persistence.GeneratedValue</code> annotation
described in <a class="xref" href="#jpa_overview_meta_id" title="2.3.&nbsp; Id">Section&nbsp;2.3, &#8220;
Id
&#8221;</a> of the JPA Overview.
</p>
<p>
To retrieve the identity value of a datastore identity entity, use the
<code class="methodname">OpenJPAEntityManager.getObjectId(Object entity)</code>
method. See <a class="xref" href="#ref_guide_runtime_em" title="2.2.&nbsp; OpenJPAEntityManager">Section&nbsp;2.2, &#8220;
OpenJPAEntityManager
&#8221;</a> for more information on
the <code class="classname">OpenJPAEntityManager</code>.
</p>
<div class="example" id="ref_guide_pc_oid_datastoreentityex"><p class="title"><b>Example&nbsp;5.4.&nbsp;
JPA Datastore Identity Metadata
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
@DataStoreId
public class LineItem {
... no @Id fields declared ...
}
</pre>
</div></div><br class="example-break">
<p>
Internally, OpenJPA uses the public
<a class="ulink" href="../../apidocs/org/apache/openjpa/util/Id.html" target="_top"><code class="classname">
org.apache.openjpa.util.Id</code></a> class for datastore identity
objects. When writing OpenJPA plugins, you can manipulate datastore identity
objects by casting them to this class. You can also create your own <code class="classname">
Id</code> instances and pass them to any internal OpenJPA method that
expects an identity object.
</p>
<p>
In JPA, you will never see <code class="classname">Id</code> instances directly.
Instead, calling <code class="classname">OpenJPAEntityManager.getObjectId</code> on a
datastore identity object will return the <code class="classname">Long</code> surrogate
primary key value for that object. You can then use this value in calls to
<code class="classname">EntityManager.find</code> for subsequent lookups of the same
record.
</p>
</div>
<div class="section" id="ref_guide_pc_oid_entitypk"><div class="titlepage"><div><div><h3 class="title">4.2.&nbsp;
Entities as Identity Fields
</h3></div></div></div>
<a class="indexterm" name="d5e12371"></a>
<p>
OpenJPA allows <code class="literal">ManyToOne</code> and <code class="literal">OneToOne</code>
relations to be identity fields. To identify a relation field as an identity
field, simply annotate it with both the <code class="literal">@ManyToOne</code> or
<code class="literal">@OneToOne</code> relation annotation and the <code class="literal">@Id</code>
identity annotation.
</p>
<p>
When finding an entity identified by a relation, pass the id of the
<span class="emphasis"><em>relation</em></span> to the <code class="methodname">EntityManager.find</code>
method:
</p>
<div class="example" id="ref_guide_pc_oid_entitypk_simplefind"><p class="title"><b>Example&nbsp;5.5.&nbsp;
Finding an Entity with an Entity Identity Field
</b></p><div class="example-contents">
<pre class="programlisting">
public Delivery createDelivery(Order order) {
Delivery delivery = new Delivery();
delivery.setId(order);
delivery.setDelivered(new Date());
return delivery;
}
public Delivery findDelivery(EntityManager em, Order order) {
// use the identity of the related instance
return em.find(Delivery.class, order.getId());
}
</pre>
</div></div><br class="example-break">
<p>
When your entity has multiple identity fields, at least one of which is a
relation to another entity, you can use an identity class (see
<a class="xref" href="#jpa_overview_pc_identitycls" title="2.1.&nbsp; Identity Class">Section&nbsp;2.1, &#8220;
Identity Class
&#8221;</a> in the JPA Overview), or
an embedded identity object. Identity class fields corresponding to
entity identity fields should be of the same type as the related entity's
identity. If an embedded identity object is used, you must annotate the
relation field with both the <code class="literal">@ManyToOne</code> or
<code class="literal">@OneToOne</code> relation annotation and the
<code class="literal">@MapsId</code> annotation.
</p>
<div class="example" id="ref_guide_pc_oid_entitypk_idcls"><p class="title"><b>Example&nbsp;5.6.&nbsp;
Id Class for Entity Identity Fields
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
public class Order {
@Id
private long id;
...
}
/**
* LineItem uses a compound primary key. Part of the compound key
* LineItemId is relation or reference to Order instance.
**/
@Entity
@IdClass(LineItemId.class)
public class LineItem {
@Id
private int index;
@Id
@ManyToOne
private Order order;
...
}
public class LineItemId {
public int index;
public long order; // same type as identity of Order i.e Order.id
// also the variable name must match the name of the
// variable in LineItem that refers to Order.
}
</pre>
</div></div><br class="example-break">
<p>
In the example above, if <code class="classname">Order</code> had used an identity
class <code class="classname">OrderId</code> in place of a simple <code class="classname">long
</code> value, then the <code class="literal">LineItemId.order</code> field would
have been of type <code class="classname">OrderId</code>.
</p>
<div class="example" id="ref_guide_pc_oid_entitypk_embeded_id"><p class="title"><b>Example&nbsp;5.7.&nbsp;
Embedded Id for Entity Identity Fields
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
public class Order {
@Id
private long id;
...
}
/**
* LineItem uses a compound primary key. Part of the compound key
* LineItemId is relation or reference to Order instance.
**/
@Entity
public class LineItem {
@EmbeddedId LineItemId id;
@ManyToOne
@MapsId("orderId") // The value element of the MapsId annotation
// must be used to specify the name of the primary
// key attribute to which the relationship
// corresponds. If the primary key referenced by
// the relationship attribute is of the same Java
// type as the dependent's primary key, then the
// value element is not specified.
private Order order;
...
}
@Embeddable
public class LineItemId {
public int index;
public long orderId;
}
</pre>
</div></div><br class="example-break">
<p>
In the example above, the <code class="classname">LineItem</code> uses an embedded id to
represent its primary key. The primary key attribute corresponding to the
relationship in the <code class="classname">LineItemId</code> must be of the same
type as the primary key of the <code class="classname">Order</code>. The
<code class="literal">MapsId</code> annotation must be applied to the relationship
field <code class="literal">LineItem.order</code>.
</p>
</div>
<div class="section" id="ref_guide_pc_oid_application"><div class="titlepage"><div><div><h3 class="title">4.3.&nbsp;
Application Identity Tool
</h3></div></div></div>
<a class="indexterm" name="d5e12412"></a>
<a class="indexterm" name="d5e12416"></a>
<p>
If you choose to use application identity, you may want to take advantage of
OpenJPA's application identity tool. The application
identity tool generates Java code implementing the identity class for any
persistent type using application identity. The code satisfies all the
requirements the specification places on identity classes. You can use it as-is,
or simply use it as a starting point, editing it to meet your needs.
</p>
<p>
Before you can run the application identity tool on a persistent class, the
class must be compiled and must have complete metadata. All primary key fields
must be marked as such in the metadata.
</p>
<p>
In JPA metadata, do not attempt to specify the <code class="literal">@IdClass</code>
annotation unless you are using the application identity tool to overwrite an
existing identity class. Attempting to set the value of the <code class="literal">@IdClass
</code> to a non-existent class will prevent your persistent class from
compiling. Instead, use the <code class="literal">-name</code> or <code class="literal">-suffix
</code> options described below to tell OpenJPA what name to give your
generated identity class. Once the application identity tool has generated the
class code, you can set the <code class="literal">@IdClass</code> annotation.
</p>
<p>
The application identity tool can be invoked via its Java class,
<a class="ulink" href="../../apidocs/org/apache/openjpa/enhance/ApplicationIdTool" target="_top">
<code class="classname">org.apache.openjpa.enhance.ApplicationIdTool</code></a>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
<a class="xref" href="#ref_guide_integration_appidtool" title="1.3.&nbsp; Application Identity Tool Ant Task">Section&nbsp;1.3, &#8220;
Application Identity Tool Ant Task
&#8221;</a> describes the
application identity tool's Ant task.
</p>
</div>
<div class="example" id="ref_guide_pc_appid_appidtool"><p class="title"><b>Example&nbsp;5.8.&nbsp;
Using the Application Identity Tool
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.enhance.ApplicationIdTool -s Id Magazine.java
</pre>
</div></div><br class="example-break">
<p>
The application identity tool accepts the standard set of command-line arguments
defined by the configuration framework (see
<a class="xref" href="#ref_guide_conf_devtools" title="3.&nbsp; Command Line Configuration">Section&nbsp;3, &#8220;
Command Line Configuration
&#8221;</a>), including code formatting
flags described in <a class="xref" href="#ref_guide_conf_devtools_format" title="3.1.&nbsp; Code Formatting">Section&nbsp;3.1, &#8220;
Code Formatting
&#8221;</a>. It
also accepts the following arguments:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-directory/-d &lt;output directory&gt;</code>: Path to the output
directory. If the directory does not match the generated oid class' package, the
package structure will be created beneath the directory. If not specified, the
tool will first try to find the directory of the <code class="filename">.java</code> file
for the persistence-capable class, and failing that will use the current
directory.
</p>
</li><li class="listitem">
<p>
<code class="literal">-ignoreErrors/-i &lt;true/t | false/f&gt;</code>: If <code class="literal">false
</code>, an exception will be thrown if the tool is run on any class that
does not use application identity, or is not the base class in the inheritance
hierarchy (recall that subclasses never define the application identity class;
they inherit it from their persistent superclass).
</p>
</li><li class="listitem">
<p>
<code class="literal">-token/-t &lt;token&gt;</code>: The token to use to separate
stringified primary key values in the string form of the object id. This option
is only used if you have multiple primary key fields. It defaults to "::".
</p>
</li><li class="listitem">
<p>
<code class="literal">-name/-n &lt;id class name&gt;</code>: The name of the identity
class to generate. If this option is specified, you must run the tool on exactly
one class. If the class metadata already names an object id class, this option
is ignored. If the name is not fully qualified, the persistent class' package is
prepended to form the qualified name.
</p>
</li><li class="listitem">
<p>
<code class="literal">-suffix/-s &lt;id class suffix&gt;</code>: A string to suffix each
persistent class name with to form the identity class name. This option is
overridden by <code class="literal">-name</code> or by any object id class specified in
metadata.
</p>
</li></ul></div>
<p>
Each additional argument to the tool must be one of the following:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The full name of a persistent class.
</p>
</li><li class="listitem">
<p>
The .java file for a persistent class.
</p>
</li><li class="listitem">
<p>
The <code class="filename">.class</code> file of a persistent class.
</p>
</li></ul></div>
<p>
If you do not supply any arguments to the tool, it will act on the classes in
your persistent classes list (see <a class="xref" href="#ref_guide_pc_pcclasses" title="1.&nbsp; Persistent Class List">Section&nbsp;1, &#8220;
Persistent Class List
&#8221;</a>).
</p>
</div>
<div class="section" id="ref_guide_pc_oid_pkgen_autoinc"><div class="titlepage"><div><div><h3 class="title">4.4.&nbsp;
Autoassign / Identity Strategy Caveats
</h3></div></div></div>
<a class="indexterm" name="d5e12470"></a>
<a class="indexterm" name="d5e12473"></a>
<a class="indexterm" name="d5e12476"></a>
<p>
<a class="xref" href="#jpa_overview_meta_gen" title="2.4.&nbsp; Generated Value">Section&nbsp;2.4, &#8220;
Generated Value
&#8221;</a> explains how to use JPA's
<code class="literal">IDENTITY</code> generation type to automatically assign field
values. However, here are some additional caveats you should be aware of when
using <code class="literal">IDENTITY</code> generation:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
Your database must support auto-increment / identity columns, or some equivalent
(see <a class="xref" href="#ref_guide_dbsetup_dbsupport_oracle" title="4.4.&nbsp; OracleDictionary Properties">Section&nbsp;4.4, &#8220;
OracleDictionary Properties
&#8221;</a> for how to
configure a combination of triggers and sequences to fake auto-increment support
in Oracle database).
</p>
</li><li class="listitem">
<p>
Auto-increment / identity columns must be an integer or long integer type.
</p>
</li><li class="listitem">
<p>
Databases support auto-increment / identity columns to varying degrees. Some do
not support them at all. Others only allow a single such column per table, and
require that it be the primary key column. More lenient databases may allow
non-primary key auto-increment columns, and may allow more than one per table.
See your database documentation for details.
</p>
</li></ol></div>
</div>
</div>
<div class="section" id="ref_guide_inverses"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Managed Inverses
</h2></div></div></div>
<a class="indexterm" name="d5e12493"></a>
<p>
Bidirectional relations are an essential part of data modeling.
<a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a> in the JPA Overview explains how to
use the <code class="literal">mappedBy</code> annotation attribute to form bidirectional
relations that also share datastore storage in JPA.
</p>
<p>
OpenJPA also allows you to define purely logical bidirectional relations. The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/InverseLogical.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.InverseLogical</code></a>
annotation names a logical inverse in JPA metadata.
</p>
<div class="example" id="ref_guide_inverses_logicalex"><p class="title"><b>Example&nbsp;5.9.&nbsp;
Specifying Logical Inverses
</b></p><div class="example-contents">
<p>
<code class="literal">Magazine.coverPhoto</code> and <code class="literal">Photograph.mag</code> are
each mapped to different foreign keys in their respective tables, but form a
logical bidirectional relation. Only one of the fields needs to declare the
other as its logical inverse, though it is not an error to set the logical
inverse of both fields.
</p>
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
public class Magazine {
@OneToOne
private Photograph coverPhoto;
...
}
@Entity
public class Photograph {
@OneToOne
@InverseLogical("coverPhoto")
private Magazine mag;
...
}
</pre>
</div></div><br class="example-break">
<p>
Java does not provide any native facilities to ensure that both sides of a
bidirectional relation remain consistent. Whenever you set one side of the
relation, you must manually set the other side as well.
</p>
<p>
By default, OpenJPA behaves the same way. OpenJPA does not automatically
propagate changes from one field in bidirectional relation to the other field.
This is in keeping with the philosophy of transparency, and also provides higher
performance, as OpenJPA does not need to analyze your object graph to correct
inconsistent relations.
</p>
<p>
<a class="indexterm" name="d5e12511"></a>
If convenience is more important to you than strict transparency, however, you
can enable inverse relation management in OpenJPA. Set the
<a class="link" href="#openjpa.InverseManager" title="5.41.&nbsp; openjpa.InverseManager"><code class="classname">openjpa.InverseManager
</code></a> plugin property to <code class="literal">true</code> for standard
management. Under this setting, OpenJPA detects changes to either side of a
bidirectional relation (logical or physical), and automatically sets the other
side appropriately on flush.
</p>
<div class="example" id="ref_guide_inversesex"><p class="title"><b>Example&nbsp;5.10.&nbsp;
Enabling Managed Inverses
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.InverseManager" value="true"/&gt;
</pre>
</div></div><br class="example-break">
<p>
The inverse manager has options to log a warning or throw an exception when it
detects an inconsistent bidirectional relation, rather than correcting it. To
use these modes, set the manager's <code class="literal">Action</code> property to
<code class="literal">warn</code> or <code class="literal">exception</code>, respectively.
</p>
<p>
By default, OpenJPA excludes <a class="link" href="#ref_guide_pc_scos_proxy_lrs" title="6.4.2.&nbsp; Large Result Set Proxies"> large
result set fields</a> from management. You can force large result set fields
to be included by setting the <code class="literal">ManageLRS</code> plugin property to
<code class="literal">true</code>.
</p>
<div class="example" id="ref_guide_inverses_logex"><p class="title"><b>Example&nbsp;5.11.&nbsp;
Log Inconsistencies
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.InverseManager" value="true(Action=warn)"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_pc_scos"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
Persistent Fields
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_pc_scos_restore">6.1.
Restoring State
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_order">6.2.
Typing and Ordering
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_calendar_timezone">6.3.
Calendar Fields and TimeZones
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy">6.4.
Proxies
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_smart">6.4.1.
Smart Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_lrs">6.4.2.
Large Result Set Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_custom">6.4.3.
Custom Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_serial">6.4.4.
Serialization
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_extern">6.5.
Externalization
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_extern_values">6.5.1.
External Values
</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e12532"></a>
<p>
OpenJPA enhances the specification's support for persistent fields in many ways.
This section documents aspects of OpenJPA's persistent field handling that may
affect the way you design your persistent classes.
</p>
<div class="section" id="ref_guide_pc_scos_restore"><div class="titlepage"><div><div><h3 class="title">6.1.&nbsp;
Restoring State
</h3></div></div></div>
<a class="indexterm" name="d5e12537"></a>
<a class="indexterm" name="d5e12540"></a>
<p>
While the JPA specification says that you should not use rolled back objects,
such objects are perfectly valid in OpenJPA. You can control whether the
objects' managed state is rolled back to its pre-transaction values with the
<a class="link" href="#openjpa.RestoreState" title="5.62.&nbsp; openjpa.RestoreState"><code class="literal">openjpa.RestoreState</code>
</a> configuration property. <code class="literal">none</code> does not roll back state
(the object becomes hollow, and will re-load its state the next time it is
accessed), <code class="literal">immutable</code> restores immutable values (primitives,
primitive wrappers, strings) and clears mutable values so that they are reloaded
on next access, and <code class="literal">all</code> restores all managed values to their
pre-transaction state.
</p>
</div>
<div class="section" id="ref_guide_pc_scos_order"><div class="titlepage"><div><div><h3 class="title">6.2.&nbsp;
Typing and Ordering
</h3></div></div></div>
<a class="indexterm" name="d5e12550"></a>
<p>
When loading data into a field, OpenJPA examines the value you assign the field
in your declaration code or in your no-args constructor. If the field value's
type is more specific than the field's declared type, OpenJPA uses the value
type to hold the loaded data. OpenJPA also uses the comparator you've
initialized the field with, if any. Therefore, you can use custom comparators on
your persistent field simply by setting up the comparator and using it in your
field's initial value.
</p>
<div class="example" id="ref_guide_pc_scos_order_initialvals"><p class="title"><b>Example&nbsp;5.12.&nbsp;
Using Initial Field Values
</b></p><div class="example-contents">
<p>
Though the annotations are left out for simplicity, assume <code class="literal">
employeesBySal</code> and <code class="literal">departments</code> are persistent
fields in the class below.
</p>
<pre class="programlisting">
public class Company {
// OpenJPA will detect the custom comparator in the initial field value
// and use it whenever loading data from the database into this field
private Collection employeesBySal = new TreeSet(new SalaryComparator());
private Map departments;
public Company {
// or we can initialize fields in our no-args constructor; even though
// this field is declared type Map, OpenJPA will detect that it's
// actually a TreeMap and use natural ordering for loaded data
departments = new TreeMap();
}
// rest of class definition...
}
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_pc_calendar_timezone"><div class="titlepage"><div><div><h3 class="title">6.3.&nbsp;
Calendar Fields and TimeZones
</h3></div></div></div>
<a class="indexterm" name="d5e12562"></a>
<p>
OpenJPA's support for the <code class="classname">java.util.Calendar</code> type will
store only the <code class="classname">Date</code> part of the field, not the
<code class="classname">TimeZone</code> associated with the field. When loading the date
into the <code class="classname">Calendar</code> field, OpenJPA will use the <code class="classname">
TimeZone</code> that was used to initialize the field.
</p>
</div>
<div class="section" id="ref_guide_pc_scos_proxy"><div class="titlepage"><div><div><h3 class="title">6.4.&nbsp;
Proxies
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_smart">6.4.1.
Smart Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_lrs">6.4.2.
Large Result Set Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_custom">6.4.3.
Custom Proxies
</a></span></dt><dt><span class="section"><a href="#ref_guide_pc_scos_proxy_serial">6.4.4.
Serialization
</a></span></dt></dl></div>
<a class="indexterm" name="d5e12573"></a>
<a class="indexterm" name="d5e12575"></a>
<p>
At runtime, the values of all mutable second class object fields in persistent
and transactional objects are replaced with implementation-specific proxies. On
modification, these proxies notify their owning instance that they have been
changed, so that the appropriate updates can be made on the datastore.
</p>
<div class="section" id="ref_guide_pc_scos_proxy_smart"><div class="titlepage"><div><div><h4 class="title">6.4.1.&nbsp;
Smart Proxies
</h4></div></div></div>
<a class="indexterm" name="d5e12582"></a>
<p>
Most proxies only track whether or not they have been modified. Smart proxies
for collection and map fields, however, keep a record of which elements have
been added, removed, and changed. This record enables the OpenJPA runtime to
make more efficient database updates on these fields.
</p>
<p>
When designing your persistent classes, keep in mind that you can optimize for
OpenJPA smart proxies by using fields of type <code class="classname">java.util.Set
</code>, <code class="classname">java.util.TreeSet</code>, and <code class="classname">
java.util.HashSet</code> for your collections whenever possible. Smart
proxies for these types are more efficient than proxies for <code class="classname">
List</code>s. You can also design your own smart proxies to further
optimize OpenJPA for your usage patterns. See the section on
<a class="link" href="#ref_guide_pc_scos_proxy_custom" title="6.4.3.&nbsp; Custom Proxies">custom proxies</a> for
details.
</p>
</div>
<div class="section" id="ref_guide_pc_scos_proxy_lrs"><div class="titlepage"><div><div><h4 class="title">6.4.2.&nbsp;
Large Result Set Proxies
</h4></div></div></div>
<a class="indexterm" name="d5e12594"></a>
<a class="indexterm" name="d5e12597"></a>
<p>
Under standard ORM behavior, traversing a persistent collection or map field
brings the entire contents of that field into memory. Some persistent fields,
however, might represent huge amounts of data, to the point that attempting to
fully instantiate them can overwhelm the JVM or seriously degrade performance.
</p>
<p>
OpenJPA uses special proxy types to represent these "large result set" fields.
OpenJPA's large result set proxies do not cache any data in memory. Instead,
each operation on the proxy offloads the work to the database and returns the
proper result. For example, the <code class="methodname">contains</code> method of a
large result set collection will perform a <code class="literal"> SELECT COUNT(*)</code>
query with the proper <code class="literal">WHERE</code> conditions to find out if the
given element exists in the database's record of the collection. Similarly, each
time you obtain an iterator OpenJPA performs the proper query using the current
<a class="link" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">large result set settings</a>, as
discussed in the <a class="link" href="#ref_guide_dbsetup" title="Chapter&nbsp;4.&nbsp; JDBC">JDBC</a> chapter. As you
invoke <code class="methodname">Iterator.next</code>, OpenJPA instantiates the result
objects on-demand.
</p>
<p>
You can free the resources used by a large result set iterator by passing it to
the static <a class="link" href="#ref_guide_runtime_openjpapersistence" title="2.9.&nbsp; OpenJPAPersistence"><code class="methodname">
OpenJPAPersistence.close</code></a> method.
</p>
<div class="example" id="ref_guide_pc_scos_proxy_lrs_itr"><p class="title"><b>Example&nbsp;5.13.&nbsp;
Using a Large Result Set Iterator
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
Collection employees = company.getEmployees(); // employees is a lrs collection
Iterator itr = employees.iterator();
while (itr.hasNext())
process((Employee) itr.next());
OpenJPAPersistence.close(itr);
</pre>
</div></div><br class="example-break">
<p>
You can also add and remove from large result set proxies, just as with standard
fields. OpenJPA keeps a record of all changes to the elements of the proxy,
which it uses to make sure the proper results are always returned from
collection and map methods, and to update the field's database record on commit.
</p>
<p>
In order to use large result set proxies in JPA, add the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/LRS.html" target="_top"><code class="classname">
org.apache.openjpa.persistence.LRS</code></a> annotation to the
persistent field.
</p>
<p>
The following restrictions apply to large result set fields:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The field must be declared as either a <code class="classname">java.util.Collection
</code> or <code class="classname">java.util.Map</code>. It cannot be declared as
any other type, including any sub-interface of collection or map, or any
concrete collection or map class.
</p>
</li><li class="listitem">
<p>
The field cannot have an externalizer (see
<a class="xref" href="#ref_guide_pc_extern" title="6.5.&nbsp; Externalization">Section&nbsp;6.5, &#8220;
Externalization
&#8221;</a>).
</p>
</li><li class="listitem">
<p>
Because they rely on their owning object for context, large result set proxies
cannot be transferred from one persistent field to another. The following code
would result in an error on commit:
</p>
<pre class="programlisting">
Collection employees = company.getEmployees() // employees is a lrs collection
company.setEmployees(null);
anotherCompany.setEmployees(employees);
</pre>
</li></ul></div>
<div class="example" id="ref_guide_pc_scos_proxy_lrs_extension"><p class="title"><b>Example&nbsp;5.14.&nbsp;
Marking a Large Result Set Field
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
public class Company {
@ManyToMany
@LRS private Collection&lt;Employee&gt; employees;
...
}
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_pc_scos_proxy_custom"><div class="titlepage"><div><div><h4 class="title">6.4.3.&nbsp;
Custom Proxies
</h4></div></div></div>
<a class="indexterm" name="d5e12635"></a>
<a class="indexterm" name="d5e12638"></a>
<p>
OpenJPA manages proxies through the
<a class="ulink" href="../../apidocs/org/apache/openjpa/util/ProxyManager.html" target="_top"><code class="classname">
org.apache.openjpa.util.ProxyManager</code></a> interface. OpenJPA
includes a default proxy manager, the <code class="classname">
org.apache.openjpa.util.ProxyManagerImpl</code> (with a plugin alias name
of <code class="literal">default</code>), that will meet the needs of most users. The
default proxy manager understands the following configuration properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">TrackChanges</code>: Whether to use
<a class="link" href="#ref_guide_pc_scos_proxy_smart" title="6.4.1.&nbsp; Smart Proxies">smart proxies</a>. Defaults to
<code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">AssertAllowedType</code>: Whether to immediately throw an exception
if you attempt to add an element to a collection or map that is not assignable
to the element type declared in metadata. Defaults to <code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">DelayCollectionLoading</code>: Whether to delay loading elements of a
lazily loaded collection. Delay loading allows non-indexed add and remove
operations to occur without prior loading of the collection from the data store. This can
improve performance of some applications by allowing them to perform simple add or remove
operations on collections without requiring them to be loaded. Delayed proxies are
loaded when an operation is performed that requires loading, such
as iteration, size, serialization, and indexOf. They can also be loaded by casting the
proxy to a <a class="ulink" href="../../apidocs/org/apache/openjpa/util/DelayedProxy.html" target="_top"><code class="classname">
org.apache.openjpa.util.DelayedProxy</code></a> and invoking the
<code class="methodname">load</code> method. If a broker factory is available after detaching the owning
entity, a collection may be available for delayed loading after the persistence context has been
cleared. In post-detachment, entities that are loaded are not associated with a persistence context.
Defaults to <code class="literal">false</code>.
</p>
</li></ul></div>
<p>
The default proxy manager can proxy the standard methods of any
<code class="classname">Collection</code>, <code class="classname">List</code>,
<code class="classname">Map</code>, <code class="classname">Queue</code>,
<code class="classname">Date</code>, or <code class="classname">Calendar</code> class,
including custom implementations. It can also proxy custom classes whose
accessor and mutator methods follow JavaBean naming conventions. Your custom
types must, however, meet the following criteria:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Custom container types must have a public no-arg constructor or a public
constructor that takes a single <code class="classname">Comparator</code> parameter.
</p>
</li><li class="listitem">
<p>
Custom date types must have a public no-arg constructor or a public
constructor that takes a single <code class="classname">long</code> parameter
representing the current time.
</p>
</li><li class="listitem">
<p>
Other custom types must have a public no-arg constructor or a public copy
constructor. If a custom types does not have a copy constructor, it must be
possible to fully copy an instance A by creating a new instance B and calling
each of B's setters with the value from the corresponding getter on A.
</p>
</li></ul></div>
<p>
If you have custom classes that must be proxied and do not meet these
requirements, OpenJPA allows you to define your own proxy classes and
your own proxy manager. See the <code class="literal">openjpa.util</code> package
<a class="ulink" href="../../apidocs/" target="_top">Javadoc</a> for details on the interfaces involved,
and the utility classes OpenJPA provides to assist you.
</p>
<p>
You can plug your custom proxy manager into the OpenJPA runtime through the
<a class="link" href="#openjpa.ProxyManager" title="5.56.&nbsp; openjpa.ProxyManager"><code class="literal"> openjpa.ProxyManager</code>
</a> configuration property.
</p>
<div class="example" id="ref_guide_pc_scos_proxy_custom_ex"><p class="title"><b>Example&nbsp;5.15.&nbsp;
Configuring the Proxy Manager
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.ProxyManager" value="TrackChanges=false"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_pc_scos_proxy_serial"><div class="titlepage"><div><div><h4 class="title">6.4.4.&nbsp;
Serialization
</h4></div></div></div>
<a class="indexterm" name="d5e12690"></a>
<a class="indexterm" name="d5e12693"></a>
<p>
When objects are serialized, the <code class="literal">DetachedStateField</code> in
section <a class="xref" href="#ref_guide_detach_state" title="1.3.1.&nbsp; Detached State">Section&nbsp;1.3.1, &#8220;
Detached State
&#8221;</a>
will be used to help determine when build time proxies will be removed.
If runtime created proxies are being used (proxies not supplied by OpenJPA)
or if an entity has already been detached, then any found proxies will be
removed during serialization.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">transient</code>: Use a transient detached state field. This gives
the benefits of a detached state field to local objects that are never
serialized, but retains serialization compatibility for client tiers without
access to the enhanced versions of your classes or the OpenJPA runtime.
All proxies will be removed during serialization. This is the default.
</p>
</li><li class="listitem">
<p>
<code class="literal">true</code>: Use a non-transient detached state field so that
objects crossing serialization barriers can still be attached efficiently. This
requires, however, that your client tier have the enhanced versions of your
classes and the OpenJPA runtime.
No OpenJPA provided proxies will be removed during serialization.
</p>
</li><li class="listitem">
<p>
<code class="literal">false</code>: Do not use a detached state field.
All proxies will be removed during serialization.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_pc_extern"><div class="titlepage"><div><div><h3 class="title">6.5.&nbsp;
Externalization
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_pc_extern_values">6.5.1.
External Values
</a></span></dt></dl></div>
<a class="indexterm" name="d5e12711"></a>
<a class="indexterm" name="d5e12713"></a>
<p>
OpenJPA offers the ability to write
<a class="link" href="#ref_guide_mapping_custom_field" title="10.3.&nbsp; Custom Field Mapping">custom field mappings</a> in
order to have complete control over the mechanism with which fields are stored,
queried, and loaded from the datastore. Often, however, a custom mapping is
overkill. There is often a simple transformation from a Java field value to its
database representation. Thus, OpenJPA provides the externalization service.
Externalization allows you to specify methods that will externalize a field
value to its database equivalent on store and then rebuild the value from its
externalized form on load.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Fields of embeddable classes used for <code class="literal">@EmbeddedId</code> values in
JPA cannot have externalizers.
</p>
</div>
<p>
The OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Externalizer.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.Externalizer</code></a>
annotation sets the name of a method that will be invoked to convert
the field into its external form for database storage. You can specify either
the name of a non-static method, which will be invoked on the field value, or a
static method, which will be invoked with the field value as a parameter. Each
method can also take an optional
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/StoreContext.html" target="_top"><code class="classname">
StoreContext</code></a> parameter for access to a persistence context.
The return value of the method is the field's external form. By default, OpenJPA
assumes that all named methods belong to the field value's class (or its
superclasses). You can, however, specify static methods of other classes using
the format <code class="literal">&lt;class-name&gt;.&lt;method-name&gt;</code>.
</p>
<p>
Given a field of type <code class="classname">CustomType</code> that externalizes to a
string, the table below demonstrates several possible externalizer methods and
their corresponding metadata extensions.
</p>
<div class="table" id="d5e12730"><p class="title"><b>Table&nbsp;5.1.&nbsp;
Externalizer Options
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Externalizer Options&#xA; " border="1"><colgroup><col align="left" class="method"><col align="left" class="extension"></colgroup><thead><tr><th align="left">
Method
</th><th align="left">
Extension
</th></tr></thead><tbody><tr><td align="left">
<code class="literal">
public String CustomType.toString()
</code>
</td><td align="left">
<code class="literal">
@Externalizer("toString")
</code>
</td></tr><tr><td align="left">
<code class="literal">
public String CustomType.toString(StoreContext ctx)
</code>
</td><td align="left">
<code class="literal">
@Externalizer("toString")
</code>
</td></tr><tr><td align="left">
<code class="literal">
public static String AnyClass.toString(CustomType ct)
</code>
</td><td align="left">
<code class="literal">
@Externalizer("AnyClass.toString")
</code>
</td></tr><tr><td align="left">
<code class="literal">
public static String AnyClass.toString(CustomType ct, StoreContext ctx)
</code>
</td><td align="left">
<code class="literal">
@Externalizer("AnyClass.toString")
</code>
</td></tr></tbody></table>
</div></div><br class="table-break">
<p>
The OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Factory.html" target="_top"><code class="classname">
org.apache.openjpa.persistence.Factory</code></a> annotation
contains the name of a method that will be invoked to instantiate the field from
the external form stored in the database. Specify a static method name. The
method will be invoked with the externalized value and must return an
instance of the field type. The method can also take an optional
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/StoreContext.html" target="_top"><code class="classname">
StoreContext</code></a> parameter for access to a persistence context.
If a factory is not specified, OpenJPA will use the constructor of the field
type that takes a single argument of the external type, or will throw an
exception if no constructor with that signature exists.
</p>
<p>
Given a field of type <code class="classname">CustomType</code> that externalizes to a
string, the table below demonstrates several possible factory methods and their
corresponding metadata extensions.
</p>
<div class="table" id="d5e12767"><p class="title"><b>Table&nbsp;5.2.&nbsp;
Factory Options
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Factory Options&#xA; " border="1"><colgroup><col align="left" class="method"><col align="left" class="extension"></colgroup><thead><tr><th align="left">
Method
</th><th align="left">
Extension
</th></tr></thead><tbody><tr><td align="left">
<code class="literal">
public CustomType(String str)
</code>
</td><td align="left">
none
</td></tr><tr><td align="left">
<code class="literal">
public static CustomType CustomType.fromString(String str)
</code>
</td><td align="left">
<code class="literal">
@Factory("fromString")
</code>
</td></tr><tr><td align="left">
<code class="literal">
public static CustomType CustomType.fromString(String str, StoreContext ctx)
</code>
</td><td align="left">
<code class="literal">
@Factory("fromString")
</code>
</td></tr><tr><td align="left">
<code class="literal">
public static CustomType AnyClass.fromString(String str)
</code>
</td><td align="left">
<code class="literal">
@Factory("AnyClass.fromString")
</code>
</td></tr><tr><td align="left">
<code class="literal">
public static CustomType AnyClass.fromString(String str, StoreContext ctx)
</code>
</td><td align="left">
<code class="literal">
@Factory("AnyClass.fromString")
</code>
</td></tr></tbody></table>
</div></div><br class="table-break">
<p>
If your externalized field is not a standard persistent type, you must
explicitly mark it persistent. In OpenJPA, you can force a persistent field
by annotating it with <a class="link" href="#ref_guide_meta_jpa_persistent" title="3.3.&nbsp; Persistent Field Values"><code class="classname">
org.apache.openjpa.persistence.Persistent</code></a> annotation.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
If your custom field type is mutable and is not a standard collection, map, or
date class, OpenJPA will not be able to detect changes to the field. You must
mark the field dirty manually, or create a custom field proxy.
See
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="methodname">OpenJPAEntityManager.dirty</code></a> for how to mark a
field dirty manually in JPA.
See <a class="xref" href="#ref_guide_pc_scos_proxy" title="6.4.&nbsp; Proxies">Section&nbsp;6.4, &#8220;
Proxies
&#8221;</a> for a discussion of proxies.
</p>
</div>
<p>
You can externalize a field to virtually any value that is supported by
OpenJPA's field mappings (embedded relations are the exception; you must declare
your field to be a persistence-capable type in order to embed it). This means
that a field can externalize to something as simple as a primitive, something as
complex as a collection or map of entities, or anything in
between. If you do choose to externalize to a collection or map, OpenJPA
recognizes a family of metadata extensions for specifying type information for the
externalized form of your fields - see <a class="xref" href="#type" title="4.2.6.&nbsp; Type">Section&nbsp;4.2.6, &#8220;
Type
&#8221;</a>. If the
external form of your field is an entity object or contains entities, OpenJPA
will correctly include the objects in its persistence-by-reachability
algorithms and its delete-dependent algorithms.
</p>
<p>
The example below demonstrates a few forms of externalization.
</p>
<div class="example" id="ref_guide_pc_externex"><p class="title"><b>Example&nbsp;5.16.&nbsp;
Using Externalization
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
public class Magazine {
// use Class.getName and Class.forName to go to/from strings
@Persistent
@Externalizer("getName")
@Factory("forName")
private Class cls;
// use URL.getExternalForm for externalization. no factory;
// we can rely on the URL string constructor
@Persistent
@Externalizer("toExternalForm")
private URL url;
// use our custom methods
@Persistent
@Externalizer("Magazine.authorsFromCustomType")
@Factory("Magazine.authorsToCustomType")
@ElementType(Author.class)
private CustomType customType;
public static Collection authorsFromCustomType(CustomType customType) {
... logic to pack custom type into a list of authors ...
}
public static CustomType authorsToCustomType(Collection authors) {
... logic to create custom type from a collection of authors ...
}
...
}
</pre>
</div></div><br class="example-break">
<p>
<a class="indexterm" name="d5e12816"></a>
You can query externalized fields using parameters. Pass in a value of the field
type when executing the query. OpenJPA will externalize the parameter using the
externalizer method named in your metadata, and compare the externalized
parameter with the value stored in the database. As a shortcut, OpenJPA also
allows you to use parameters or literals of the field's externalized type in
queries, as demonstrated in the example below.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Currently, queries are limited to fields that externalize to a primitive,
primitive wrapper, string, or date types, due to constraints on query syntax.
</p>
</div>
<div class="example" id="ref_guide_pc_extern_queryex"><p class="title"><b>Example&nbsp;5.17.&nbsp;
Querying Externalization Fields
</b></p><div class="example-contents">
<p>
Assume the <code class="classname">Magazine</code> class has the same fields as in the
previous example.
</p>
<pre class="programlisting">
// you can query using parameters
Query q = em.createQuery("select m from Magazine m where m.url = :u");
q.setParameter("u", new URL("http://www.solarmetric.com"));
List results = q.getResultList();
// or as a shortcut, you can use the externalized form directly
q = em.createQuery("select m from Magazine m where m.url = 'http://www.solarmetric.com'");
results = q.getResultList();
</pre>
</div></div><br class="example-break">
<div class="section" id="ref_guide_pc_extern_values"><div class="titlepage"><div><div><h4 class="title">6.5.1.&nbsp;
External Values
</h4></div></div></div>
<a class="indexterm" name="d5e12828"></a>
<p>
Externalization often takes simple constant values and transforms them to
constant values of a different type. An example would be storing a <code class="classname">
boolean</code> field as a <code class="classname">char</code>, where <code class="literal">true
</code> and <code class="literal">false</code> would be stored in the database as
<code class="literal">'T'</code> and <code class="literal">'F'</code> respectively.
</p>
<p>
OpenJPA allows you to define these simple translations in metadata, so that the
field behaves as in <a class="link" href="#ref_guide_pc_extern" title="6.5.&nbsp; Externalization">full-fledged
externalization</a> without requiring externalizer and factory methods.
External values supports translation of pre-defined simple types (primitives,
primitive wrappers, and Strings), to other pre-defined simple values.
</p>
<p>
Use the OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/ExternalValues.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.ExternalValues</code></a>
annotation to define external value translations. The values are
defined in a format similar to that of <a class="link" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">
configuration plugins</a>, except that the value pairs represent Java and
datastore values. To convert the Java boolean values of <code class="literal">true</code>
and <code class="literal">false</code> to the character values <code class="literal">T</code> and
<code class="literal">F</code>, for example, you would use the extension value: <code class="literal">
true=T,false=F</code>.
</p>
<p>
If the type of the datastore value is different from the field's type, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Type.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.Type</code></a> annotation
to define the datastore type.
</p>
<div class="example" id="externvalues_ex"><p class="title"><b>Example&nbsp;5.18.&nbsp;
Using External Values
</b></p><div class="example-contents">
<p>
This example uses external value translation to transform a string field to an
integer in the database.
</p>
<pre class="programlisting">
public class Magazine {
@ExternalValues({"SMALL=5", "MEDIUM=8", "LARGE=10"})
@Type(int.class)
private String sizeWidth;
...
}
</pre>
</div></div><br class="example-break">
</div>
</div>
</div>
<div class="section" id="ref_guide_fetch"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
Fetch Groups
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_fetch_custom">7.1.
Custom Fetch Groups
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_conf">7.2.
Custom Fetch Group Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_single_field">7.3.
Per-field Fetch Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_fetch_impl">7.4.
Implementation Notes
</a></span></dt></dl></div>
<a class="indexterm" name="d5e12858"></a>
<p>
Fetch groups are sets of fields that load together. They can be used to pool
together associated fields in order to provide performance improvements over
standard data fetching. Specifying fetch groups allows for tuning of lazy
loading and eager fetching behavior.
</p>
<p>
The JPA Overview's <a class="xref" href="#jpa_overview_meta_fetch" title="2.7.1.&nbsp; Fetch Type">Section&nbsp;2.7.1, &#8220;
Fetch Type
&#8221;</a> describes how
to use JPA metadata annotations to control whether a field is fetched eagerly or
lazily. Fetch groups add a dynamic aspect to this standard ability. As you will
see, OpenJPA's JPA extensions allow you can add and remove fetch groups at
runtime to vary the sets of fields that are eagerly loaded.
</p>
<div class="section" id="ref_guide_fetch_custom"><div class="titlepage"><div><div><h3 class="title">7.1.&nbsp;
Custom Fetch Groups
</h3></div></div></div>
<p>
OpenJPA places any field that is eagerly loaded according to the JPA metadata
rules into the built-in <span class="emphasis"><em>default</em></span> fetch group. As its name
implies, the default fetch group is active by default. You may also
define your own named fetch groups and activate or deactivate them at runtime,
as described later in this chapter. OpenJPA will eagerly-load the fields in all
active fetch groups when loading objects from the datastore.
</p>
<p>
You create fetch groups with the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/FetchGroup.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.FetchGroup</code></a>
annotation. If your class only has one custom fetch group, you can place this
annotation directly on the class declaration. Otherwise, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/FetchGroups.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.FetchGroups</code></a>
annotation to declare an array of individual <code class="classname">FetchGroup</code>
values. The <code class="classname">FetchGroup</code> annotation has the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the fetch group. Fetch group names
are global, and are expected to be shared among classes. For example, a shopping
website may use a <span class="emphasis"><em>detail</em></span> fetch group in each product class
to efficiently load all the data needed to display a product's "detail" page.
The website might also define a sparse <span class="emphasis"><em>list</em></span> fetch group
containing only the fields needed to display a table of products, as in a search
result.
</p>
<p>
The following names are reserved for use by OpenJPA: <code class="literal">default</code>
, <code class="literal">values</code>, <code class="literal">all</code>, <code class="literal">none</code>,
and any name beginning with <code class="literal">jdo</code>, <code class="literal">jpa</code>, or
<code class="literal">openjpa</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">FetchAttribute[] attributes</code>: The set of persistent fields or
properties in the fetch group.
</p>
</li><li class="listitem">
<p>
<code class="literal">String[] fetchGroups</code>: Other fetch groups whose fields to
include in this group.
</p>
</li></ul></div>
<p>
As you might expect, listing a
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/FetchAttribute.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.FetchAttribute</code></a>
within a <code class="classname">FetchGroup</code> includes the corresponding persistent
field or property in the fetch group. Each <code class="classname">FetchAttribute</code>
has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the persistent field or property to
include in the fetch group.
</p>
</li><li class="listitem">
<p>
<code class="literal">recursionDepth</code>: If the attribute represents a relation, the
maximum number of same-typed relations to eager-fetch from this field. Defaults
to 1. For example, consider an <code class="classname">Employee</code> class with a
<code class="literal">manager</code> field, also of type <code class="classname">Employee</code>.
When we load an <code class="classname">Employee</code> and the <code class="literal">
manager</code> field is in an active fetch group, the recursion depth (along
with the max fetch depth setting, described below) determines whether we only
retrieve the target <code class="classname">Employee</code> and his manager (depth 1),
or whether we also retrieve the manager's manager (depth 2), or the manager's
manager's manager (depth 3), etc. Use -1 for unlimited depth.
</p>
</li></ul></div>
<div class="example" id="ref_guide_fetch_customgroups"><p class="title"><b>Example&nbsp;5.19.&nbsp;
Custom Fetch Group Metadata
</b></p><div class="example-contents">
<p>
Creates a <span class="emphasis"><em>detail</em></span> fetch group consisting of the
<code class="literal">publisher</code> and <code class="literal">articles</code> relations.
</p>
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
@FetchGroups({
@FetchGroup(name="detail", attributes={
@FetchAttribute(name="publisher"),
@FetchAttribute(name="articles")
}),
...
})
public class Magazine {
...
}
</pre>
</div></div><br class="example-break">
<p>
A field can be a member of any number of fetch groups. A field can also
declare a <span class="emphasis"><em>load fetch group</em></span>.
When you access a lazy-loaded field for the first time, OpenJPA makes a
datastore trip to fetch that field's data. Sometimes, however, you know
that whenever you access a lazy field A, you're likely to access lazy fields B
and C as well. Therefore, it would be more efficient to fetch the data for A,
B, and C in the same datastore trip. By setting A's load fetch group to the
name of a <a class="link" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">fetch group</a> containing B and
C, you can tell OpenJPA to load all of these fields together when A is first
accessed.
</p>
<p>
Use OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/LoadFetchGroup.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.LoadFetchGroup</code></a>
annotation to specify the load fetch group of any persistent field. The value of
the annotation is the name of a declared fetch group whose members should be
loaded along with the annotated field.
</p>
<div class="example" id="ref_guide_fetch_loadgroup"><p class="title"><b>Example&nbsp;5.20.&nbsp;
Load Fetch Group Metadata
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
@FetchGroups({
@FetchGroup(name="detail", attributes={
@FetchAttribute(name="publisher"),
@FetchAttribute(name="articles")
}),
...
})
public class Magazine {
@ManyToOne(fetch=FetchType.LAZY)
@LoadFetchGroup("detail")
private Publisher publisher;
...
}
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_fetch_conf"><div class="titlepage"><div><div><h3 class="title">7.2.&nbsp;
Custom Fetch Group Configuration
</h3></div></div></div>
<a class="indexterm" name="d5e12930"></a>
<p>
<a class="indexterm" name="d5e12934"></a>
You can control the default set of fetch groups with the
<a class="link" href="#openjpa.FetchGroups" title="5.35.&nbsp; openjpa.FetchGroups"><code class="literal">openjpa.FetchGroups</code>
</a> configuration property. Set this property to a comma-separated list of
fetch group names.
</p>
<p>
You can also set the system's default maximum fetch depth with the
<a class="link" href="#openjpa.MaxFetchDepth" title="5.47.&nbsp; openjpa.MaxFetchDepth"><code class="literal">openjpa.MaxFetchDepth</code>
</a> configuration property. The maximum fetch depth determines how "deep"
into the object graph to traverse when loading an instance. For example, with
a <code class="literal">MaxFetchDepth</code> of 1, OpenJPA will load at most the target
instance and its immediate relations. With a <code class="literal">MaxFetchDepth</code>
of 2, OpenJPA may load the target instance, its immediate relations, and
the relations of those relations. This works to arbitrary depth. In fact,
the default <code class="literal">MaxFetchDepth</code> value is -1, which symbolizes
infinite depth. Under this setting, OpenJPA will fetch configured relations
until it reaches the edges of the object graph. Of course, which relation
fields are loaded depends on whether the fields are eager or lazy, and on the
active fetch groups. A fetch group member's recursion depth may also limit
the fetch depth to something less than the configured maximum.
</p>
<p>
OpenJPA's <code class="classname">OpenJPAEntityManager</code> and <code class="classname">
OpenJPAQuery</code> extensions to the standard <code class="classname">EntityManager
</code> and <code class="classname">Query</code> interfaces provide access to a
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/FetchPlan.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.FetchPlan</code></a> object.
The <code class="classname">FetchPlan</code> maintains the set of active fetch groups
and the maximum fetch depth. It begins with the groups and depth defined in the
<code class="literal">openjpa.FetchGroups</code> and <code class="literal">openjpa.MaxFetchDepth
</code> properties, but allows you to add or remove groups and change the
maximum fetch depth for an individual <code class="classname">EntityManager</code> or
<code class="classname">Query</code> through the methods below.
</p>
<pre class="programlisting">
public FetchPlan addFetchGroup(String group);
public FetchPlan addFetchGroups(String... groups);
public FetchPlan addFetchGroups(Collection groups);
public FetchPlan removeFetchGrop(String group);
public FetchPlan removeFetchGroups(String... groups);
public FetchPlan removeFetchGroups(Collection groups);
public FetchPlan resetFetchGroups();
public Collection&lt;String&gt; getFetchGroups();
public void clearFetchGroups();
public FetchPlan setMaxFetchDepth(int depth);
public int getMaxFetchDepth();
</pre>
<p>
<a class="xref" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">Chapter&nbsp;9, <i>
Runtime Extensions
</i></a> details the <code class="classname">
OpenJPAEntityManager</code>, <code class="classname">OpenJPAQuery</code>, and
<code class="classname">FetchPlan</code> interfaces.
</p>
<div class="example" id="ref_guide_fetch_conf_query"><p class="title"><b>Example&nbsp;5.21.&nbsp;
Using the FetchPlan
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAQuery kq = OpenJPAPersistence.cast(em.createQuery(...));
kq.getFetchPlan().setMaxFetchDepth(3).addFetchGroup("detail");
List results = kq.getResultList();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_fetch_single_field"><div class="titlepage"><div><div><h3 class="title">7.3.&nbsp;
Per-field Fetch Configuration
</h3></div></div></div>
<a class="indexterm" name="d5e12968"></a>
<p>
In addition to controlling fetch configuration on a per-fetch-group basis, you
can configure OpenJPA to include particular fields in the current fetch
plan. This allows you to add individual fields that are not in the
default fetch group or in any other active fetch groups to the set of
fields that will be eagerly loaded from the database.
</p>
<p>
OpenJPA <code class="classname">FetchPlan</code> methods:
</p>
<pre class="programlisting">
public FetchPlan addField(String field);
public FetchPlan addFields(String... fields);
public FetchPlan addFields(Class cls, String... fields);
public FetchPlan addFields(Collection fields);
public FetchPlan addFields(Class cls, Collection fields);
public FetchPlan removeField(String field);
public FetchPlan removeFields(String... fields);
public FetchPlan removeFields(Class cls, String... fields);
public FetchPlan removeFields(Collection fields);
public FetchPlan removeFields(Class cls, Collection fields);
public Collection&lt;String&gt; getFields();
public void clearFields();
</pre>
<p>
The methods that take only string arguments use the fully-qualified field name,
such as <code class="literal">org.mag.Magazine.publisher</code>. Similarly, <code class="methodname">
getFields</code> returns the set of fully-qualified field names. In all
methods, the named field must be defined in the class specified in the
invocation, not a superclass. So, if the field <code class="literal">publisher</code> is
defined in base class <code class="classname">Publication</code> rather than subclass
<code class="classname">Magazine</code>, you must invoke <code class="literal">addField
(Publication.class, "publisher")</code> and not <code class="literal">addField
(Magazine.class, "publisher")</code>. This is stricter than Java's default
field-masking algorithms, which would allow the latter method behavior if
<code class="literal">Magazine</code> did not also define a field called <code class="literal">
publisher</code>.
</p>
<p>
To include the fields defined in a super class by the subclass or to distinguish
between fields that are defined in <span class="emphasis"><em>both</em></span> super- and subclass,
set <code class="literal">setExtendedPathLookup(boolean)</code> on <code class="literal">FetchPlan
</code> to <code class="literal">true</code>. By default, this option is set to
<code class="literal">false</code>, to reduce more extensive lookups for predominant use
cases.
</p>
<p>
In order to avoid the cost of reflection, OpenJPA does not perform any
validation of the field name / class name pairs that you put into the fetch
configuration. If you specify non-existent class / field pairs, nothing adverse
will happen, but you will receive no notification of the fact that the specified
configuration is not being used.
</p>
<div class="example" id="ref_guide_fetch-conf_per_field"><p class="title"><b>Example&nbsp;5.22.&nbsp;
Adding an Eager Field
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManager kem = OpenJPAPersistence.cast(em);
kem.getFetchPlan().addField(Magazine.class, "publisher");
Magazine mag = em.find(Magazine.class, magId);
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_fetch_impl"><div class="titlepage"><div><div><h3 class="title">7.4.&nbsp;
Implementation Notes
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Even when a direct relation is not eagerly fetched, OpenJPA selects the foreign
key columns and caches the values. This way when you do traverse the relation,
OpenJPA can often find the related object in its cache, or at least avoid joins
when loading the related object from the database.
</p>
</li><li class="listitem">
<p>
The above implicit foreign key-selecting behavior does not always apply when the
relation is in a subclass table. If the subclass table would not otherwise be
joined into the select, OpenJPA avoids the extra join just to select the foreign
key values.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_perfpack_eager"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;
Eager Fetching
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_perfpack_eager_conf">8.1.
Configuring Eager Fetching
</a></span></dt><dt><span class="section"><a href="#ref_guide_perfpack_eager_consider">8.2.
Eager Fetching Considerations and Limitations
</a></span></dt></dl></div>
<a class="indexterm" name="d5e13004"></a>
<a class="indexterm" name="d5e13006"></a>
<a class="indexterm" name="d5e13009"></a>
<a class="indexterm" name="d5e13013"></a>
<p>
Eager fetching is the ability to efficiently load subclass data and related
objects along with the base instances being queried. Typically, OpenJPA has to
make a trip to the database whenever a relation is loaded, or when you first
access data that is mapped to a table other than the least-derived superclass
table. If you perform a query that returns 100 <code class="classname">Person</code>
objects, and then you have to retrieve the <code class="classname">Address</code> for
each person, OpenJPA may make as many as 101 queries (the initial query, plus
one for the address of each person returned). Or if some of the <code class="classname">
Person</code> instances turn out to be <code class="classname">Employee</code>s,
where <code class="classname">Employee</code> has additional data in its own joined
table, OpenJPA once again might need to make extra database trips to access the
additional employee data. With eager fetching, OpenJPA can reduce these cases to
a single query.
</p>
<p>
Eager fetching only affects relations in the active fetch groups, and is limited
by the declared maximum fetch depth and field recursion depth (see
<a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a>). In other words, relations that would
not normally be loaded immediately when retrieving an object or accessing a
field are not affected by eager fetching. In our example above, the address of
each person would only be eagerly fetched if the query were configured to
include the address field or its fetch group, or if the address were in the
default fetch group. This allows you to control exactly which fields are eagerly
fetched in different situations. Similarly, queries that exclude subclasses
aren't affected by eager subclass fetching, described below.
</p>
<p>
Eager fetching has three modes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">none</code>: No eager fetching is performed. Related objects are
always loaded in an independent select statement. No joined subclass data is
loaded unless it is in the table(s) for the base type being queried. Unjoined
subclass data is loaded using separate select statements rather than a SQL UNION
operation.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e13032"></a>
<code class="literal">join</code>: In this mode, OpenJPA joins to to-one relations in the
configured fetch groups. If OpenJPA is loading data for a single instance, then
OpenJPA will also join to any collection field in the configured fetch groups.
When loading data for multiple instances, though, (such as when executing a
<code class="classname">Query</code>) OpenJPA will not join to collections by default.
Instead, OpenJPA defaults to <code class="literal">parallel</code> mode for collections,
as described below. You can force OpenJPA use a join rather than parallel mode
for a collection field using the metadata extension described in
<a class="xref" href="#eager-fetch-mode" title="9.2.1.&nbsp; Eager Fetch Mode">Section&nbsp;9.2.1, &#8220;
Eager Fetch Mode
&#8221;</a>.
</p>
<p>
<a class="indexterm" name="d5e13040"></a>
Under <code class="literal">join</code> mode, OpenJPA uses a left outer join (or inner
join, if the relations' field metadata declares the relation non-nullable) to
select the related data along with the data for the target objects. This process
works recursively for to-one joins, so that if <code class="classname">Person</code> has
an <code class="classname">Address</code>, and <code class="classname">Address</code> has a
<code class="classname">TelephoneNumber</code>, and the fetch groups are configured
correctly, OpenJPA might issue a single select that joins across the tables for
all three classes. To-many joins can not recursively spawn other to-many joins,
but they can spawn recursive to-one joins.
</p>
<p>
Under the <code class="literal">join</code> subclass fetch mode, subclass data in joined
tables is selected by outer joining to all possible subclass tables of the type
being queried. As you'll see below, subclass data fetching is configured
separately from relation fetching, and can be disabled for specific classes.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Some databases may not support outer joins. Also, OpenJPA can not use
outer joins if you have set the <a class="link" href="#openjpa.jdbc.DBDictionary" title="6.2.&nbsp; openjpa.jdbc.DBDictionary">
<code class="literal"> DBDictionary</code></a>'s <code class="literal">JoinSyntax</code> to
<code class="literal">traditional</code>. See <a class="xref" href="#ref_guide_dbsetup_sql92" title="6.&nbsp; Setting the SQL Join Syntax">Section&nbsp;6, &#8220;
Setting the SQL Join Syntax
&#8221;</a>.
</p>
</div>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e13058"></a>
<code class="literal">parallel</code>: Under this mode, OpenJPA selects to-one relations
and joined collections as outlined in the <code class="literal">join</code> mode
description above. Unjoined collection fields, however, are eagerly fetched
using a separate select statement for each collection, executed in parallel with
the select statement for the target objects. The parallel selects use the
<code class="literal">WHERE</code> conditions from the primary select, but add their own
joins to reach the related data. Thus, if you perform a query that returns 100
<code class="classname">Company</code> objects, where each company has a list of
<code class="classname">Employee</code> objects and <code class="classname">Department</code>
objects, OpenJPA will make 3 queries. The first will select the company objects,
the second will select the employees for those companies, and the third will
select the departments for the same companies. Just as for joins, this process
can be recursively applied to the objects in the relations being eagerly
fetched. Continuing our example, if the <code class="classname">Employee</code> class
had a list of <code class="classname">Projects</code> in one of the fetch groups being
loaded, OpenJPA would execute a single additional select in parallel to load the
projects of all employees of the matching companies.
</p>
<p>
Using an additional select to load each collection avoids transferring more data
than necessary from the database to the application. If eager joins were used
instead of parallel select statements, each collection added to the configured
fetch groups would cause the amount of data being transferred to rise
dangerously, to the point that you could easily overwhelm the network.
</p>
<p>
Polymorphic to-one relations to table-per-class mappings use parallel eager
fetching because proper joins are impossible. You can force other to-one
relations to use parallel rather than join mode eager fetching using the
metadata extension described in <a class="xref" href="#eager-fetch-mode" title="9.2.1.&nbsp; Eager Fetch Mode">Section&nbsp;9.2.1, &#8220;
Eager Fetch Mode
&#8221;</a>.
</p>
<p>
Parallel subclass fetch mode only applies to queries on joined inheritance
hierarchies. Rather than outer-joining to
subclass tables, OpenJPA will issue the query separately for each subclass. In
all other situations, parallel subclass fetch mode acts just like join mode in
regards to vertically-mapped subclasses.
</p>
<p>
When OpenJPA knows that it is selecting for a single object only, it never uses
<code class="literal">parallel</code> mode, because the additional selects can be made
lazily just as efficiently. This mode only increases efficiency over <code class="literal">
join</code> mode when multiple objects with eager relations are being loaded,
or when multiple selects might be faster than joining to all possible
subclasses.
</p>
</li></ul></div>
<div class="section" id="ref_guide_perfpack_eager_conf"><div class="titlepage"><div><div><h3 class="title">8.1.&nbsp;
Configuring Eager Fetching
</h3></div></div></div>
<a class="indexterm" name="d5e13078"></a>
<p>
<a class="indexterm" name="d5e13082"></a>
<a class="indexterm" name="d5e13084"></a>
<a class="indexterm" name="d5e13086"></a>
<a class="indexterm" name="d5e13089"></a>
You can control OpenJPA's default eager fetch mode through the
<a class="link" href="#openjpa.jdbc.EagerFetchMode" title="6.4.&nbsp; openjpa.jdbc.EagerFetchMode"><code class="literal">
openjpa.jdbc.EagerFetchMode</code></a> and
<a class="link" href="#openjpa.jdbc.SubclassFetchMode" title="6.16.&nbsp; openjpa.jdbc.SubclassFetchMode"><code class="literal">
openjpa.jdbc.SubclassFetchMode</code></a> configuration properties. Set
each of these properties to one of the mode names described in the previous
section: <code class="literal">none, join, parallel</code>. If left unset, the eager
fetch mode defaults to <code class="literal">parallel</code> and the subclass fetch mode
defaults to <code class="literal">join</code> These are generally the most robust and
performant strategies.
</p>
<p>
You can easily override the default fetch modes at runtime for any lookup or
query through OpenJPA's fetch configuration APIs. See
<a class="xref" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">Chapter&nbsp;9, <i>
Runtime Extensions
</i></a> for details.
</p>
<div class="example" id="ref_guide_perfpack_eager_def"><p class="title"><b>Example&nbsp;5.23.&nbsp;
Setting the Default Eager Fetch Mode
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.EagerFetchMode" value="parallel"/&gt;
&lt;property name="openjpa.jdbc.SubclassFetchMode" value="join"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_perfpack_eager_runtime"><p class="title"><b>Example&nbsp;5.24.&nbsp;
Setting the Eager Fetch Mode at Runtime
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
import org.apache.openjpa.persistence.jdbc.*;
...
Query q = em.createQuery("select p from Person p where p.address.state = 'TX'");
OpenJPAQuery kq = OpenJPAPersistence.cast(q);
JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan();
fetch.setEagerFetchMode(FetchMode.PARALLEL);
fetch.setSubclassFetchMode(FetchMode.JOIN);
List results = q.getResultList();
</pre>
</div></div><br class="example-break">
<p>
You can specify a default subclass fetch mode for an individual class with the
metadata extension described in <a class="xref" href="#subclass-fetch-mode" title="9.1.1.&nbsp; Subclass Fetch Mode">Section&nbsp;9.1.1, &#8220;
Subclass Fetch Mode
&#8221;</a>.
Note, however, that you cannot "upgrade" the runtime fetch mode with your class
setting. If the runtime fetch mode is <code class="literal">none</code>, no eager
subclass data fetching will take place, regardless of your metadata setting.
</p>
<p>
This applies to the eager fetch mode metadata extension as well (see
<a class="xref" href="#eager-fetch-mode" title="9.2.1.&nbsp; Eager Fetch Mode">Section&nbsp;9.2.1, &#8220;
Eager Fetch Mode
&#8221;</a>). You can use this extension to
disable eager fetching on a field or to declare that a collection would rather
use joins than parallel selects or vice versa. But an extension value of
<code class="literal">join</code> won't cause any eager joining if the fetch
configuration's setting is <code class="literal">none</code>.
</p>
</div>
<div class="section" id="ref_guide_perfpack_eager_consider"><div class="titlepage"><div><div><h3 class="title">8.2.&nbsp;
Eager Fetching Considerations and Limitations
</h3></div></div></div>
<p>
There are several important points that you should consider when using eager
fetching:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e13120"></a>
<a class="indexterm" name="d5e13123"></a>
When you are using <code class="literal">parallel</code> eager fetch mode and you have
large result sets enabled (see <a class="xref" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">Section&nbsp;10, &#8220;
Large Result Sets
&#8221;</a>)
or you place a range on a query, OpenJPA performs the needed parallel selects on
one page of results at a time. For example, suppose your <code class="literal">
FetchBatchSize</code> is set to 20, and you perform a large result set query
on a class that has collection fields in the configured fetch groups. OpenJPA
will immediately cache the first <code class="literal">20</code> results of the query
using <code class="literal">join</code> mode eager fetching only. Then, it will issue the
extra selects needed to eager fetch your collection fields according to
<code class="literal">parallel</code> mode. Each select will use a SQL <code class="literal">IN
</code> clause (or multiple <code class="literal">OR</code> clauses if your class has a
compound primary key) to limit the selected collection elements to those owned
by the 20 cached results.
</p>
<p>
Once you iterate past the first 20 results, OpenJPA will cache the next 20 and
again issue any needed extra selects for collection fields, and so on. This
pattern ensures that you get the benefits of eager fetching without bringing
more data into memory than anticipated.
</p>
</li><li class="listitem">
<p>
Once OpenJPA eager-joins into a class, it cannot issue any further eager to-many
joins or parallel selects from that class in the same query. To-one joins,
however, can recurse to any level.
</p>
</li><li class="listitem">
<p>
Using a to-many join makes it impossible to determine the number of instances
the result set contains without traversing the entire set. This is because each
result object might be represented by multiple rows. Thus, queries with a range
specification or queries configured for lazy result set traversal automatically
turn off eager to-many joining.
</p>
</li><li class="listitem">
<p>
OpenJPA cannot eagerly join to polymorphic relations to non-leaf classes in a
table-per-class inheritance hierarchy. You can work around this restriction
using the mapping extensions described in <a class="xref" href="#nonpolymorphic" title="9.2.2.&nbsp; Nonpolymorphic">Section&nbsp;9.2.2, &#8220;
Nonpolymorphic
&#8221;</a>.
</p>
</li></ul></div>
</div>
</div>
</div>
<div class="chapter" id="ref_guide_meta"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;6.&nbsp;
Metadata
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_meta_factory">1.
Metadata Factory
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_repository">2. Metadata Repository</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa">3.
Additional JPA Metadata
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_jpa_datastoreid">3.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_version">3.2.
Surrogate Version
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent">3.3.
Persistent Field Values
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_coll">3.4. Persistent Collection Fields</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_map">3.5. Persistent Map Fields</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_ext">4.
Metadata Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_meta_class">4.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#fetch-groups">4.1.1.
Fetch Groups
</a></span></dt><dt><span class="section"><a href="#data-cache">4.1.2.
Data Cache
</a></span></dt><dt><span class="section"><a href="#detached-state-field">4.1.3.
Detached State
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_field">4.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#dependent">4.2.1.
Dependent
</a></span></dt><dt><span class="section"><a href="#load-fetch-group">4.2.2.
Load Fetch Group
</a></span></dt><dt><span class="section"><a href="#lrs">4.2.3.
LRS
</a></span></dt><dt><span class="section"><a href="#inverse-logical">4.2.4.
Inverse-Logical
</a></span></dt><dt><span class="section"><a href="#read-only">4.2.5.
Read-Only
</a></span></dt><dt><span class="section"><a href="#type">4.2.6.
Type
</a></span></dt><dt><span class="section"><a href="#externalizer">4.2.7.
Externalizer
</a></span></dt><dt><span class="section"><a href="#factory">4.2.8.
Factory
</a></span></dt><dt><span class="section"><a href="#external-values">4.2.9.
External Values
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_example">4.3.
Example
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_xml">4.4.
XML extensions
</a></span></dt></dl></dd></dl></div>
<p>
The JPA Overview covers JPA metadata in <a class="xref" href="#jpa_overview_meta" title="Chapter&nbsp;5.&nbsp; Metadata">Chapter&nbsp;5, <i>
Metadata
</i></a>.
This chapter discusses OpenJPA's extensions to standard JPA metadata.
</p>
<div class="section" id="ref_guide_meta_factory"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Metadata Factory
</h2></div></div></div>
<a class="indexterm" name="d5e13148"></a>
<p>
The <a class="link" href="#openjpa.MetaDataFactory" title="5.48.&nbsp; openjpa.MetaDataFactory"><code class="literal">openjpa.MetaDataFactory
</code></a> configuration property controls metadata loading and storing.
This property takes a plugin string (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) describing a concrete
<a class="ulink" href="../../apidocs/org/apache/openjpa/meta/MetaDataFactory.html" target="_top">
<code class="classname">org.apache.openjpa.meta.MetaDataFactory</code></a>
implementation. A metadata factory can load mapping information as well as
persistence metadata, or it can leave mapping information to a separate
<span class="emphasis"><em>mapping factory</em></span> (see
<a class="xref" href="#ref_guide_mapping_factory" title="5.&nbsp; Mapping Factory">Section&nbsp;5, &#8220;
Mapping Factory
&#8221;</a>). OpenJPA recognizes the
following built-in metadata factories:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">jpa</code>: Standard JPA metadata. This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/PersistenceMetaDataFactory.html" target="_top">
<code class="classname">
org.apache.openjpa.persistence.PersistenceMetaDataFactory</code></a>.
</p>
</li></ul></div>
<p>
JPA has built-in settings for listing your persistent classes, which
the <a class="link" href="#jpa_overview_persistence_xml" title="1.&nbsp; persistence.xml">JPA Overview</a> describes.
OpenJPA supports these JPA standard settings by translating them into its own
internal metadata factory properties. Each internal property represents a
different mechanism for locating persistent types; you can choose the mechanism
or combination of mechanisms that are most convenient. See
<a class="xref" href="#ref_guide_pc_pcclasses" title="1.&nbsp; Persistent Class List">Section&nbsp;1, &#8220;
Persistent Class List
&#8221;</a> for a discussion of when it is
necessary to list your persistent classes.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Types</code>: A semicolon-separated list of fully-qualified
persistent class names.
</p>
</li><li class="listitem">
<p>
<code class="literal">Resources</code>: A semicolon-separated list of resource paths to
metadata files or jar archives. Each jar archive will be scanned for
annotated JPA entities.
</p>
</li><li class="listitem">
<p>
<code class="literal">URLs</code>: A semicolon-separated list of URLs of metadata files
or jar archives. Each jar archive will be scanned for annotated JPA
entities.
</p>
</li><li class="listitem">
<p>
<code class="literal">ClasspathScan</code>: A semicolon-separated list of directories or
jar archives listed in your classpath. Each directory and jar archive will be
scanned for annotated JPA entities.
</p>
</li></ul></div>
<div class="example" id="ref_guide_meta_stdfactoryex"><p class="title"><b>Example&nbsp;6.1.&nbsp;
Setting a Standard Metadata Factory
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.MetaDataFactory" value="jpa(ClasspathScan=build;lib.jar)"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_meta_customfactoryex"><p class="title"><b>Example&nbsp;6.2.&nbsp;
Setting a Custom Metadata Factory
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.MetaDataFactory" value="com.xyz.CustomMetaDataFactory"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_meta_repository"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;Metadata Repository</h2></div></div></div>
<p>The openjpa.MetaDataRepository configuration property controls the configuration of
the MetaDataRepository. The following are valid properties:</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">Preload</code>: A boolean property. If true, OpenJPA will eagerly load the repository on
EntityManagerFactory creation. As a result, all Entity classes will be eagerly loaded by the JVM.
Once MetaData preloading completes, all locking is removed from the MetaDataRepository and this will
result in a much more scalable repository. If false, the repository will be lazily loaded as Entity
classes are loaded by the JVM. The default value is false.
</p>
</li></ul></div>
<div class="example" id="ref_guide_meta_repo"><p class="title"><b>Example&nbsp;6.3.&nbsp;
Setting the Preload Property on Metadata Repository
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.MetaDataRepository" value="Preload=true"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_meta_jpa"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Additional JPA Metadata
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_meta_jpa_datastoreid">3.1.
Datastore Identity
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_version">3.2.
Surrogate Version
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent">3.3.
Persistent Field Values
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_coll">3.4. Persistent Collection Fields</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_jpa_persistent_map">3.5. Persistent Map Fields</a></span></dt></dl></div>
<a class="indexterm" name="d5e13200"></a>
<p>
This section describes OpenJPA's core additions to standard entity metadata. We
present the object-relational mapping syntax to support these additions in
<a class="xref" href="#ref_guide_mapping_jpa" title="7.&nbsp; Additional JPA Mappings">Section&nbsp;7, &#8220;
Additional JPA Mappings
&#8221;</a>. Finally,
<a class="xref" href="#ref_guide_meta_ext" title="4.&nbsp; Metadata Extensions">Section&nbsp;4, &#8220;
Metadata Extensions
&#8221;</a> covers additional extensions to JPA
metadata that allow you to access auxiliary OpenJPA features.
</p>
<div class="section" id="ref_guide_meta_jpa_datastoreid"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;
Datastore Identity
</h3></div></div></div>
<a class="indexterm" name="d5e13208"></a>
<p>
JPA typically requires you to declare one or more <code class="literal">Id</code> fields
to act as primary keys. OpenJPA, however, can create and maintain a surrogate
primary key value when you do not declare any <code class="literal">Id</code> fields. This
form of persistent identity is called <span class="emphasis"><em>datastore identity</em></span>.
<a class="xref" href="#ref_guide_pc_oid" title="4.&nbsp; Object Identity">Section&nbsp;4, &#8220;
Object Identity
&#8221;</a> discusses OpenJPA's support for
datastore identity in JPA. We cover how to map your datastore identity primary
key column in <a class="xref" href="#ref_guide_mapping_jpa_datastoreid" title="7.1.&nbsp; Datastore Identity Mapping">Section&nbsp;7.1, &#8220;
Datastore Identity Mapping
&#8221;</a>
</p>
</div>
<div class="section" id="ref_guide_meta_jpa_version"><div class="titlepage"><div><div><h3 class="title">3.2.&nbsp;
Surrogate Version
</h3></div></div></div>
<a class="indexterm" name="d5e13219"></a>
<p>
Just as OpenJPA can maintain your entity's identity without any <code class="literal">Id
</code> fields, OpenJPA can maintain your entity's optimistic version without
any <code class="literal">Version</code> fields.
<a class="xref" href="#ref_guide_mapping_jpa_version" title="7.2.&nbsp; Surrogate Version Mapping">Section&nbsp;7.2, &#8220;
Surrogate Version Mapping
&#8221;</a> shows you how to map
surrogate version columns.
</p>
</div>
<div class="section" id="ref_guide_meta_jpa_persistent"><div class="titlepage"><div><div><h3 class="title">3.3.&nbsp;
Persistent Field Values
</h3></div></div></div>
<a class="indexterm" name="d5e13228"></a>
<p>
JPA defines <code class="literal">Basic</code>, <code class="literal">Lob</code>, <code class="literal">Embedded
</code>, <code class="literal">ManyToOne</code>, and <code class="literal">OneToOne</code>
persistence strategies for direct field values. OpenJPA supports all of these
standard strategies, but adds one of its own: <code class="literal">Persistent</code>.
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Persistent.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.Persistent</code></a>
metadata annotation can represent any direct field value, including custom
types. It has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the field eagerly or
lazily. Corresponds exactly to the same-named property of standard JPA
annotations such as <a class="link" href="#jpa_overview_meta_basic" title="2.7.&nbsp; Basic"><code class="classname"> Basic
</code></a>. Defaults to <code class="literal">FetchType.EAGER</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] cascade</code>: Array of enum values defining cascade
behavior for this field. Corresponds exactly to the same-named property of
standard JPA annotations such as <a class="link" href="#jpa_overview_meta_manytoone" title="2.9.&nbsp; Many To One">
<code class="classname"> ManyToOne</code></a>. Defaults to empty array.
</p>
</li><li class="listitem">
<p>
<code class="literal">String mappedBy</code>: Names the field in the related entity that
maps this bidirectional relation. Corresponds to the same-named property of
standard JPA annotations such as <a class="link" href="#jpa_overview_meta_onetoone" title="2.11.&nbsp; One To One">
<code class="classname"> OneToOne</code></a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean optional</code>: Whether the value can be null. Corresponds
to the same-named property of standard JPA annotations such as
<a class="link" href="#jpa_overview_meta_manytoone" title="2.9.&nbsp; Many To One"><code class="classname"> ManyToOne</code>
</a>, but can apply to non-entity object values as well. Defaults to
<code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean embedded</code>: Set this property to <code class="literal">true
</code> if the field value is stored as an embedded object.
</p>
</li></ul></div>
<p>
Though you can use the <code class="classname">Persistent</code> annotation in place of
most of the standard direct field annotations mentioned above, we recommend
primarily using it for non-standard and custom types for which no standard JPA
annotation exists. For example, <a class="xref" href="#ref_guide_mapping_jpa_columns" title="7.3.&nbsp; Multi-Column Mappings">Section&nbsp;7.3, &#8220;
Multi-Column Mappings
&#8221;</a>
demonstrates the use of the <code class="classname">Persistent</code> annotation
to denote a persistent <code class="classname">java.awt.Point</code> field.
</p>
</div>
<div class="section" id="ref_guide_meta_jpa_persistent_coll"><div class="titlepage"><div><div><h3 class="title">3.4.&nbsp;Persistent Collection Fields</h3></div></div></div>
<a class="indexterm" name="d5e13273"></a>
<p>
JPA standardizes support for collections of entities with the <code class="literal">
OneToMany</code> and <code class="literal">ManyToMany</code> persistence strategies.
OpenJPA supports these strategies, and may be extended for other strategies as
well. For extended strategies, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/PersistentCollection.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.PersistentCollection</code></a> metadata
annotation to represents any persistent collection field. It has the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Class elementType</code>: The class of the collection elements.
This information is usually taken from the parameterized collection element
type. You must supply it explicitly, however, if your field isn't a
parameterized type.
</p>
</li><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the collection eagerly or
lazily. Corresponds exactly to the same-named property of standard JPA
annotations such as <a class="link" href="#jpa_overview_meta_basic" title="2.7.&nbsp; Basic"><code class="classname">
Basic</code></a>. Defaults to <code class="literal">FetchType.LAZY</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">String mappedBy</code>: Names the field in the related entity that
maps this bidirectional relation. Corresponds to the same-named property of
standard JPA annotations such as <a class="link" href="#jpa_overview_meta_manytomany" title="2.12.&nbsp; Many To Many">
<code class="classname">ManyToMany</code></a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] elementCascade</code>: Array of enum values defining
cascade behavior for the collection elements. Corresponds exactly to the
<code class="literal">cascade</code> property of standard JPA annotations such as
<a class="link" href="#jpa_overview_meta_manytomany" title="2.12.&nbsp; Many To Many"><code class="classname">
ManyToMany</code></a>. Defaults to empty array.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean elementEmbedded</code>: Set this property to <code class="literal">true
</code> if the elements are stored as embedded objects.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_meta_jpa_persistent_map"><div class="titlepage"><div><div><h3 class="title">3.5.&nbsp;Persistent Map Fields</h3></div></div></div>
<a class="indexterm" name="d5e13308"></a>
<p>
JPA has limited support for maps. If you extend JPA's standard map support to
encompass new mappings, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/PersistentMap.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.PersistentMap</code></a> metadata
annotation to represent your custom persistent map fields. It has the
following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Class keyType</code>: The class of the map keys. This information
is usually taken from the parameterized map key type. You must supply it
explicitly, however, if your field isn't a parameterized type.
</p>
</li><li class="listitem">
<p>
<code class="literal">Class elementType</code>: The class of the map values. This
information is usually taken from the parameterized map value type. You must
supply it explicitly, however, if your field isn't a parameterized type.
</p>
</li><li class="listitem">
<p>
<code class="literal">FetchType fetch</code>: Whether to load the collection eagerly or
lazily. Corresponds exactly to the same-named property of standard JPA
annotations such as <a class="link" href="#jpa_overview_meta_basic" title="2.7.&nbsp; Basic"><code class="classname">
Basic</code></a>. Defaults to <code class="literal">FetchType.LAZY</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] keyCascade</code>: Array of enum values defining
cascade behavior for the map keys. Corresponds exactly to the <code class="literal">cascade
</code> property of standard JPA annotations such as
<a class="link" href="#jpa_overview_meta_manytoone" title="2.9.&nbsp; Many To One"><code class="classname">
ManyToOne</code></a>. Defaults to empty array.
</p>
</li><li class="listitem">
<p>
<code class="literal">CascadeType[] elementCascade</code>: Array of enum values defining
cascade behavior for the map values. Corresponds exactly to the
<code class="literal">cascade</code> property of standard JPA annotations such as
<a class="link" href="#jpa_overview_meta_manytoone" title="2.9.&nbsp; Many To One"><code class="classname">
ManyToOne</code></a>. Defaults to empty array.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean keyEmbedded</code>: Set this property to <code class="literal">true
</code> if the map keys are stored as embedded objects.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean elementEmbedded</code>: Set this property to <code class="literal">
true</code> if the map values are stored as embedded objects.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_meta_ext"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Metadata Extensions
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_meta_class">4.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#fetch-groups">4.1.1.
Fetch Groups
</a></span></dt><dt><span class="section"><a href="#data-cache">4.1.2.
Data Cache
</a></span></dt><dt><span class="section"><a href="#detached-state-field">4.1.3.
Detached State
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_field">4.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#dependent">4.2.1.
Dependent
</a></span></dt><dt><span class="section"><a href="#load-fetch-group">4.2.2.
Load Fetch Group
</a></span></dt><dt><span class="section"><a href="#lrs">4.2.3.
LRS
</a></span></dt><dt><span class="section"><a href="#inverse-logical">4.2.4.
Inverse-Logical
</a></span></dt><dt><span class="section"><a href="#read-only">4.2.5.
Read-Only
</a></span></dt><dt><span class="section"><a href="#type">4.2.6.
Type
</a></span></dt><dt><span class="section"><a href="#externalizer">4.2.7.
Externalizer
</a></span></dt><dt><span class="section"><a href="#factory">4.2.8.
Factory
</a></span></dt><dt><span class="section"><a href="#external-values">4.2.9.
External Values
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_meta_example">4.3.
Example
</a></span></dt><dt><span class="section"><a href="#ref_guide_meta_xml">4.4.
XML extensions
</a></span></dt></dl></div>
<a class="indexterm" name="d5e13349"></a>
<p>
OpenJPA extends standard metadata to allow you to access advanced OpenJPA
functionality. This section covers persistence metadata extensions; we discuss
mapping metadata extensions in <a class="xref" href="#ref_guide_mapping_ext" title="9.&nbsp; Mapping Extensions">Section&nbsp;9, &#8220;
Mapping Extensions
&#8221;</a>.
All metadata extensions are optional; OpenJPA will rely on its defaults when no
explicit data is provided.
</p>
<div class="section" id="ref_guide_meta_class"><div class="titlepage"><div><div><h3 class="title">4.1.&nbsp;
Class Extensions
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#fetch-groups">4.1.1.
Fetch Groups
</a></span></dt><dt><span class="section"><a href="#data-cache">4.1.2.
Data Cache
</a></span></dt><dt><span class="section"><a href="#detached-state-field">4.1.3.
Detached State
</a></span></dt></dl></div>
<p>
OpenJPA recognizes the following class extensions:
</p>
<div class="section" id="fetch-groups"><div class="titlepage"><div><div><h4 class="title">4.1.1.&nbsp;
Fetch Groups
</h4></div></div></div>
<a class="indexterm" name="d5e13359"></a>
<p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/FetchGroups.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.FetchGroups</code></a> and
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/FetchGroup.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.FetchGroup</code></a>
annotations allow you to define fetch groups in your JPA entities.
<a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a> discusses OpenJPA's support for fetch
groups in general; see <a class="xref" href="#ref_guide_fetch_custom" title="7.1.&nbsp; Custom Fetch Groups">Section&nbsp;7.1, &#8220;
Custom Fetch Groups
&#8221;</a> for how to
use these annotations in particular.
</p>
</div>
<div class="section" id="data-cache"><div class="titlepage"><div><div><h4 class="title">4.1.2.&nbsp;
Data Cache
</h4></div></div></div>
<a class="indexterm" name="d5e13373"></a>
<p>
<a class="xref" href="#ref_guide_cache" title="1.&nbsp; Data Cache">Section&nbsp;1, &#8220;
Data Cache
&#8221;</a> examines caching in OpenJPA. Metadata
extensions allow individual classes to override system caching defaults.
</p>
<p>
OpenJPA defines the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/DataCache.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.DataCache</code></a>
annotation for caching information. This annotation has the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">boolean enabled</code>: Whether to cache data for instances of the
class. Defaults to <code class="literal">true</code> for base classes, or the superclass
value for subclasses. If you set this property to <code class="literal">false</code>, all
other properties are ignored.
</p>
</li><li class="listitem">
<p>
<code class="literal">int timeout</code>: The number of milliseconds data for the class
remains valid. Use -1 for no timeout. Defaults to the
<a class="link" href="#openjpa.DataCacheTimeout" title="5.29.&nbsp; openjpa.DataCacheTimeout"><code class="literal"> openjpa.DataCacheTimeout
</code></a> property value.
</p>
</li></ul></div>
</div>
<div class="section" id="detached-state-field"><div class="titlepage"><div><div><h4 class="title">4.1.3.&nbsp;
Detached State
</h4></div></div></div>
<a class="indexterm" name="d5e13396"></a>
<p>
The OpenJPA <a class="link" href="#ref_guide_pc_enhance" title="2.&nbsp; Enhancement">enhancer</a> may add a
synthetic field to detachable classes to hold detached state (see
<a class="xref" href="#ref_guide_detach_graph" title="1.3.&nbsp; Defining the Detached Object Graph">Section&nbsp;1.3, &#8220;
Defining the Detached Object Graph
&#8221;</a> for details). You can instead
declare your own detached state field or suppress the creation of a detached
state field altogether. In the latter case, your class must not use
<a class="link" href="#ref_guide_pc_oid" title="4.&nbsp; Object Identity">datastore identity</a>, and should declare
a version field to detect optimistic concurrency errors during detached
modifications.
</p>
<p>
OpenJPA defines the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/DetachedState.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.DetachedState</code></a>
annotation for controlling detached state. When used to annotate a class,
<code class="classname">DetachedState</code> recognizes the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">boolean enabled</code>: Set to false to suppress the use of
detached state.
</p>
</li><li class="listitem">
<p>
<code class="literal">String fieldName</code>: Use this property to declare your own
detached state field. The field must be of type <code class="classname">Object</code>.
Typically this property is only used if the field is inherited from a
non-persisted superclass. If the field is declared in your entity class, you
will typically annotate the field directly, as described below.
</p>
</li></ul></div>
<p>
If you declare your own detached state field, you can annotate that field with
<code class="classname">DetachedState</code> directly, rather than placing the
annotation at the class level and using the <code class="literal">fieldName</code>
property. When placed on a field, <code class="classname">DetachedState</code> acts as a
marker annotation; it does not recognize any properties. Your annotated field
must be of type <code class="classname">Object</code>.
</p>
</div>
</div>
<div class="section" id="ref_guide_meta_field"><div class="titlepage"><div><div><h3 class="title">4.2.&nbsp;
Field Extensions
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dependent">4.2.1.
Dependent
</a></span></dt><dt><span class="section"><a href="#load-fetch-group">4.2.2.
Load Fetch Group
</a></span></dt><dt><span class="section"><a href="#lrs">4.2.3.
LRS
</a></span></dt><dt><span class="section"><a href="#inverse-logical">4.2.4.
Inverse-Logical
</a></span></dt><dt><span class="section"><a href="#read-only">4.2.5.
Read-Only
</a></span></dt><dt><span class="section"><a href="#type">4.2.6.
Type
</a></span></dt><dt><span class="section"><a href="#externalizer">4.2.7.
Externalizer
</a></span></dt><dt><span class="section"><a href="#factory">4.2.8.
Factory
</a></span></dt><dt><span class="section"><a href="#external-values">4.2.9.
External Values
</a></span></dt></dl></div>
<p>
OpenJPA recognizes the following field extensions:
</p>
<div class="section" id="dependent"><div class="titlepage"><div><div><h4 class="title">4.2.1.&nbsp;
Dependent
</h4></div></div></div>
<a class="indexterm" name="d5e13427"></a>
<p>
In a <span class="emphasis"><em>dependent</em></span> relation, the referenced object is deleted
whenever the owning object is deleted, or whenever the relation is severed by
nulling or resetting the owning field. For example, if the <code class="literal">
Magazine.coverArticle</code> field is marked dependent, then setting
<code class="literal">Magazine.coverArticle</code> to a new <code class="classname">Article</code>
instance will automatically delete the old <code class="classname">Article</code> stored
in the field. Similarly, deleting a <code class="classname">Magazine</code> object will
automatically delete its current cover <code class="classname">Article</code>. (This
latter processing is analogous to using JPA's CascadeType.REMOVE functionality
as described in <a class="xref" href="#jpa_overview_meta_cascade" title="2.9.1.&nbsp; Cascade Type">Section&nbsp;2.9.1, &#8220;
Cascade Type
&#8221;</a>.) You can
prevent an orphaned dependent object from being automatically deleted by
assigning it to another relation in the same transaction.
</p>
<p>
OpenJPA offers a family of marker annotations to denote dependent relations in
JPA entities:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Dependent.html" target="_top">
<code class="classname"> org.apache.openjpa.persistence.Dependent</code></a>: Marks
a direct relation as dependent.
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/ElementDependent.html" target="_top">
<code class="classname"> org.apache.openjpa.persistence.ElementDependent</code></a>
: Marks the entity elements of a collection, array, or map field as dependent.
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/KeyDependent.html" target="_top">
<code class="classname"> org.apache.openjpa.persistence.KeyDependent</code></a>:
Marks the key entities in a map field as dependent.
</p>
</li></ul></div>
</div>
<div class="section" id="load-fetch-group"><div class="titlepage"><div><div><h4 class="title">4.2.2.&nbsp;
Load Fetch Group
</h4></div></div></div>
<a class="indexterm" name="d5e13456"></a>
<a class="indexterm" name="d5e13460"></a>
<p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/LoadFetchGroup.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.LoadFetchGroup</code></a>
annotation specifies a field's load fetch group.
<a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a> discusses OpenJPA's support for fetch groups
in general; see <a class="xref" href="#ref_guide_fetch_custom" title="7.1.&nbsp; Custom Fetch Groups">Section&nbsp;7.1, &#8220;
Custom Fetch Groups
&#8221;</a> for how to use this
annotation in particular.
</p>
</div>
<div class="section" id="lrs"><div class="titlepage"><div><div><h4 class="title">4.2.3.&nbsp;
LRS
</h4></div></div></div>
<a class="indexterm" name="d5e13470"></a>
<p>
This boolean extension, denoted by the OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/LRS.html" target="_top"><code class="classname">
org.apache.openjpa.persistence.LRS</code></a> annotation,
indicates that a field should use OpenJPA's special large result set collection
or map proxies. A complete description of large result set proxies is available
in <a class="xref" href="#ref_guide_pc_scos_proxy_lrs" title="6.4.2.&nbsp; Large Result Set Proxies">Section&nbsp;6.4.2, &#8220;
Large Result Set Proxies
&#8221;</a>.
</p>
</div>
<div class="section" id="inverse-logical"><div class="titlepage"><div><div><h4 class="title">4.2.4.&nbsp;
Inverse-Logical
</h4></div></div></div>
<a class="indexterm" name="d5e13481"></a>
<p>
This extension names the inverse field in a logical bidirectional relation.
To create a logical bidirectional relation in OpenJPA, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/InverseLogical.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.InverseLogical</code></a>
annotation. We discuss logical bidirectional relations and this
extension in detail in <a class="xref" href="#ref_guide_inverses" title="5.&nbsp; Managed Inverses">Section&nbsp;5, &#8220;
Managed Inverses
&#8221;</a>.
</p>
</div>
<div class="section" id="read-only"><div class="titlepage"><div><div><h4 class="title">4.2.5.&nbsp;
Read-Only
</h4></div></div></div>
<a class="indexterm" name="d5e13492"></a>
<a class="indexterm" name="d5e13497"></a>
<p>
The read-only extension makes a field unwritable. The extension only applies to
existing persistent objects; new object fields are always writeable.
</p>
<p>
To mark a field read-only in JPA metadata, set the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/ReadOnly.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.ReadOnly</code></a>
annotation to an
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/UpdateAction.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.UpdateAction</code></a> enum
value. The <code class="classname">UpdateAction</code> enum includes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">UpdateAction.IGNORE</code>: Updates to the field are completely
ignored. The field is not considered dirty. The new value will not even get
stored in the OpenJPA <a class="link" href="#ref_guide_cache" title="1.&nbsp; Data Cache">data cache</a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">UpdateAction.RESTRICT</code>: Any attempt to change the field will
result in an immediate exception.
</p>
</li></ul></div>
</div>
<div class="section" id="type"><div class="titlepage"><div><div><h4 class="title">4.2.6.&nbsp;
Type
</h4></div></div></div>
<a class="indexterm" name="d5e13517"></a>
<p>
OpenJPA has three levels of support for relations:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
Relations that hold a reference to an object of a concrete persistent class are
supported by storing the primary key values of the related instance in the
database.
</p>
</li><li class="listitem">
<p>
Relations that hold a reference to an object of an unknown persistent class are
supported by storing the stringified identity value of the related instance.
This level of support does not allow queries across the relation.
</p>
</li><li class="listitem">
<p>
Relations that hold an unknown object or interface. The only way to support
these relations is to serialize their value to the database. This does not allow
you to query the field, and is not very efficient.
</p>
</li></ol></div>
<p>
Clearly, when you declare a field's type to be another persistence-capable
class, OpenJPA uses level 1 support. By default, OpenJPA assumes that any
interface-typed fields you declare will be implemented only by other persistent
classes, and assigns interfaces level 2 support. The exception to this rule is
the <code class="classname">java.io.Serializable</code> interface. If you declare a
field to be of type <code class="classname">Serializable</code>, OpenJPA lumps it
together with <code class="classname">java.lang.Object</code> fields and other
non-interface, unrecognized field types, which are all assigned level 3 support.
</p>
<p>
With OpenJPA's type family of metadata extensions, you can control the level of
support given to your unknown/interface-typed fields. Setting the value of this
extension to <code class="classname">Entity</code> indicates that the
field value will always be some persistent object, and gives level 2 support.
Setting the value of this extension to the class of a concrete persistent type
is even better; it gives you level 1 support (just as if you had declared your
field to be of that type in the first place). Setting this extension to
<code class="classname">Object</code> uses level 3 support. This is useful when you have
an interface relation that may <span class="bold"><strong>not</strong></span> hold other
persistent objects (recall that OpenJPA assumes interface fields will always
hold persistent instances by default).
</p>
<p>
This extension is also used with OpenJPA's externalization feature, described in
<a class="xref" href="#ref_guide_pc_extern" title="6.5.&nbsp; Externalization">Section&nbsp;6.5, &#8220;
Externalization
&#8221;</a>.
</p>
<p>
OpenJPA defines the following type annotations for field values, collection,
array, and map elements, and map keys, respectively:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Type.html" target="_top"><code class="classname">
org.apache.openjpa.persistence.Type</code></a>
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/ElementType.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.ElementType</code></a>
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/KeyType.html" target="_top"><code class="classname">
org.apache.openjpa.persistence.KeyType</code></a>
</p>
</li></ul></div>
</div>
<div class="section" id="externalizer"><div class="titlepage"><div><div><h4 class="title">4.2.7.&nbsp;
Externalizer
</h4></div></div></div>
<a class="indexterm" name="d5e13556"></a>
<p>
The OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Externalizer.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.Externalizer</code></a>
annotation names a method to transform a field value into a value of
another type. See <a class="xref" href="#ref_guide_pc_extern" title="6.5.&nbsp; Externalization">Section&nbsp;6.5, &#8220;
Externalization
&#8221;</a> for details.
</p>
</div>
<div class="section" id="factory"><div class="titlepage"><div><div><h4 class="title">4.2.8.&nbsp;
Factory
</h4></div></div></div>
<a class="indexterm" name="d5e13567"></a>
<p>
The OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Factory.html" target="_top"><code class="classname">
org.apache.openjpa.persistence.Factory</code></a> annotation
names a method to re-create a field value from its externalized form. See
<a class="xref" href="#ref_guide_pc_extern" title="6.5.&nbsp; Externalization">Section&nbsp;6.5, &#8220;
Externalization
&#8221;</a> for details.
</p>
</div>
<div class="section" id="external-values"><div class="titlepage"><div><div><h4 class="title">4.2.9.&nbsp;
External Values
</h4></div></div></div>
<a class="indexterm" name="d5e13578"></a>
<p>
The OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/ExternalValues.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.ExternalValues</code></a>
annotation declares values for transformation of simple fields to
different constant values in the datastore. See
<a class="xref" href="#ref_guide_pc_extern_values" title="6.5.1.&nbsp; External Values">Section&nbsp;6.5.1, &#8220;
External Values
&#8221;</a> for details.
</p>
</div>
</div>
<div class="section" id="ref_guide_meta_example"><div class="titlepage"><div><div><h3 class="title">4.3.&nbsp;
Example
</h3></div></div></div>
<p>
The following example shows you how to specify extensions in metadata.
</p>
<div class="example" id="ref_guide_metaex"><p class="title"><b>Example&nbsp;6.4.&nbsp;
OpenJPA Metadata Extensions
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
@DataCache(enabled=false)
public class Magazine
{
@ManyToMany
@LRS
private Collection&lt;Subscriber&gt; subscribers;
@ExternalValues({"true=1", "false=2"})
@Type(int.class)
private boolean weekly;
...
}
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_meta_xml"><div class="titlepage"><div><div><h3 class="title">4.4.&nbsp;
XML extensions
</h3></div></div></div>
<p>
OpenJPA has extended the JPA 2.0 schema to include elements and attributes corresponding
to OpenJPA extended metadata and mapping annotations. The schema are contained in 2
files: <a class="ulink" href="http://openjpa.apache.org/builds/latest/docs/schema/extendable/extendable-orm.xsd" target="_top">
extendable-orm.xsd</a> and
<a class="ulink" href="http://openjpa.apache.org/builds/latest/docs/schema/openjpa-orm.xsd" target="_top">openjpa-orm.xsd</a>.
The extendable-orm.xsd file provides copies of some of the JPA 2.0 schema elements with additional schema to make it
extendable.
The openjpa-orm.xsd file extends the extendable-orm.xsd with OpenJPA specific elements and attributes representing
OpenJPA annotations. Currently, only a subset of annotations have actually been implemented, and some of those
have been partially tested. The current status can be found by comments in the
<a class="ulink" href="http://openjpa.apache.org/builds/latest/docs/schema/openjpa-orm.xsd" target="_top">openjpa-orm.xsd</a>
schema file.
</p>
<p>
In order to use the OpenJPA extensions in your mapping file you must include the namespaces for these 2 new
schemas as well as for the schema for JPA 2.0, as shown in the following example:
</p>
<div class="example" id="ref_guide_schema_ex"><p class="title"><b>Example&nbsp;6.5.&nbsp;
OpenJPA Schema Extensions
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;entity-mappings xmlns="http://www.apache.org/openjpa/ns/orm/extendable"
xmlns:openjpa="http://www.apache.org/openjpa/ns/orm"
xmlns:orm="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.0"&gt;
&lt;entity class="org.apache.openjpa.persistence.jdbc.annotations.MultiColumnVersionPC"
metadata-complete="true"&gt;
&lt;table name="MCV"/&gt;
&lt;attributes&gt;
&lt;id name="id"&gt;
&lt;orm:generated-value/&gt;
&lt;/id&gt;
&lt;basic name="id"/&gt;
&lt;basic name="name"/&gt;
&lt;/attributes&gt;
&lt;openjpa:entity version-strategy="version-numbers"&gt;
&lt;openjpa:version-columns&gt;
&lt;openjpa:version-column name="v1"/&gt;
&lt;openjpa:version-column name="v2"/&gt;
&lt;openjpa:version-column name="v3"
column-definition="FLOAT"
scale="3"
precision="10"/&gt;
&lt;/openjpa:version-columns&gt;
&lt;/openjpa:entity&gt;
&lt;/entity&gt;
&lt;/entity-mappings&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
</div>
<div class="chapter" id="ref_guide_mapping"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;7.&nbsp;
Mapping
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_mappingtool">1.
Forward Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_mappingtool_examples">1.1.
Using the Mapping Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_ddl_examples">1.2.
Generating DDL SQL
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_synch">1.3.
Runtime Forward Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_pc_reverse">2.
Reverse Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_pc_reverse_custom">2.1.
Customizing Reverse Mapping
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_middle">3.
Meet-in-the-Middle Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_defaults">4.
Mapping Defaults
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_factory">5.
Mapping Factory
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_notes_nonstdjoins">6.
Non-Standard Joins
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa">7.
Additional JPA Mappings
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_datastoreid">7.1.
Datastore Identity Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_version">7.2.
Surrogate Version Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_columns">7.3.
Multi-Column Mappings
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fieldjoin">7.4.
Join Column Attribute Targets
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_embed">7.5.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll">7.6.
Collections
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_table">7.6.1.
Container Table
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_joincols">7.6.2.
Element Join Columns
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_order">7.6.3.
Order Column
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_onemany">7.7.
One-Sided One-Many Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map">7.8.
Maps
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keycols">7.8.1. Key Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keyjoincols">7.8.2. Key Join Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_embedkey">7.8.3. Key Embedded Mapping</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_ex">7.8.4. Examples</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_constraints">7.9.
Indexes and Constraints
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_index">7.9.1.
Indexes
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fk">7.9.2.
Foreign Keys
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_unique">7.9.3.
Unique Constraints
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_xmlmapping">7.10.
XML Column Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_streamsupport">7.11.
LOB Streaming
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_limits">8.
Mapping Limitations
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_limits_tpc">8.1.
Table Per Class
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_ext">9.
Mapping Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_ext_cls">9.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#subclass-fetch-mode">9.1.1.
Subclass Fetch Mode
</a></span></dt><dt><span class="section"><a href="#class-strategy">9.1.2.
Strategy
</a></span></dt><dt><span class="section"><a href="#discriminator-strategy">9.1.3.
Discriminator Strategy
</a></span></dt><dt><span class="section"><a href="#version-strategy">9.1.4.
Version Strategy
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_ext_field">9.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#eager-fetch-mode">9.2.1.
Eager Fetch Mode
</a></span></dt><dt><span class="section"><a href="#nonpolymorphic">9.2.2.
Nonpolymorphic
</a></span></dt><dt><span class="section"><a href="#class-criteria">9.2.3.
Class Criteria
</a></span></dt><dt><span class="section"><a href="#strategy">9.2.4.
Strategy
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_custom">10.
Custom Mappings
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_custom_class">10.1.
Custom Class Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_versdiscrim">10.2.
Custom Discriminator and Version Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field">10.3.
Custom Field Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_custom_vhandler">10.3.1.
Value Handlers
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_fieldstrat">10.3.2.
Field Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field_conf">10.3.3.
Configuration
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_orphan">11.
Orphaned Keys
</a></span></dt></dl></div>
<a class="indexterm" name="d5e13605"></a>
<p>
The JPA Overview's <a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a> explains
object-relational mapping under JPA. This chapter reviews the mapping utilities
OpenJPA provides and examines OpenJPA features that go beyond the JPA
specification.
</p>
<div class="section" id="ref_guide_mapping_mappingtool"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Forward Mapping
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_mappingtool_examples">1.1.
Using the Mapping Tool
</a></span></dt><dt><span class="section"><a href="#ref_guide_ddl_examples">1.2.
Generating DDL SQL
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_synch">1.3.
Runtime Forward Mapping
</a></span></dt></dl></div>
<a class="indexterm" name="d5e13611"></a>
<a class="indexterm" name="d5e13613"></a>
<a class="indexterm" name="d5e13616"></a>
<p>
<span class="emphasis"><em>Forward mapping</em></span> is the process of creating mappings and
their corresponding database schema from your object model. OpenJPA supports
forward mapping through the <span class="emphasis"><em>mapping tool</em></span>. The next section
presents several common mapping tool use cases. You can invoke the tool through
its Java class,
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/MappingTool" target="_top"><code class="classname">
org.apache.openjpa.jdbc.meta.MappingTool</code></a>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
<a class="xref" href="#ref_guide_integration_mappingtool" title="1.4.&nbsp; Mapping Tool Ant Task">Section&nbsp;1.4, &#8220;
Mapping Tool Ant Task
&#8221;</a> describes the mapping
tool Ant task.
</p>
</div>
<div class="example" id="ref_guide_mapping_mappingtool_typical"><p class="title"><b>Example&nbsp;7.1.&nbsp;
Using the Mapping Tool
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool Magazine.java
</pre>
</div></div><br class="example-break">
<p>
In addition to the universal flags of the
<a class="link" href="#ref_guide_conf_devtools" title="3.&nbsp; Command Line Configuration">configuration framework</a>, the
mapping tool accepts the following command line arguments:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-schemaAction/-sa &lt;add | refresh | drop | build | retain | reflect | createDB | dropDB | import | export | none&gt;
</code>: The action to take on the schema. These options correspond to the
same-named actions on the schema tool described in
<a class="xref" href="#ref_guide_schema_schematool" title="13.&nbsp; Schema Tool">Section&nbsp;13, &#8220;
Schema Tool
&#8221;</a>. Actions can be composed in a
comma-separated list. Unless you are running the mapping tool on all of
your persistent types at once or dropping a mapping, we strongly
recommend you use the default <code class="literal">add</code> action or the
<code class="literal">build</code> action. Otherwise you may end up inadvertently
dropping schema components that are used by classes you are not
currently running the tool over.
</p>
</li><li class="listitem">
<p>
<code class="literal">-schemaFile/-sf &lt;stdout | output file&gt;</code>: Use this
option to write the planned schema to an XML document rather than modify the
database. The document can then be manipulated and committed to the database
with the <a class="link" href="#ref_guide_schema_schematool" title="13.&nbsp; Schema Tool"> schema tool</a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-sqlFile/-sql &lt;stdout | output file&gt;</code>: Use this option
to write the planned schema modifications to a SQL script rather than modify the
database. Combine this with a <code class="literal">schemaAction</code> of <code class="literal">build
</code> to generate a script that recreates the schema for the current
mappings, even if the schema already exists.
</p>
</li><li class="listitem">
<p>
<code class="literal">-sqlEncode/-se &lt;encoding&gt;</code>: Use this option
with <code class="literal">-sqlFile</code> to write the SQL script in a different
Java character set encoding than the default JVM locale, such as
<code class="literal">-sqlTerminator/-st &lt;terminal&gt;</code>: Use this option
with <code class="literal">-sqlFile</code> to write the SQL terminating with a
different character instead of a semicolon.
</p>
</li><li class="listitem">
<p>
<code class="literal">-dropTables/-dt &lt;true/t | false/f&gt;</code>: Corresponds to the
same-named option on the schema tool.
</p>
</li><li class="listitem">
<p>
<code class="literal">-rollbackBeforeDDL/-rbddl &lt;true/t | false/f&gt;</code>: Corresponds to the
same-named option on the schema tool.
</p>
</li><li class="listitem">
<p>
<code class="literal">-dropSequences/-dsq &lt;true/t | false/f&gt;</code>: Corresponds to
the same-named option on the schema tool.
</p>
</li><li class="listitem">
<p>
<code class="literal">-openjpaTables/-ot &lt;true/t | false/f&gt;</code>: Corresponds to
the same-named option on the schema tool.
</p>
</li><li class="listitem">
<p>
<code class="literal">-ignoreErrors/-i &lt;true/t | false/f&gt;</code>: Corresponds to
the same-named option on the schema tool.
</p>
</li><li class="listitem">
<p>
<code class="literal">-schemas/-s &lt;schema and table names&gt;</code>: Corresponds to
the same-named option on the schema tool. This option is ignored if <code class="literal">
readSchema</code> is not set to <code class="literal">true</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-readSchema/-rs &lt;true/t | false/f&gt;</code>: Set this option to
<code class="literal">true</code> to read the entire existing schema when the tool runs.
Reading the existing schema ensures that OpenJPA does not generate any mappings
that use table, index, primary key, or foreign key names that conflict with
existing names. Depending on the JDBC driver, though, it can be a slow process
for large schemas.
</p>
</li><li class="listitem">
<p>
<code class="literal">-primaryKeys/-pk &lt;true/t | false/f&gt;</code>: Whether to read
and manipulate primary key information of existing tables. Defaults to false.
</p>
</li><li class="listitem">
<p>
<code class="literal">-foreignKeys/-fk &lt;true/t | false/f&gt;</code>: Whether to read
and manipulate foreign key information of existing tables. Defaults to false.
This means that to add any new foreign keys to a class that has already been
mapped, you must explicitly set this flag to true.
</p>
</li><li class="listitem">
<p>
<code class="literal">-indexes/-ix &lt;true/t | false/f&gt;</code>: Whether to read and
manipulate index information of existing tables. Defaults to false. This means
that to add any new indexes to a class that has already been mapped once, you
must explicitly set this flag to true.
</p>
</li><li class="listitem">
<p>
<code class="literal">-sequences/-sq &lt;true/t | false/f&gt;</code>: Whether to
manipulate sequences. Defaults to true.
</p>
</li><li class="listitem">
<p>
<code class="literal">-meta/-m &lt;true/t | false/f&gt;</code>: Whether the given action
applies to metadata rather than or in addition to mappings.
</p>
</li></ul></div>
<p>
The mapping tool also uses an <code class="literal">-action/-a</code> argument to specify
the action to take on each class. The available actions are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">buildSchema</code>: This is the default action. It
makes the database schema match your existing mappings. If your provided
mappings conflict with your class definitions, OpenJPA will fail with an
informative exception.
</p>
</li><li class="listitem">
<p>
<code class="literal">validate</code>: Ensure that the mappings for the given classes are
valid and that they match the schema. No mappings or tables will be changed. An
exception is thrown if any mappings are invalid.
</p>
</li></ul></div>
<p>
Each additional argument to the tool should be one of:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The full name of a persistent class.
</p>
</li><li class="listitem">
<p>
The .java file for a persistent class.
</p>
</li><li class="listitem">
<p>
The <code class="filename">.class</code> file of a persistent class.
</p>
</li></ul></div>
<p>
If you do not supply any arguments to the mapping tool, it will run on the
classes in your persistent classes list (see
<a class="xref" href="#ref_guide_pc_pcclasses" title="1.&nbsp; Persistent Class List">Section&nbsp;1, &#8220;
Persistent Class List
&#8221;</a>).
</p>
<p>
The mappings generated by the mapping tool are stored by the system <span class="emphasis"><em>
mapping factory</em></span>. <a class="xref" href="#ref_guide_mapping_factory" title="5.&nbsp; Mapping Factory">Section&nbsp;5, &#8220;
Mapping Factory
&#8221;</a>
discusses your mapping factory options.
</p>
<div class="section" id="ref_guide_mapping_mappingtool_examples"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Using the Mapping Tool
</h3></div></div></div>
<a class="indexterm" name="d5e13719"></a>
<p>
The JPA specification defines a comprehensive set of defaults for missing
mapping information. Thus, forward mapping in JPA is virtually automatic. After
using the mapping annotations covered in <a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a>
of the JPA Overview to override any unsatisfactory defaults, run the
mapping tool on your persistent classes. The default <code class="literal">buildSchema
</code> mapping tool action manipulates the database schema to
match your mappings. It fails if any of your mappings don't match your object
model.
</p>
<div class="example" id="ref_guide_mapping_mappingtool_buildschema"><p class="title"><b>Example&nbsp;7.2.&nbsp;
Creating the Relational Schema from Mappings
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool Magazine.java
</pre>
</div></div><br class="example-break">
<p>
To drop the schema for a persistent class, set the mapping tool's <code class="literal">
schemaAction</code> to <code class="literal">drop</code>.
</p>
<div class="example" id="ref_guide_mapping_mappingtool_cleanup_tables"><p class="title"><b>Example&nbsp;7.3.&nbsp;
Refreshing entire schema and cleaning out tables
</b></p><div class="example-contents">
<a class="indexterm" name="d5e13733"></a>
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool -schemaAction add,deleteTableContents
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_mapping_mappingtool_dropschema"><p class="title"><b>Example&nbsp;7.4.&nbsp;
Dropping Mappings and Association Schema
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool -schemaAction drop Magazine.java
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_ddl_examples"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Generating DDL SQL
</h3></div></div></div>
<a class="indexterm" name="d5e13742"></a>
<a class="indexterm" name="d5e13745"></a>
<p>
The examples below show how to use the mapping tool to generate DDL SQL scripts,
rather than modifying the database directly.
</p>
<div class="example" id="ref_guid_mapping_ddl_full_ddl"><p class="title"><b>Example&nbsp;7.5.&nbsp;
Create DDL for Current Mappings
</b></p><div class="example-contents">
<p>
This example uses your existing mappings to determine the needed schema, then
writes the SQL to create that schema to <code class="filename">create.sql</code>.
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool -schemaAction build -sql create.sql Magazine.java
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guid_mapping_ddl_part_ddl"><p class="title"><b>Example&nbsp;7.6.&nbsp;
Create DDL to Update Database for Current Mappings
</b></p><div class="example-contents">
<p>
This example uses your existing mappings to determine the needed schema. It then
writes the SQL to add any missing tables and columns to the current schema to
<code class="filename">update.sql</code>.
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool -sql update.sql Magazine.java
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_mapping_synch"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Runtime Forward Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e13761"></a>
<a class="indexterm" name="d5e13764"></a>
<p>
You can configure OpenJPA to automatically run the mapping tool at runtime
through the <a class="link" href="#openjpa.jdbc.SynchronizeMappings" title="6.17.&nbsp; openjpa.jdbc.SynchronizeMappings"><code class="literal">
openjpa.jdbc.SynchronizeMappings</code></a> configuration property. Using
this property saves you the trouble of running the mapping tool manually, and is
meant for use during rapid test/debug cycles.
</p>
<p>
In order to enable automatic runtime mapping, you must first list all your
persistent classes as described in <a class="xref" href="#ref_guide_pc_pcclasses" title="1.&nbsp; Persistent Class List">Section&nbsp;1, &#8220;
Persistent Class List
&#8221;</a>.
</p>
<p>
OpenJPA will run the mapping tool on these classes when your application obtains
its first <code class="classname">EntityManager</code>.
</p>
<p>
The <code class="literal">openjpa.jdbc.SynchronizeMappings</code> property is a plugin
string (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) where the class
name is the mapping tool action to invoke, and the properties are the
<code class="classname">MappingTool</code> class' JavaBean properties. These properties
correspond go the long versions of the tool's command line flags.
</p>
<div class="example" id="ref_guide_mapping_synchex"><p class="title"><b>Example&nbsp;7.7.&nbsp;
Configuring Runtime Forward Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/&gt;
</pre>
<p>
The setting above corresponds to running the following command:
</p>
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool -action buildSchema -foreignKeys true
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_pc_reverse"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Reverse Mapping
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_pc_reverse_custom">2.1.
Customizing Reverse Mapping
</a></span></dt></dl></div>
<a class="indexterm" name="d5e13785"></a>
<a class="indexterm" name="d5e13787"></a>
<a class="indexterm" name="d5e13790"></a>
<p>
OpenJPA includes a <span class="emphasis"><em>reverse mapping</em></span> tool for generating
persistent class definitions, complete with metadata, from an existing database
schema. You do not have to use the reverse mapping tool to access an existing
schema; you are free to write your classes and mappings yourself, as described
in <a class="xref" href="#ref_guide_mapping_middle" title="3.&nbsp; Meet-in-the-Middle Mapping">Section&nbsp;3, &#8220;
Meet-in-the-Middle Mapping
&#8221;</a>. The reverse mapping tool,
however, can give you an excellent starting point from which to grow your
persistent classes.
</p>
<p>
To use the reverse mapping tool, follow the steps below:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
Use the <a class="link" href="#ref_guide_schema_schematool" title="13.&nbsp; Schema Tool"> schema tool</a> to
export your current schema to an XML schema file. You can skip this step and the
next step if you want to run the reverse mapping tool directly against the
database.
</p>
<div class="example" id="ref_guide_pc_reverse_schemagen"><p class="title"><b>Example&nbsp;7.8.&nbsp;
Reflection with the Schema Tool
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.jdbc.schema.SchemaTool -a reflect -f schema.xml
</pre>
</div></div><br class="example-break">
</li><li class="listitem">
<p>
Examine the generated schema file. JDBC drivers often provide incomplete or
faulty metadata, in which case the file will not exactly match the actual
schema. Alter the XML file to match the true schema. The XML format for the
schema file is described in <a class="xref" href="#ref_guide_schema_xml" title="14.&nbsp; XML Schema Format">Section&nbsp;14, &#8220;
XML Schema Format
&#8221;</a>.
</p>
<p>
After fixing any errors in the schema file, modify the XML to include foreign
keys between all relations. The schema tool will have automatically detected
existing foreign key constraints; many schemas, however, do not employ database
foreign keys for every relation. By manually adding any missing foreign keys,
you will give the reverse mapping tool the information it needs to generate the
proper relations between the persistent classes it creates.
</p>
</li><li class="listitem">
<p>
Run the reverse mapping tool on the finished schema file. If you do not supply
the schema file to reverse map, the tool will run directly against the schema in
the database. The tool can be run via its Java class,
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/ReverseMappingTool" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.ReverseMappingTool</code></a>.
</p>
<div class="example" id="ref_guide_pc_reverse_reversemappingtool"><p class="title"><b>Example&nbsp;7.9.&nbsp;
Using the Reverse Mapping Tool
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.ReverseMappingTool -pkg com.xyz -d ~/src -cp customizer.properties schema.xml
</pre>
</div></div><br class="example-break">
<p>
In addition to OpenJPA's <a class="link" href="#ref_guide_conf_devtools" title="3.&nbsp; Command Line Configuration">standard
configuration flags</a>, including
<a class="link" href="#ref_guide_conf_devtools_format" title="3.1.&nbsp; Code Formatting">code formatting options</a>,
the reverse mapping tool recognizes the following command line arguments:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-schemas/-s &lt;schema and table names&gt;</code>: A
comma-separated list of schema and table names to reverse map, if no XML schema
file is supplied. Each element of the list must follow the naming conventions
for the <code class="literal">openjpa.jdbc.Schemas</code> property described in
<a class="xref" href="#ref_guide_schema_info_list" title="12.1.&nbsp; Schemas List">Section&nbsp;12.1, &#8220;
Schemas List
&#8221;</a>. In fact, if this flag is
omitted, it defaults to the value of the <code class="literal">Schemas</code> property. If
the <code class="literal">Schemas</code> property is not defined, all schemas will be
reverse-mapped.
</p>
</li><li class="listitem">
<p>
<code class="literal">-package/-pkg &lt;package name&gt;</code>: The package name of the
generated classes. If no package name is given, the generated code will not
contain package declarations.
</p>
</li><li class="listitem">
<p>
<code class="literal">-directory/-d &lt;output directory&gt;</code>: All generated code
and metadata will be written to the directory at this path. If the path does not
match the package of a class, the package structure will be created beneath this
directory. Defaults to the current directory.
</p>
</li><li class="listitem">
<p>
<code class="literal">-metadata/-md &lt;class | package | none&gt;</code>: Specify the
level the metadata should be generated at. Defaults to generating a single
package-level metadata file. Set to <code class="literal">none</code> to disable orm.xml
generation.
</p>
</li><li class="listitem">
<p>
<code class="literal">-annotations/-ann &lt;true/t | false/f&gt;</code>: Set to
<code class="literal">true</code> to
generate JPA annotations in generated Java classes.
</p>
</li><li class="listitem">
<p>
<code class="literal">-accessType/-access &lt;field | property&gt;</code>: Change access
type for generated annotations. Defaults to field access.
</p>
</li><li class="listitem">
<p>
<code class="literal">-useSchemaName/-sn &lt;true/t | false/f&gt;</code>: Set this flag
to <code class="literal">true</code> to include the schema as well as table name in the
name of each generated class. This can be useful when dealing with multiple
schemas with same-named tables.
</p>
</li><li class="listitem">
<p>
<code class="literal">-useSchemaElement/-se &lt;true/t | false/f&gt;</code>: Set this
flag to <code class="literal">false</code> to exclude the schema name from the
<code class="literal">@Table</code> annotation in the generated class for each table.
If set to <code class="literal">false</code>, the schema name will also be removed from
the corresponding XML mapping files (orm.xml) that are generated by the tool.
The initialized value is true (in order to preserve backwards compatibility).
</p>
</li><li class="listitem">
<p>
<code class="literal">-useForeignKeyName/-fkn &lt;true/t | false/f&gt;</code>: Set this
flag to <code class="literal">true</code> if you would like field names for relations to
be based on the database foreign key name. By default, relation field names are
derived from the name of the related class.
</p>
</li><li class="listitem">
<p>
<code class="literal">-nullableAsObject/-no &lt;true/t | false/f&gt;</code>: By default,
all non-foreign key columns are mapped to primitives. Set this flag to <code class="literal">
true</code> to generate primitive wrapper fields instead for columns that
allow null values.
</p>
</li><li class="listitem">
<p>
<code class="literal">-blobAsObject/-bo &lt;true/t | false/f&gt;</code>: By default, all
binary columns are mapped to <code class="classname">byte[]</code> fields. Set this flag
to <code class="literal">true</code> to map them to <code class="classname">Object</code> fields
instead. Note that when mapped this way, the column is presumed to contain a
serialized Java object.
</p>
</li><li class="listitem">
<p>
<code class="literal">-primaryKeyOnJoin/-pkj &lt;true/t | false/f&gt;</code>: The
standard reverse mapping tool behavior is to map all tables with primary keys to
persistent classes. If your schema has primary keys on many-many join tables as
well, set this flag to <code class="literal">true</code> to avoid creating classes for
those tables.
</p>
</li><li class="listitem">
<p>
<code class="literal">-inverseRelations/-ir &lt;true/t | false/f&gt;</code>: Set to
<code class="literal">false</code> to prevent the creation of inverse 1-many/1-1 relations
for every many-1/1-1 relation detected.
</p>
</li><li class="listitem">
<p>
<code class="literal">-useGenericCollections/-gc &lt;true/t | false/f&gt;</code>: Set to
true to use generic collections on OneToMany and ManyToMany relations.
</p>
</li><li class="listitem">
<p>
<code class="literal">-useDatastoreIdentity/-ds &lt;true/t | false/f&gt;</code>: Set to
<code class="literal">true</code> to use datastore identity for tables that have single
numeric primary key columns. The tool typically uses application identity for
all generated classes.
</p>
</li><li class="listitem">
<p>
<code class="literal">-useBuiltinIdentityClass/-bic &lt;true/t | false/f&gt;</code>: Set
to <code class="literal">false</code> to prevent the tool from using built-in application
identity classes when possible. This will force the tool to create custom
application identity classes even when there is only one primary key column.
</p>
</li><li class="listitem">
<p>
<code class="literal">-innerIdentityClasses/-inn &lt;true/t | false/f&gt;</code>: Set to
<code class="literal">true</code> to have any generated application identity classes be
created as static inner classes within the persistent classes. Defaults to
<code class="literal">false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-identityClassSuffix/-is &lt;suffix&gt;</code>: Suffix to append to
class names to form application identity class names, or for inner identity
classes, the inner class name. Defaults to <code class="literal">Id</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-typeMap/-typ &lt;type mapping&gt;</code>: A string that specifies
the default Java classes to generate for each SQL type that is seen in the
schema. The format is <code class="literal"> SQLTYPE1=JavaClass1,SQLTYPE2=JavaClass2
</code>. The SQL type name first looks for a customization based on <code class="literal">
SQLTYPE(SIZE,PRECISION)</code>, then <code class="literal">SQLTYPE(SIZE)</code>, then
<code class="literal">SQLTYPE</code>. So if a column whose type name is
<code class="literal">CHAR</code> is found, it will first look for the <code class="literal">
CHAR(50,0)</code> type name specification, then it will look for <code class="literal">
CHAR(50)</code>, and finally it will just look for <code class="literal">CHAR</code>.
For example, to generate a char array for every <code class="literal">CHAR</code> column
whose size is exactly 50, and to generate a <code class="literal">short</code> for every
type name of <code class="literal">INTEGER</code>, you might specify: <code class="literal">
CHAR(50)=char[],INTEGER=short</code>. Note that since various databases
report different type names differently, one database's type name specification
might not work for another database. Enable <code class="literal">TRACE</code> level
logging on the <code class="literal">MetaData</code> channel to track which type names
OpenJPA is examining.
</p>
</li><li class="listitem">
<p>
<code class="literal">-customizerClass/-cc &lt;class name&gt;</code>: The full class name
of a
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/ReverseCustomizer.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.ReverseCustomizer</code></a>
customization plugin. If you do not specify a reverse customizer of your own,
the system defaults to a
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/PropertiesReverseCustomizer.html" target="_top">
<code class="classname">PropertiesReverseCustomizer</code></a>. This customizer
allows you to specify simple customization options in the properties file given
with the <code class="literal">-customizerProperties</code> flag below. We present the
available property keys <a class="link" href="#ref_guide_pc_reverse_custom" title="2.1.&nbsp; Customizing Reverse Mapping">
below</a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">-customizerProperties/-cp &lt;properties file or resource&gt;</code>
: The path or resource name of a properties file to pass to the reverse
customizer on initialization.
</p>
</li><li class="listitem">
<p>
<code class="literal">-customizer./-c.&lt;property name&gt; &lt;property value&gt;</code>
: The given property name will be matched with the corresponding Java bean
property in the specified reverse customizer, and set to the given value.
</p>
</li></ul></div>
<p>
Running the tool will generate <code class="filename">.java</code> files for each
generated class (and its application identity class, if applicable), along with
JPA annotations (if enabled by setting <code class="literal">-annotations true</code>),
or an <code class="filename">orm.xml</code> file (if not disabled with <code class="literal">
-metadata none</code>) containing the corresponding persistence metadata.
</p>
</li><li class="listitem">
<p>
Examine the generated class, metadata, and mapping information, and modify it as
necessary. Remember that the reverse mapping tool only provides a starting
point, and you are free to make whatever modifications you like to the code it
generates.
</p>
<p>
After you are satisfied with the generated classes and their mappings, you
should first compile the classes with <code class="literal">javac</code>, <code class="literal">
jikes</code>, or your favorite Java compiler. Make sure the classes are
located in the directory corresponding to the <code class="literal">-package</code> flag
you gave the reverse mapping tool. Next, if you have generated an <code class="filename">
orm.xml</code>, move that file to a <code class="filename">META-INF</code> directory
within a directory in your classpath. Finally, enhance the classes
if necessary (see <a class="xref" href="#ref_guide_pc_enhance" title="2.&nbsp; Enhancement">Section&nbsp;2, &#8220;
Enhancement
&#8221;</a>).
</p>
</li></ol></div>
<p>
Your persistent classes are now ready to access your existing schema.
</p>
<div class="section" id="ref_guide_pc_reverse_custom"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
Customizing Reverse Mapping
</h3></div></div></div>
<p>
The <code class="classname">org.apache.openjpa.jdbc.meta.ReverseCustomizer</code> plugin
interface allows you to customize the reverse mapping process. See the class
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/ReverseCustomizer.html" target="_top">
Javadoc</a> for details on the hooks that this interface provides. Specify
the concrete plugin implementation to use with the <code class="literal">
-customizerClass/-cc</code> command-line flag, described in the preceding
section.
</p>
<p>
By default, the reverse mapping tool uses a
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/PropertiesReverseCustomizer.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.PropertiesReverseCustomizer</code>
</a>. This customizer allows you to perform relatively simple
customizations through the properties file named with the <code class="literal">
-customizerProperties</code> tool flag. The customizer recognizes the
following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">&lt;table name&gt;.table-type &lt;type&gt;</code>: Override the
default type of the table with name <code class="literal">&lt;table name&gt;</code>.
Legal values are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">base</code>: Primary table for a base class.
</p>
</li><li class="listitem">
<p>
<code class="literal">secondary</code>: Secondary table for a class. The table must have
a foreign key joining to a class table.
</p>
</li><li class="listitem">
<p>
<code class="literal">secondary-outer</code>: Outer-joined secondary table for a class.
The table must have a foreign key joining to a class table.
</p>
</li><li class="listitem">
<p>
<code class="literal">association</code>: Association table. The table must have two
foreign keys to class tables.
</p>
</li><li class="listitem">
<p>
<code class="literal">collection</code>: Collection table. The table must have one
foreign key to a class table and one data column.
</p>
</li><li class="listitem">
<p>
<code class="literal">subclass</code>: A joined subclass table. The table must have a
foreign key to the superclass' table.
</p>
</li><li class="listitem">
<p>
<code class="literal">none</code>: The table should not be reverse-mapped.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<code class="literal">&lt;class name&gt;.rename &lt;new class name&gt;</code>: Override
the given tool-generated name <code class="literal">&lt;class name&gt;</code> with a new
value. Use full class names, including package. You are free to rename a class
to a new package. Specify a value of <code class="literal">none</code> to reject the class
and leave the corresponding table unmapped.
</p>
</li><li class="listitem">
<p>
<code class="literal">&lt;table name&gt;.class-name &lt;new class name&gt;</code>: Assign
the given fully-qualified class name to the type created from the table with
name <code class="literal">&lt;table name&gt;</code>. Use a value of <code class="literal">none
</code> to prevent reverse mapping this table. This property can be used in
place of the <code class="literal">rename</code> property.
</p>
</li><li class="listitem">
<p>
<code class="literal">&lt;class name&gt;.identity &lt;datastore | builtin | identity class
name&gt;</code>: Set this property to <code class="literal">datastore</code> to use
datastore identity for the class <code class="literal">&lt;class name&gt;</code>,
<code class="literal">builtin</code> to use a built-in identity class, or the desired
application identity class name. Give full class names, including package. You
are free to change the package of the identity class this way. If the persistent
class has been renamed, use the new class name for this property key. Remember
that datastore identity requires a table with a single numeric primary key
column, and built-in identity requires a single primary key column of any type.
</p>
</li><li class="listitem">
<p>
<code class="literal">&lt;class name&gt;.&lt;field name&gt;.rename &lt;new field name&gt;
</code>: Override the tool-generated <code class="literal">&lt;field name&gt;</code> in
class <code class="literal">&lt;class name&gt;</code> with the given name. Use the field
owner's full class name in the property key. If the field owner's class was
renamed, use the new class name. The property value should be the new field
name, without the preceding class name. Use a value of <code class="literal">none</code>
to reject the generated mapping and remove the field from the class.
</p>
</li><li class="listitem">
<p>
<code class="literal">&lt;table name&gt;.&lt;column name&gt;.field-name &lt;new field
name&gt;</code>: Set the generated field name for the <code class="literal">&lt;table
name&gt;</code> table's <code class="literal">&lt;column name&gt;</code> column. If
this is a multi-column mapping, any of the columns can be used. Use a value of
<code class="literal">none</code> to prevent the column and its associated columns from
being reverse-mapped.
</p>
</li><li class="listitem">
<p>
<code class="literal">&lt;class name&gt;.&lt;field name&gt;.type &lt;field type&gt;</code>
: The type to give the named field. Use full class names. If the field or the
field's owner class has been renamed, use the new name.
</p>
</li><li class="listitem">
<p>
<code class="literal">&lt;class name&gt;.&lt;field name&gt;.value</code>: The initial
value for the named field. The given string will be placed as-is in the
generated Java code, so be sure it is valid Java. If the field or the field's
owner class has been renamed, use the new name.
</p>
</li></ul></div>
<p>
All property keys are optional; if not specified, the customizer keeps the
default value generated by the reverse mapping tool.
</p>
<div class="example" id="ref_guide_pc_reverse_custom_ex"><p class="title"><b>Example&nbsp;7.10.&nbsp;
Customizing Reverse Mapping with Properties
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.ReverseMappingTool -pkg com.xyz -cp custom.properties schema.xml
</pre>
<p>
Example <code class="filename">custom.properties</code>:
</p>
<pre class="programlisting">
com.xyz.TblMagazine.rename: com.xyz.Magazine
com.xyz.TblArticle.rename: com.xyz.Article
com.xyz.TblPubCompany.rename: com.xyz.pub.Company
com.xyz.TblSysInfo.rename: none
com.xyz.Magazine.allArticles.rename: articles
com.xyz.Magazine.articles.type: java.util.Collection
com.xyz.Magazine.articles.value: new TreeSet()
com.xyz.Magazine.identity: datastore
com.xyz.pub.Company.identity: com.xyz.pub.CompanyId
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_mapping_middle"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Meet-in-the-Middle Mapping
</h2></div></div></div>
<a class="indexterm" name="d5e14024"></a>
<a class="indexterm" name="d5e14026"></a>
<a class="indexterm" name="d5e14029"></a>
<p>
In the <span class="emphasis"><em>meet-in-the-middle</em></span>
mapping approach, you control both the relational model and the object model. It
is up to you to define the mappings between these models. The mapping
tool's <code class="literal">validate</code> action is useful to meet-in-the-middle
mappers. This action verifies that the mapping information for a class matches
the class definition and the existing schema. It throws an informative exception
when your mappings are incorrect.
</p>
<div class="example" id="ref_guide_mapping_mappingtool_validate"><p class="title"><b>Example&nbsp;7.11.&nbsp;
Validating Mappings
</b></p><div class="example-contents">
<pre class="programlisting">
java org.apache.openjpa.jdbc.meta.MappingTool -action validate Magazine.java
</pre>
</div></div><br class="example-break">
<p>
The <code class="literal">buildSchema</code> action we discussed in
<a class="xref" href="#ref_guide_mapping_mappingtool" title="1.&nbsp; Forward Mapping">Section&nbsp;1, &#8220;
Forward Mapping
&#8221;</a> is also somewhat useful
during meet-in-the-middle mapping. Unlike the <code class="literal">validate</code>
action, which throws an exception if your mapping data does not match the
existing schema, the <code class="literal">buildSchema</code> action assumes your mapping
data is correct, and modifies the schema to match your mappings. This lets you
modify your mapping data manually, but saves you the hassle of using your
database's tools to bring the schema up-to-date.
</p>
</div>
<div class="section" id="ref_guide_mapping_defaults"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Mapping Defaults
</h2></div></div></div>
<a class="indexterm" name="d5e14046"></a>
<a class="indexterm" name="d5e14048"></a>
<p>
The previous sections showed how to use the mapping tool to generate default
mappings. But how does the mapping tool know what mappings to generate? The
answer lies in the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/MappingDefaults.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.MappingDefaults</code></a>
interface. OpenJPA uses an instance of this interface to decide how to name
tables and columns, where to put foreign keys, and generally how to create a
schema that matches your object model.
</p>
<div class="important" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Important</h3>
<p>
OpenJPA relies on foreign key constraint information at runtime to order SQL
appropriately. Be sure to set your mapping defaults to reflect your existing
database constraints, set the schema factory to reflect on the database for
constraint information (see <a class="xref" href="#ref_guide_schema_info_factory" title="12.2.&nbsp; Schema Factory">Section&nbsp;12.2, &#8220;
Schema Factory
&#8221;</a>),
or use explicit foreign key mappings as described in
<a class="xref" href="#ref_guide_mapping_jpa_fk" title="7.9.2.&nbsp; Foreign Keys">Section&nbsp;7.9.2, &#8220;
Foreign Keys
&#8221;</a>.
</p>
</div>
<p>
The <a class="link" href="#openjpa.jdbc.MappingDefaults" title="6.8.&nbsp; openjpa.jdbc.MappingDefaults"><code class="literal">
openjpa.jdbc.MappingDefaults</code></a> configuration property controls
the <code class="classname">MappingDefaults</code> interface implementation in use. This
is a plugin property (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>), so
you can substitute your own implementation or configure the existing ones.
OpenJPA includes the following standard implementations:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">jpa</code>: Provides defaults in compliance with the JPA standard.
This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/PersistenceMappingDefaults.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.PersistenceMappingDefaults
</code></a> class. This class extends the <code class="classname">
MappingDefaultsImpl</code> class described below, so it has all the same
properties (though with different default values), as well as:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">PrependFieldNameToJoinTableInverseJoinColumns</code>: Whether to
prepend the owning field name to the names of inverse join columns in join
tables. Defaults to true per the JPA specification. Set to false for
compatibility with older OpenJPA versions which did not prepend the field name.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<code class="literal">default</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/MappingDefaultsImpl.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.MappingDefaultsImpl</code></a>
class. This default implementation is highly configurable. It has the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">DefaultMissingInfo</code>: Whether to default missing column and
table names rather than throw an exception. If set to false, full explicit
mappings are required at runtime and when using mapping tool actions like
<code class="literal">buildSchema</code> and <code class="literal">validate</code>.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e14088"></a>
<code class="literal">RemoveHungarianNotation</code>: Switches on/off removal of
Hungarian notation when generating column names.
Fields such as <code class="literal">mFoobar</code> and <code class="literal">strBarFoo</code>
would become columns named <code class="literal">foobar</code> and
<code class="literal">barfoo</code> respectively. OpenJPA will search for the first
instance of a uppercase character in the field name and then truncate the
column name to remove anything before it.
</p>
</li><li class="listitem">
<p>
<code class="literal">BaseClassStrategy</code>: The default mapping strategy for base
classes. You can specify a built-in strategy alias or the full class name of a
<a class="link" href="#ref_guide_mapping_custom_class" title="10.1.&nbsp; Custom Class Mapping">custom class strategy</a>.
You can also use OpenJPA's plugin format (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) to pass arguments to the
strategy instance. See the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/strats/package-summary.html" target="_top">
<code class="literal">org.apache.openjpa.jdbc.meta.strats</code></a> package for
available strategies.
</p>
</li><li class="listitem">
<p>
<code class="literal">SubclassStrategy</code>: The default mapping strategy for
subclasses. You can specify a builtin strategy alias or the full class name of a
<a class="link" href="#ref_guide_mapping_custom_class" title="10.1.&nbsp; Custom Class Mapping"> custom class strategy</a>.
You can also use OpenJPA's plugin format (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) to pass arguments to the
strategy instance. Common strategies are <code class="literal">vertical</code> and
<code class="literal">flat</code>, the default. See the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/strats/package-summary.html" target="_top">
<code class="literal">org.apache.openjpa.jdbc.meta.strats</code></a> package for all
available strategies.
</p>
</li><li class="listitem">
<p>
<code class="literal">VersionStrategy</code>: The default version strategy for classes
without a version field. You can specify a builtin strategy alias or the full
class name of a <a class="link" href="#ref_guide_mapping_custom_versdiscrim" title="10.2.&nbsp; Custom Discriminator and Version Strategies"> custom
version strategy</a>. You can also use OpenJPA's plugin format (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) to pass arguments to the
strategy instance. Common strategies are <code class="literal">none</code>, <code class="literal">
state-comparison</code>, <code class="literal"> timestamp</code>, and <code class="literal">
version-number</code>, the default. See the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/strats/package-summary.html" target="_top">
<code class="literal">org.apache.openjpa.jdbc.meta.strats</code></a> package for all
available strategies.
</p>
</li><li class="listitem">
<p>
<code class="literal">DiscriminatorStrategy</code>: The default discriminator strategy
when no discriminator value is given. You can specify a builtin strategy alias
or the full class name of a
<a class="link" href="#ref_guide_mapping_custom_versdiscrim" title="10.2.&nbsp; Custom Discriminator and Version Strategies"> custom discriminator
strategy</a>. You can also use OpenJPA's plugin format (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) to pass arguments to the
strategy instance. Common strategies are <code class="literal">final</code> for a base
class without subclasses, <code class="literal">none</code> to use joins to subclass
tables rather than a discriminator column, and <code class="literal"> class-name</code>,
the default. See the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/strats/package-summary.html" target="_top">
<code class="literal">org.apache.openjpa.jdbc.meta.strats</code></a> package for all
available strategies.
</p>
</li><li class="listitem">
<p>
<code class="literal">FieldStrategies</code>: This property associates field types with
custom strategies. The format of this property is similar to that of plugin
strings (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a> ), without the class
name. It is a comma-separated list of key/value pairs, where each key is a
possible field type, and each value is itself a plugin string describing the
strategy for that type. We present an example below. See
<a class="xref" href="#ref_guide_mapping_custom_field" title="10.3.&nbsp; Custom Field Mapping">Section&nbsp;10.3, &#8220;
Custom Field Mapping
&#8221;</a> for information on custom
field strategies.
</p>
</li><li class="listitem">
<p>
<code class="literal">ForeignKeyDeleteAction</code>: The default delete action of foreign
keys representing relations to other objects. Recognized values include
<code class="literal">restrict</code>, <code class="literal">cascade</code>, <code class="literal">null</code>
, <code class="literal">default</code>. These values correspond exactly to the standard
database foreign key actions of the same names.
</p>
<p>
The value <code class="literal">none</code> tells OpenJPA not to create database foreign
keys on relation columns. This is the default.
</p>
</li><li class="listitem">
<p>
<code class="literal">JoinForeignKeyDeleteAction</code>: The default delete action of
foreign keys that join secondary, collection, map, or subclass tables to
the primary table. Accepts the same values as the <code class="literal">
ForeignKeyDeleteAction</code> property above.
</p>
</li><li class="listitem">
<p>
<code class="literal">DeferConstraints</code>: Whether to use deferred database
constraints if possible. Defaults to false.
</p>
</li><li class="listitem">
<p>
<code class="literal">IndexLogicalForeignKeys</code>: Boolean property controlling
whether to create indexes on logical foreign keys. Logical foreign keys are
columns that represent a link between tables, but have been configured through
the <code class="literal">ForeignKey</code> properties above not to use a physical
database foreign key. Defaults to true.
</p>
</li><li class="listitem">
<p>
<code class="literal">DataStoreIdColumnName</code>: The default name of datastore
identity columns.
</p>
</li><li class="listitem">
<p>
<code class="literal">DiscriminatorColumnName</code>: The default name of discriminator
columns.
</p>
</li><li class="listitem">
<p>
<code class="literal">IndexDiscriminator</code>: Whether to index the discriminator
column. Defaults to true.
</p>
</li><li class="listitem">
<p>
<code class="literal">VersionColumnName</code>: The default name of version columns.
</p>
</li><li class="listitem">
<p>
<code class="literal">IndexVersion</code>: Whether to index the version column. Defaults
to false.
</p>
</li><li class="listitem">
<p>
<code class="literal">AddNullIndicator</code>: Whether to create a synthetic null
indicator column for embedded mappings. The null indicator column allows OpenJPA
to distinguish between a null embedded object and one with default values for
all persistent fields.
</p>
</li><li class="listitem">
<p>
<code class="literal">NullIndicatorColumnName</code>: The default name of synthetic null
indicator columns for embedded objects.
</p>
</li><li class="listitem">
<p>
<code class="literal">OrderLists</code>: Whether to create a database ordering column for
maintaining the order of persistent lists and arrays.
</p>
</li><li class="listitem">
<p>
<code class="literal">OrderColumnName</code>: The default name of collection and array
ordering columns.
</p>
</li><li class="listitem">
<p>
<code class="literal">StoreEnumOrdinal</code>: Set to true to store enum fields as
numeric ordinal values in the database. The default is to store the enum value
name as a string, which is more robust if the Java enum declaration might be
rearranged.
</p>
</li><li class="listitem">
<p>
<code class="literal">StoreUnmappedObjectIdString</code>: Set to true to store the
stringified identity of related objects when the declared related type is
unmapped. By default, OpenJPA stores the related object's primary key value(s).
However, this breaks down if different subclasses of the related type use
incompatible primary key structures. In that case, stringifying the identity
value is the better choice.
</p>
</li></ul></div>
</li></ul></div>
<p>
The example below turns on foreign key generation during schema creation and
associates the <code class="classname">org.mag.data.InfoStruct</code> field type with
the custom <code class="classname">org.mag.mapping.InfoStructHandler</code> value
handler.
</p>
<div class="example" id="ref_guide_mapping_defaults_conf"><p class="title"><b>Example&nbsp;7.12.&nbsp;
Configuring Mapping Defaults
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,
FieldStrategies='org.mag.data.InfoStruct=org.mag.mapping.InfoStructHandler'"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_mapping_factory"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Mapping Factory
</h2></div></div></div>
<a class="indexterm" name="d5e14198"></a>
<a class="indexterm" name="d5e14200"></a>
<p>
An important decision in the object-relational mapping process is how and where
to store the data necessary to map your persistent classes to the database
schema.
</p>
<p>
<a class="xref" href="#ref_guide_meta_factory" title="1.&nbsp; Metadata Factory">Section&nbsp;1, &#8220;
Metadata Factory
&#8221;</a> introduced OpenJPA's <code class="classname">
MetaDataFactory</code> interface. OpenJPA uses this same interface to
abstract the storage and retrieval of mapping information. OpenJPA includes the
built-in mapping factories below, and you can create your own factory if you
have custom needs. You control which mapping factory OpenJPA uses with the
<a class="link" href="#openjpa.jdbc.MappingFactory" title="6.9.&nbsp; openjpa.jdbc.MappingFactory"><code class="literal">
openjpa.jdbc.MappingFactory</code></a> configuration property.
</p>
<p>
The bundled mapping factories are:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">-</code>: Leaving the <code class="literal"> openjpa.jdbc.MappingFactory
</code> property unset allows your metadata factory to take over mappings as
well. If you are using the default <code class="literal">jpa</code> metadata factory,
OpenJPA will read mapping information from your annotations and
<code class="filename">orm.xml</code> when you leave the mapping factory unspecified.
</p>
</li></ul></div>
<div class="example" id="ref_guide_mapping_factory_jpa"><p class="title"><b>Example&nbsp;7.13.&nbsp;
Standard JPA Configuration
</b></p><div class="example-contents">
<p>
In the standard JPA configuration, the mapping factory is left unset.
</p>
<pre class="programlisting">
&lt;property name="openjpa.MetaDataFactory" value="jpa"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_mapping_notes_nonstdjoins"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
Non-Standard Joins
</h2></div></div></div>
<a class="indexterm" name="d5e14224"></a>
<p>
The JPA Overview's <a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a> explains join
mapping. All of the examples in that document, however, use "standard" joins, in
that there is one foreign key column for each primary key column in the target
table. OpenJPA supports additional join patterns, including partial primary key
joins, non-primary key joins, and joins using constant values.
</p>
<p>
<a class="indexterm" name="d5e14230"></a>
In a partial primary key join, the source table only has foreign key columns for
a subset of the primary key columns in the target table. So long as this subset
of columns correctly identifies the proper row(s) in the referenced table,
OpenJPA will function properly. There is no special syntax for expressing a
partial primary key join - just do not include column definitions for missing
foreign key columns.
</p>
<p>
<a class="indexterm" name="d5e14234"></a>
In a non-primary key join, at least one of the target columns is not a primary
key. Once again, OpenJPA supports this join type with the same syntax as a
primary key join. There is one restriction, however: each non-primary key column
you are joining to must be controlled by a field mapping that implements the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/Joinable.html" target="_top"><code class="classname">
org.apache.openjpa.jdbc.meta.Joinable</code></a> interface. All built
in basic mappings implement this interface, including basic fields of embedded
objects. OpenJPA will also respect any custom mappings that implement this
interface. See <a class="xref" href="#ref_guide_mapping_custom" title="10.&nbsp; Custom Mappings">Section&nbsp;10, &#8220;
Custom Mappings
&#8221;</a> for an
examination of custom mappings.
</p>
<p>
<a class="indexterm" name="d5e14241"></a>
Not all joins consist of only links between columns. In some cases you might
have a schema in which one of the join criteria is that a column in the source
or target table must have some constant value. OpenJPA calls joins involving
constant values <span class="emphasis"><em>constant joins</em></span>.
</p>
<p>
To form a constant join in JPA mapping, first set the <code class="literal">JoinColumn
</code>'s <code class="literal">name</code> attribute to the name of the column. If the
column with the constant value is the target of the join, give its fully
qualified name in the form <code class="literal">&lt;table name&gt;.&lt;column name&gt;
</code>. Next, set the <code class="literal">referencedColumnName</code> attribute to
the constant value. If the constant value is a string, place it in single quotes
to differentiate it from a column name.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="285"><tr><td><img src="img/joins-constant.png"></td></tr></table></div>
<p>
Consider the tables above. First, we want to join row <code class="literal">T1.R1</code>
to row <code class="literal">T2.R1</code>. If we just join column <code class="literal">T1.FK</code>
to <code class="literal">T2.PK1</code>, we will wind up matching both <code class="literal">T2.R1
</code> and <code class="literal"> T2.R2</code>. So in addition to joining <code class="literal">
T1.FK</code> to <code class="literal">T2.PK1</code>, we also have to specify that
<code class="literal">T2.PK2</code> has the value <code class="literal">a</code>. Here is how we'd
accomplish this in mapping metadata.
</p>
<pre class="programlisting">
@Entity
@Table(name="T1")
public class ... {
@ManyToOne
@JoinColumns({
@JoinColumn(name="FK" referencedColumnName="PK1"),
@JoinColumn(name="T2.PK2" referencedColumnName="'a'")
});
private ...;
}
</pre>
<p>
Notice that we had to fully qualify the name of column <code class="literal">PK2</code>
because it is in the target table. Also notice that we put single quotes around
the constant value so that it won't be confused with a column name. You do not
need single quotes for numeric constants. For example, the syntax to join
<code class="literal">T1.R2</code> to <code class="literal">T2.R4</code> is:
</p>
<pre class="programlisting">
@Entity
@Table(name="T1")
public class ... {
@ManyToOne
@JoinColumns({
@JoinColumn(name="FK" referencedColumnName="PK2"),
@JoinColumn(name="T2.PK1" referencedColumnName="2")
});
private ...;
}
</pre>
<p>
Finally, from the inverse direction, these joins would look like this:
</p>
<pre class="programlisting">
@Entity
@Table(name="T2")
public class ... {
@ManyToOne
@JoinColumns({
@JoinColumn(name="T1.FK" referencedColumnName="PK1"),
@JoinColumn(name="PK2" referencedColumnName="'a'")
});
private ...;
@ManyToOne
@JoinColumns({
@JoinColumn(name="T1.FK" referencedColumnName="PK2"),
@JoinColumn(name="PK1" referencedColumnName="2")
});
private ...;
}
</pre>
</div>
<div class="section" id="ref_guide_mapping_jpa"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
Additional JPA Mappings
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_jpa_datastoreid">7.1.
Datastore Identity Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_version">7.2.
Surrogate Version Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_columns">7.3.
Multi-Column Mappings
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fieldjoin">7.4.
Join Column Attribute Targets
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_embed">7.5.
Embedded Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll">7.6.
Collections
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_table">7.6.1.
Container Table
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_joincols">7.6.2.
Element Join Columns
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_order">7.6.3.
Order Column
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_onemany">7.7.
One-Sided One-Many Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map">7.8.
Maps
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keycols">7.8.1. Key Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keyjoincols">7.8.2. Key Join Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_embedkey">7.8.3. Key Embedded Mapping</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_ex">7.8.4. Examples</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_jpa_constraints">7.9.
Indexes and Constraints
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_jpa_index">7.9.1.
Indexes
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fk">7.9.2.
Foreign Keys
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_unique">7.9.3.
Unique Constraints
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_xmlmapping">7.10.
XML Column Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_streamsupport">7.11.
LOB Streaming
</a></span></dt></dl></div>
<a class="indexterm" name="d5e14274"></a>
<p>
OpenJPA supports many persistence strategies beyond those of the JPA
specification. <a class="xref" href="#ref_guide_meta_jpa" title="3.&nbsp; Additional JPA Metadata">Section&nbsp;3, &#8220;
Additional JPA Metadata
&#8221;</a> covered the logical
metadata for OpenJPA's additional persistence strategies. We now demonstrate how
to map entities using these strategies to the database.
</p>
<div class="section" id="ref_guide_mapping_jpa_datastoreid"><div class="titlepage"><div><div><h3 class="title">7.1.&nbsp;
Datastore Identity Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e14281"></a>
<a class="indexterm" name="d5e14284"></a>
<a class="indexterm" name="d5e14288"></a>
<a class="indexterm" name="d5e14291"></a>
<p>
<a class="xref" href="#ref_guide_pc_oid" title="4.&nbsp; Object Identity">Section&nbsp;4, &#8220;
Object Identity
&#8221;</a> describes how to use datastore identity
in JPA. OpenJPA requires a single numeric primary key column to hold datastore
identity values. The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/DataStoreIdColumn.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.DataStoreIdColumn</code>
</a> annotation customizes the datastore identity column. This annotation
has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: Defaults to <code class="literal">ID</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">int precision</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">String columnDefinition</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean insertable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean updatable</code>
</p>
</li></ul></div>
<p>
All properties correspond exactly to the same-named properties on the standard
<code class="classname">Column</code> annotation, described in
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a>.
</p>
<div class="example" id="ref_guide_mapping_jpa_datastoreidex"><p class="title"><b>Example&nbsp;7.14.&nbsp;
Datastore Identity Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
import org.apache.openjpa.persistence.jdbc.*;
@Entity
@Table(name="LOGS")
@DataStoreIdColumn(name="ENTRY")
public class LogEntry {
@Lob
private String content;
...
}
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_mapping_jpa_version"><div class="titlepage"><div><div><h3 class="title">7.2.&nbsp;
Surrogate Version Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e14322"></a>
<a class="indexterm" name="d5e14325"></a>
<a class="indexterm" name="d5e14329"></a>
<p>
OpenJPA supports version fields as defined by the JPA specification, but allows
you to use a surrogate version column in place of a version field if you like.
You map the surrogate version column with the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/VersionColumn.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.VersionColumn</code></a>
annotation. You can also use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/VersionColumns.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.VersionColumns</code>
</a> annotation to declare an array of <code class="classname">VersionColumn</code>
values. Each <code class="classname">VersionColumn</code> has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: Defaults to <code class="literal">VERSN</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">String table</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">int length</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">int precision</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">int scale</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">String columnDefinition</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean nullable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean insertable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean updatable</code>
</p>
</li></ul></div>
<p>
All properties correspond exactly to the same-named properties on the standard
<code class="classname">Column</code> annotation, described in
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a>.
</p>
<p>
By default, OpenJPA assumes that surrogate versioning uses a version number
strategy. You can choose a different strategy with the <code class="classname">
VersionStrategy</code> annotation described in
<a class="xref" href="#version-strategy" title="9.1.4.&nbsp; Version Strategy">Section&nbsp;9.1.4, &#8220;
Version Strategy
&#8221;</a>.
</p>
<p>
If multiple columns are used for surrogate versioning, then each column,
by default, uses a version number. But column definition for each version
column can be set independently to other numeric types. The version values are
compared to detect optimistic concurrent modification. Such comparison must
determine whether a version value <code class="literal">v1</code> represents an earlier,
later or same with respect to another version value <code class="literal">v2</code>. While
result of such comparison is obvious for a single numeric column that
monotonically increases on each update, the same is not true when version value
is an array of numbers. By default, OpenJPA compares a version
<code class="literal">v1</code> as later than another version <code class="literal">v2</code>,
if any array element of <code class="literal">v1</code> is
later than the corresponding element of <code class="literal">v2</code>.
<code class="literal">v1</code> is equal to <code class="literal">v2</code> if every array element
is equal and <code class="literal">v1</code> is earlier to <code class="literal">v1</code> if some
elements of <code class="literal">v1</code> are earlier and rest are equal to corresponding
element of <code class="literal">v2</code>.
</p>
<p>
Multiple surrogate version columns can be spread across primary and secondary
tables. For example, following example shows 3 version columns
<code class="literal">v01, v11, v12, v21</code> defined across the primary and secondary tables of
a persistent entity
</p>
<pre class="programlisting">
@Entity
@Table(name="PRIMARY")
@SecondaryTables({
@SecondaryTable(name = "SECONDARY_1"),
@SecondaryTable(name = "SECONDARY_2")
})
@VersionStrategy("version-numbers")
@VersionColumns({
@VersionColumn(name = "v01") // default is the PRIMARY table
@VersionColumn(name = "v11", table="SECONDARY_1", columnDefinition="FLOAT", scale=3, precision=10),
@VersionColumn(name = "v12", table="SECONDARY_1"),
@VersionColumn(name = "v21", table="SECONDARY_2"),
})
</pre>
</div>
<div class="section" id="ref_guide_mapping_jpa_columns"><div class="titlepage"><div><div><h3 class="title">7.3.&nbsp;
Multi-Column Mappings
</h3></div></div></div>
<a class="indexterm" name="d5e14392"></a>
<a class="indexterm" name="d5e14395"></a>
<a class="indexterm" name="d5e14398"></a>
<p>
OpenJPA makes it easy to create multi-column
<a class="link" href="#ref_guide_mapping_custom_field" title="10.3.&nbsp; Custom Field Mapping">custom mappings</a>. The JPA
specification includes a <code class="classname">Column</code> annotation, but is
missing a way to declare multiple columns for a single field. OpenJPA remedies
this with the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Columns.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Columns</code></a>
annotation, which contains an array of <code class="classname">Column</code> values.
</p>
<p>
Remember to annotate custom field types with <code class="classname">Persistent</code>,
as described in <a class="xref" href="#ref_guide_meta_jpa_persistent" title="3.3.&nbsp; Persistent Field Values">Section&nbsp;3.3, &#8220;
Persistent Field Values
&#8221;</a>.
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_fieldjoin"><div class="titlepage"><div><div><h3 class="title">7.4.&nbsp;
Join Column Attribute Targets
</h3></div></div></div>
<p>
<a class="xref" href="#jpa_overview_mapping_rel" title="8.4.&nbsp; Direct Relations">Section&nbsp;8.4, &#8220;
Direct Relations
&#8221;</a> in the JPA Overview introduced
you to the <code class="classname">JoinColumn</code> annotation. A <code class="classname">
JoinColumn</code>'s <code class="literal"> referencedColumnName</code> property
declares which column in the table of the related type this join column links
to. Suppose, however, that the related type is unmapped, or that it is part of a
table-per-class inheritance hierarchy. Each subclass that might be assigned to
the field could reside in a different table, and could use entirely different
names for its primary key columns. It becomes impossible to supply a single
<code class="literal">referencedColumnName</code> that works for all subclasses.
</p>
<p>
OpenJPA rectifies this by allowing you to declare which <span class="emphasis"><em>attribute
</em></span> in the related type each join column links to, rather than which
column. If the attribute is mapped differently in various subclass tables,
OpenJPA automatically forms the proper join for the subclass record at hand. The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/XJoinColumn.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.XJoinColumn</code></a>
annotation has all the same properties as the standard <code class="classname">JoinColumn
</code> annotation, but adds an additional <code class="literal">
referencedAttributeName</code> property for this purpose. Simply use a
<code class="classname">XJoinColumn</code> in place of a <code class="classname">JoinColumn
</code> whenever you need to access this added functionality.
</p>
<p>
For compound keys, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/XJoinColumns.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.XJoinColumns</code></a>
annotation. The value of this annotation is an array of individual <code class="classname">
XJoinColumn</code>s.
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_embed"><div class="titlepage"><div><div><h3 class="title">7.5.&nbsp;
Embedded Mapping
</h3></div></div></div>
<p>
JPA uses the <code class="classname">AttributeOverride</code> annotation to override the
default mappings of an embeddable class. The JPA Overview details this process
in <a class="xref" href="#jpa_overview_mapping_embed" title="8.3.&nbsp; Embedded Mapping">Section&nbsp;8.3, &#8220;
Embedded Mapping
&#8221;</a>. <code class="classname">
AttributeOverride</code>s suffice for simple mappings, but do not allow
you to override complex mappings. Also, JPA has no way to differentiate between
a null embedded object and one with default values for all of its fields.
</p>
<p>
OpenJPA overcomes these shortcomings with the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/EmbeddedMapping.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.EmbeddedMapping</code>
</a> annotation. This annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String nullIndicatorColumnName</code>: If the named column's value
is <code class="literal">NULL</code>, then the embedded object is assumed to be null. If
the named column has a non- <code class="literal">NULL</code> value, then the embedded
object will get loaded and populated with data from the other embedded fields.
This property is entirely optional. By default, OpenJPA always assumes the
embedded object is non-null, just as in standard JPA mapping.
</p>
<p>
If the column you name does not belong to any fields of the embedded object,
OpenJPA will create a synthetic null-indicator column with this name. In fact,
you can specify a value of <code class="literal">true</code> to simply indicate that you
want a synthetic null-indicator column, without having to come up with a name
for it. A value of <code class="literal">false</code> signals that you explicitly do not
want a null-indicator column created for this mapping (in case you have
configured your <a class="link" href="#ref_guide_mapping_defaults" title="4.&nbsp; Mapping Defaults">mapping defaults
</a> to create one by default).
</p>
</li><li class="listitem">
<p>
<code class="literal">String nullIndicatorFieldName</code>: Rather than name a null
indicator column, you can name a field of the embedded type. OpenJPA will use
the column of this field as the null-indicator column.
</p>
</li><li class="listitem">
<p>
<code class="literal">MappingOverride[] overrides</code>: This array allows you to
override any mapping of the embedded object.
</p>
</li></ul></div>
<p>
The <code class="classname">EmbeddedMapping</code>'s <code class="literal">overrides</code> array
serves the same purpose as standard JPA's <code class="classname">AttributeOverride
</code>s and <code class="classname">AssociationOverride</code> s. In fact, you can
also use the <code class="classname">MappingOverride</code> annotation on an entity
class to override a complex mapping of its mapped superclass, just as you can
with <code class="classname"> AttributeOverride</code> and <code class="classname">
AssociationOverride</code> s. The <code class="classname">MappingOverrides</code>
annotation, whose value is an array of <code class="classname">MappingOverride</code> s,
allows you to override multiple mapped superclass mappings.
</p>
<p>
Each
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/MappingOverride.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.MappingOverride</code>
</a> annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the field that is being overridden.
</p>
</li><li class="listitem">
<p>
<code class="literal">Column[] columns</code>: Columns for the new field mapping.
</p>
</li><li class="listitem">
<p>
<code class="literal">XJoinColumn[] joinColumns</code>: Join columns for the new field
mapping, if it is a relation field.
</p>
</li><li class="listitem">
<p>
<code class="literal">ContainerTable containerTable</code>: Table for the new collection
or map field mapping. We cover collection mappings in
<a class="xref" href="#ref_guide_mapping_jpa_coll" title="7.6.&nbsp; Collections">Section&nbsp;7.6, &#8220;
Collections
&#8221;</a>, and map mappings in
<a class="xref" href="#ref_guide_mapping_jpa_map" title="7.8.&nbsp; Maps">Section&nbsp;7.8, &#8220;
Maps
&#8221;</a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">ElementJoinColumn[] elementJoinColumns</code>: Element join columns
for the new collection or map field mapping. You will see how to use element
join columns in <a class="xref" href="#ref_guide_mapping_jpa_coll_joincols" title="7.6.2.&nbsp; Element Join Columns">Section&nbsp;7.6.2, &#8220;
Element Join Columns
&#8221;</a>.
</p>
</li></ul></div>
<p>
The following example defines an embeddable <code class="classname"> PathCoordinate
</code> class with a custom mapping of a <code class="classname">java.awt.Point
</code> field to two columns. It then defines an entity which embeds a
<code class="classname"> PointCoordinate</code> and overrides the default mapping for
the point field. The entity also declares that if the <code class="classname">PathCoordinate
</code>'s <code class="literal">siteName</code> field column is null, it means that
no <code class="classname">PathCoordinate</code> is stored in the embedded record; the
owning field will load as null.
</p>
<div class="example" id="ref_guide_mapping_jpa_embedex"><p class="title"><b>Example&nbsp;7.15.&nbsp;
Overriding Complex Mappings
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.jdbc.*;
@Embeddable
public class PathCoordinate {
private String siteName;
@Persistent
@Strategy("com.xyz.openjpa.PointValueHandler")
private Point point;
...
}
@Entity
public class Path {
@Embedded
@EmbeddedMapping(nullIndicatorFieldName="siteName", overrides={
@MappingOverride(name="siteName", columns=@Column(name="START_SITE")),
@MappingOverride(name="point", columns={
@Column(name="START_X"),
@Column(name="START_Y")
})
})
private PathCoordinate start;
...
}
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_mapping_jpa_coll"><div class="titlepage"><div><div><h3 class="title">7.6.&nbsp;
Collections
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_table">7.6.1.
Container Table
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_joincols">7.6.2.
Element Join Columns
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_coll_order">7.6.3.
Order Column
</a></span></dt></dl></div>
<a class="indexterm" name="d5e14499"></a>
<p>
In <a class="xref" href="#ref_guide_meta_jpa_persistent_coll" title="3.4.&nbsp;Persistent Collection Fields">Section&nbsp;3.4, &#8220;Persistent Collection Fields&#8221;</a>, we explored the
<code class="classname">PersistentCollection</code> annotation for persistent collection
fields that aren't a standard <code class="literal">OneToMany</code> or <code class="literal">
ManyToMany</code> relation. To map these non-standard collections, combine
OpenJPA's <code class="classname">ContainerTable</code> annotation with
<code class="classname">ElementJoinColumn</code>s.
We explore the annotations below.
</p>
<div class="section" id="ref_guide_mapping_jpa_coll_table"><div class="titlepage"><div><div><h4 class="title">7.6.1.&nbsp;
Container Table
</h4></div></div></div>
<a class="indexterm" name="d5e14511"></a>
<p>
The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ContainerTable.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ContainerTable</code>
</a> annotation describes a database table that holds collection (or map)
elements. This annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">String catalog</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">String schema</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">XJoinColumn[] joinColumns</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">ForeignKey joinForeignKey</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">Index joinIndex</code>
</p>
</li></ul></div>
<p>
The <code class="literal">name</code>, <code class="literal">catalog</code>, <code class="literal">schema
</code>, and <code class="literal">joinColumns</code> properties describe the container
table and how it joins to the owning entity's table. These properties correspond
to the same-named properties on the standard <code class="classname"> JoinTable</code>
annotation, described in <a class="xref" href="#jpa_overview_mapping_assoccoll" title="8.5.&nbsp; Join Table">Section&nbsp;8.5, &#8220;
Join Table
&#8221;</a>
. If left unspecified, the name of the table defaults to the first five
characters of the entity table name, plus an underscore, plus the field name.
The <code class="literal">joinForeignKey</code> and <code class="literal"> joinIndex</code>
properties override default foreign key and index generation for the join
columns. We explore foreign keys and indexes later in this chapter.
</p>
<p>
You may notice that the container table does not define how to store the
collection elements. That is left to separate annotations, which are the subject
of the next sections.
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_coll_joincols"><div class="titlepage"><div><div><h4 class="title">7.6.2.&nbsp;
Element Join Columns
</h4></div></div></div>
<a class="indexterm" name="d5e14548"></a>
<p>
Element join columns are equivalent to standard JPA join columns, except that
they represent a join to a collection or map element entity rather than a direct
relation. You represent an element join column with OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ElementJoinColumn.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ElementJoinColumn</code>
</a> annotation. To declare a compound join, enclose an array of <code class="classname">
ElementJoinColumn</code>s in the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ElementJoinColumns.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ElementJoinColumns</code>
</a> annotation.
</p>
<p>
An <code class="classname">ElementJoinColumn</code> always resides in a container table,
so it does not have the <code class="literal"> table</code> property of a standard
<code class="classname"> JoinColumn</code>. Like <code class="classname"> XJoinColumn</code>s
above, <code class="classname"> ElementJoinColumn</code>s can reference a linked
attribute rather than a static linked column. Otherwise, the <code class="classname">
ElementJoinColumn</code> and standard <code class="classname">JoinColumn</code>
annotations are equivalent. See <a class="xref" href="#jpa_overview_mapping_rel" title="8.4.&nbsp; Direct Relations">Section&nbsp;8.4, &#8220;
Direct Relations
&#8221;</a>
in the JPA Overview for a review of the <code class="classname">JoinColumn</code>
annotation.
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_coll_order"><div class="titlepage"><div><div><h4 class="title">7.6.3.&nbsp;
Order Column
</h4></div></div></div>
<a class="indexterm" name="d5e14569"></a>
<p>
Relational databases do not guarantee that records are returned in insertion
order. If you want to make sure that your collection elements are loaded in the
same order they were in when last stored, you must declare an order column. An
order column can be declared using OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/OrderColumn" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.OrderColumn</code></a>
annotation or the JPA 2.0 <code class="classname">javax.persistence.OrderColumn</code>
annotation or <code class="literal">order-column</code> orm element as defined in
<a class="xref" href="#jpa_overview_meta_xml" title="3.&nbsp; XML Schema">Section&nbsp;3, &#8220;
XML Schema
&#8221;</a>.
OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/OrderColumn" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.OrderColumn</code></a>
annotation has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">String name</code>: Defaults to <code class="literal">the name of the
relationship property or field of the entity or embeddable
class + _ORDER</code>. To use the JPA 1.0 default order column
name <code class="literal">ORDR</code>, set the <a class="xref" href="#openjpa.Compatibility" title="5.7.&nbsp; openjpa.Compatibility">Section&nbsp;5.7, &#8220;
openjpa.Compatibility
&#8221;</a>
option <code class="literal">UseJPA2DefaultOrderColumnName</code> to <code class="literal">
false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean enabled</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">int precision</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">String columnDefinition</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean insertable</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean updatable</code>
</p>
</li></ul></div>
<p>
Order columns are always in the container table. You can explicitly turn off
ordering (if you have enabled it by default via your
<a class="link" href="#ref_guide_mapping_defaults" title="4.&nbsp; Mapping Defaults"> mapping defaults</a>) by setting
the <code class="literal">enabled</code> property to <code class="literal">false</code>. All other
properties correspond exactly to the same-named properties on the standard
<code class="classname">Column</code> annotation, described in
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a>.
</p>
</div>
</div>
<div class="section" id="ref_guide_mapping_jpa_onemany"><div class="titlepage"><div><div><h3 class="title">7.7.&nbsp;
One-Sided One-Many Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e14612"></a>
<p>
The previous section covered the use of <code class="classname">ElementJoinColumn</code>
annotations in conjunction with a <code class="classname">ContainerTable</code> for
mapping collections to dedicate tables. <code class="classname">ElementJoinColumn</code>
s, however, have one additional use: to create a one-sided one-many mapping.
Standard JPA supports <code class="classname">OneToMany</code> fields without a
<code class="literal">mappedBy</code> inverse, but only by mapping these fields to a
<code class="classname">JoinTable</code> (see
<a class="xref" href="#jpa_overview_mapping_assoccoll" title="8.5.&nbsp; Join Table">Section&nbsp;8.5, &#8220;
Join Table
&#8221;</a> in the JPA Overview for
details). Often, you'd like to create a one-many association based on an inverse
foreign key (logical or actual) in the table of the related type.
</p>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="261"><tr><td><img src="img/inv-key-coll.png"></td></tr></table></div>
<p>
Consider the model above. <code class="classname">Subscription</code> has a collection
of <code class="classname">LineItem</code> s, but <code class="classname">LineItem</code> has
no inverse relation to <code class="classname">Subscription</code>. To retrieve all of
the <code class="classname">LineItem</code> records for a <code class="classname">Subscription
</code>, we join the <code class="literal">SUB_ID</code> inverse foreign key column
in the <code class="literal">LINE_ITEM</code> table to the primary key column of the
<code class="literal">SUB</code> table. The example below shows how to represent this
model in mapping annotations. Note that OpenJPA automatically assumes an inverse
foreign key mapping when element join columns are given, but no container or
join table is given.
</p>
<div class="example" id="ref_guide_mapping_jpa_onemanyex"><p class="title"><b>Example&nbsp;7.16.&nbsp;
One-Sided One-Many Mapping
</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag.subscribe;
import org.apache.openjpa.persistence.jdbc.*;
@Entity
@Table(name="LINE_ITEM", schema="CNTRCT")
public class LineItem {
...
}
@Entity
@Table(name="SUB", schema="CNTRCT")
public class Subscription {
@Id private long id;
@OneToMany
@ElementJoinColumn(name="SUB_ID", referencedColumnName="ID")
private Collection&lt;LineItem&gt; items;
...
}
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_mapping_jpa_map"><div class="titlepage"><div><div><h3 class="title">7.8.&nbsp;
Maps
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keycols">7.8.1. Key Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_keyjoincols">7.8.2. Key Join Columns</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_embedkey">7.8.3. Key Embedded Mapping</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_map_ex">7.8.4. Examples</a></span></dt></dl></div>
<a class="indexterm" name="d5e14642"></a>
<p>
We detailed the <code class="literal">ContainerTable</code> annotation in
<a class="xref" href="#ref_guide_mapping_jpa_coll_table" title="7.6.1.&nbsp; Container Table">Section&nbsp;7.6.1, &#8220;
Container Table
&#8221;</a>. Custom map mappings may
also use this annotation to represent a map table.
</p>
<div class="section" id="ref_guide_mapping_jpa_map_keycols"><div class="titlepage"><div><div><h4 class="title">7.8.1.&nbsp;Key Columns</h4></div></div></div>
<a class="indexterm" name="d5e14650"></a>
<p>
Key columns serve the same role for map keys as the element
join columns described in
<a class="xref" href="#ref_guide_mapping_jpa_coll_joincols" title="7.6.2.&nbsp; Element Join Columns">Section&nbsp;7.6.2, &#8220;
Element Join Columns
&#8221;</a> serve for
collection elements. OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/KeyColumn.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.KeyColumn</code>
</a> annotation represents a map key. To map custom
multi-column keys, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/KeyColumns.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.KeyColumns</code>
</a> annotation, whose value is an array of <code class="classname">KeyColumn</code>s.
</p>
<p>
A <code class="classname">KeyColumn</code> always resides in
a container table, so it does not have the <code class="literal">table</code>
property of a standard <code class="classname">Column</code>. Otherwise, the
<code class="classname">KeyColumn</code> and standard <code class="classname">Column</code>
annotations are equivalent. See
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a> in the JPA
Overview for a review of the <code class="classname">Column</code> annotation.
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_map_keyjoincols"><div class="titlepage"><div><div><h4 class="title">7.8.2.&nbsp;Key Join Columns</h4></div></div></div>
<a class="indexterm" name="d5e14670"></a>
<p>
Key join columns are equivalent to standard JPA
join columns, except that they represent a join to a map key entity rather than a direct relation. You represent
a key join column with OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/KeyJoinColumn.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.KeyJoinColumn</code></a> annotation. To declare a compound join, enclose an
array of <code class="classname">KeyJoinColumn</code>s in the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/KeyJoinColumns.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.KeyJoinColumns</code>
</a> annotation.
</p>
<p>
A <code class="classname">KeyJoinColumn</code> always resides in
a container table, so it does not have the <code class="literal">table</code> property
of a standard <code class="classname">JoinColumn</code>. Like <code class="classname">XJoinColumn</code>s above,
<code class="classname">KeyJoinColumn</code>s can reference a linked field
rather than a static linked column. Otherwise, the <code class="classname">KeyJoinColumn</code>
and standard <code class="classname">JoinColumn</code> annotations are equivalent. See
<a class="xref" href="#jpa_overview_mapping_rel" title="8.4.&nbsp; Direct Relations">Section&nbsp;8.4, &#8220;
Direct Relations
&#8221;</a> in the JPA
Overview for a review of the <code class="classname">JoinColumn</code> annotation.
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_map_embedkey"><div class="titlepage"><div><div><h4 class="title">7.8.3.&nbsp;Key Embedded Mapping</h4></div></div></div>
<a class="indexterm" name="d5e14691"></a>
<p>
The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/KeyEmbeddedMapping.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.KeyEmbeddedMapping</code>
</a> annotation allows you to map your map field's embedded
key type to your container table. This annotation has exactly
the same properties as the
<code class="classname">EmbeddedMapping</code> annotation described
<a class="link" href="#ref_guide_mapping_jpa_embed" title="7.5.&nbsp; Embedded Mapping">above</a>.
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_map_ex"><div class="titlepage"><div><div><h4 class="title">7.8.4.&nbsp;Examples</h4></div></div></div>
<div class="mediaobject"><table border="0" summary="manufactured viewport for HTML img" style="cellpadding: 0; cellspacing: 0;" width="273"><tr><td><img src="img/string-rel-map.png"></td></tr></table></div>
<p>
Map mapping in OpenJPA uses the same principles you saw in
collection mapping. The example below maps the <code class="literal">
Article.authors</code> map according to the diagram above.
</p>
<div class="example" id="ref_guide_mapping_jpa_map_stringrelmap"><p class="title"><b>Example&nbsp;7.17.&nbsp;String Key, Entity Value Map Mapping</b></p><div class="example-contents">
<pre class="programlisting">
package org.mag.pub;
import org.apache.openjpa.persistence.*;
import org.apache.openjpa.persistence.jdbc.*;
@Entity
@Table(name="AUTH")
@DataStoreIdColumn(name="AID", columnDefinition="INTEGER64")
public class Author {
...
}
package org.mag;
@Entity
@Table(name="ART")
public class Article {
@Id private long id;
@PersistentMap
@ContainerTable(name="ART_AUTHS", joinColumns=@XJoinColumn(name="ART_ID"))
@KeyColumn(name="LNAME")
@ElementJoinColumn(name="AUTH_ID")
private Map&lt;String,Author&gt; authors;
...
}
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_mapping_jpa_constraints"><div class="titlepage"><div><div><h3 class="title">7.9.&nbsp;
Indexes and Constraints
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_jpa_index">7.9.1.
Indexes
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_fk">7.9.2.
Foreign Keys
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_jpa_unique">7.9.3.
Unique Constraints
</a></span></dt></dl></div>
<p>
OpenJPA uses index information during schema generation to index the proper
columns. OpenJPA uses foreign key and unique constraint information during
schema creation to generate the proper database constraints, and also at runtime
to order SQL statements to avoid constraint violations while maximizing SQL
batch size.
</p>
<p>
OpenJPA assumes certain columns have indexes or constraints based on your
mapping defaults, as detailed in <a class="xref" href="#ref_guide_mapping_defaults" title="4.&nbsp; Mapping Defaults">Section&nbsp;4, &#8220;
Mapping Defaults
&#8221;</a>.
You can override the configured defaults on individual joins, field
values, collection elements, map keys, or map values using the annotations
presented in the following sections.
</p>
<div class="section" id="ref_guide_mapping_jpa_index"><div class="titlepage"><div><div><h4 class="title">7.9.1.&nbsp;
Indexes
</h4></div></div></div>
<a class="indexterm" name="d5e14716"></a>
<a class="indexterm" name="d5e14719"></a>
<p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Index.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Index</code></a>
annotation represents an index on the columns of a field. It is also used within
the <a class="link" href="#ref_guide_mapping_jpa_coll_table" title="7.6.1.&nbsp; Container Table"><code class="classname">ContainerTable
</code></a> annotation to index join columns.
To index the columns of a collection element, use the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ElementIndex.html" target="_top">
<code class="classname"> org.apache.openjpa.persistence.jdbc.ElementIndex</code></a>
annotation. These annotations have the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">boolean enabled</code>: Set this property to <code class="literal">false
</code> to explicitly tell OpenJPA not to index these columns, when OpenJPA
would otherwise do so.
</p>
</li><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the index. OpenJPA will choose a
name if you do not provide one.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean unique</code>: Whether to create a unique index. Defaults
to false.
</p>
</li></ul></div>
</div>
<div class="section" id="ref_guide_mapping_jpa_fk"><div class="titlepage"><div><div><h4 class="title">7.9.2.&nbsp;
Foreign Keys
</h4></div></div></div>
<a class="indexterm" name="d5e14741"></a>
<a class="indexterm" name="d5e14744"></a>
<p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ForeignKey.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ForeignKey</code></a>
annotation represents a foreign key on the columns of a field. It is also used
within the <a class="link" href="#ref_guide_mapping_jpa_coll_table" title="7.6.1.&nbsp; Container Table"><code class="classname">
ContainerTable</code></a> annotation to set a database foreign key on
join columns. To set a constraint to the columns of a collection element, use
the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ElementForeignKey.html" target="_top">
<code class="classname"> org.apache.openjpa.persistence.jdbc.ElementForeignKey</code>
</a> annotation. These annotations have the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">boolean enabled</code>: Set this property to <code class="literal">false
</code> to explicitly tell OpenJPA not to set a foreign key on these columns,
when OpenJPA would otherwise do so.
</p>
</li><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the foreign key. OpenJPA will
choose a name if you do not provide one, or will create an anonymous key.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean deferred</code>: Whether to create a deferred key if
supported by the database.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean implicit</code>: Whether to mark a relation field value as
implicitly referring to a related entity. This property can be used, for
example, when a field value represents primary key field of a related
entity, but for legacy or other logistic reasons, the field is declared as the
same type of the primary key of the related entity instead of a reference to
the entity itself. Hence no actual mapping can be defined on the field itself.
If this implicit property is set, then no other property on
the ForeignKey annotation can be set to their non-default value. This setting
does not manifest as a database foreign key constraint.
</p>
</li><li class="listitem">
<p>
<code class="literal">ForeignKeyAction deleteAction</code>: Value from the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ForeignKeyAction.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ForeignKeyAction</code>
</a> enum identifying the desired delete action. Defaults to <code class="literal">
RESTRICT</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">ForeignKeyAction updateAction</code>: Value from the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ForeignKeyAction.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ForeignKeyAction</code>
</a> enum identifying the desired update action. Defaults to <code class="literal">
RESTRICT</code>.
</p>
</li></ul></div>
<p>
Keep in mind that OpenJPA uses foreign key information at runtime to avoid
constraint violations; it is important, therefore, that your
<a class="link" href="#ref_guide_mapping_defaults" title="4.&nbsp; Mapping Defaults">mapping defaults</a> and foreign
key annotations combine to accurately reflect your existing database
constraints, or that you configure OpenJPA to reflect on your database schema
to discover existing foreign keys (see
<a class="xref" href="#ref_guide_schema_info_factory" title="12.2.&nbsp; Schema Factory">Section&nbsp;12.2, &#8220;
Schema Factory
&#8221;</a>).
</p>
</div>
<div class="section" id="ref_guide_mapping_jpa_unique"><div class="titlepage"><div><div><h4 class="title">7.9.3.&nbsp;
Unique Constraints
</h4></div></div></div>
<a class="indexterm" name="d5e14784"></a>
<a class="indexterm" name="d5e14787"></a>
<p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Unique.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Unique</code></a>
annotation represents a unique constraint on the columns of a field. It is more
convenient than using the <code class="literal">uniqueConstraints</code> property of
standard JPA <code class="classname">Table</code> and <code class="classname">SecondaryTable
</code> annotations, because you can apply it directly to the constrained
field. The <code class="classname">Unique</code> annotation has the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">boolean enabled</code>: Set this property to <code class="literal">false
</code> to explicitly tell OpenJPA not to constrain these columns, when
OpenJPA would otherwise do so.
</p>
</li><li class="listitem">
<p>
<code class="literal">String name</code>: The name of the constraint. OpenJPA will choose
a name if you do not provide one, or will create an anonymous constraint.
</p>
</li><li class="listitem">
<p>
<code class="literal">boolean deferred</code>: Whether to create a deferred constraint if
supported by the database.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_xmlmapping"><div class="titlepage"><div><div><h3 class="title">7.10.&nbsp;
XML Column Mapping
</h3></div></div></div>
<a class="indexterm" name="d5e14809"></a>
<a class="indexterm" name="d5e14812"></a>
<p>
Some databases support XML column types and
XPath queries and indexes over these columns. OpenJPA supports mapping of an
entity property mapped to an XML column on the following databases and their
minimum versions.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
DB2 9
</p>
</li><li class="listitem">
<p>
MySQL 5.1.30
</p>
</li><li class="listitem">
<p>
Oracle 9
</p>
</li><li class="listitem">
<p>
PostgreSQL 8.3 (XML support must be compiled in, the minimum JDBC driver
version is 8.3-603)
</p>
</li><li class="listitem">
<p>
SQL Server 2005
</p>
</li></ul></div>
<p>
See <a class="xref" href="#supported_databases" title="Appendix&nbsp;2.&nbsp; Supported Databases">Appendix&nbsp;2, <i>
Supported Databases
</i></a> for possible database-specific
restrictions.
</p>
<p>
Annotate the entity property using the XMLValueHandler strategy:
</p>
<pre class="programlisting">
@Persistent
@Strategy("org.apache.openjpa.jdbc.meta.strats.XMLValueHandler")
</pre>
<p>
The default fetch type is EAGER but can be changed to LAZY by using:
</p>
<pre class="programlisting">
@Persistence(fetch=FetchType.LAZY)
</pre>
<p>
The entity property class is required to have
JAXB binding annotations. You can generate property class from an XML schema by using
the <code class="literal">xjc</code> generator from the
<a class="ulink" href="http://jaxb.java.net/" target="_top">JAXB reference implementation</a>.
The <code class="literal">xjc</code> will generate the
class along with the required annotations. Ensure that <code class="classname">@XmlRootElement</code>
appears in the root class. In some cases this annotation needs to be added manually.
</p>
<p>
The entity property class is required to have getter and setter methods for all its
fields. By default, the <code class="literal">xjc</code> will not generate setter
methods for collections but you can force it to do so by using the
<a class="ulink" href="http://confluence.highsource.org/display/J2B/Setters+Plugin" target="_top">
setters plugin</a>
or collection setter injector plugin.
</p>
<p>
The JAXB jar files must be on the application classpath (jaxb-api.jar,
jaxb-impl.jar, jsr173_1.0_api.jar or equivalent).
</p>
<p>
JPQL path expressions can navigate into the mapped class and its
subfields to any level.
</p>
<p>
The path expression is rewritten into an equivalent XPath expression using SQL
XML functions.
</p>
<p>
The path expression must be single-valued. Path expressions over XML
mapped classes can only be used in the WHERE clause as an operand to a simple predicate
(= &lt;&gt; &lt; &gt; &gt;= &lt;=).
</p>
<p>
Path expressions over XML mapped fields can not be:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
an input to a JPQL scalar function
</p>
</li><li class="listitem">
<p>
an operand of BETWEEN, IS NULL, LIKE or IN predicate
</p>
</li><li class="listitem">
<p>
used to project out subfields in the SELECT clause
</p>
</li><li class="listitem">
<p>
used in the FROM, GROUP BY, HAVING, ORDER BY clauses
</p>
</li></ul></div>
<p>
XML schema must not contain namespace declarations. The JPQL path
expressions can not refer to Java fields generated from XML ANY type or
XML mixed element types.
</p>
<p>
The data type generated by JAXB must be a valid type
to use the property in a JPQL predicate.
</p>
<p>
Shown below is a sample XML schema <a class="link" href="#ref_guide_xmlmapping_myaddress" title="Example&nbsp;7.18.&nbsp; myaddress.xsd">myaddress.xsd</a>,
in which the JPA entity Order has <code class="classname">shipAddress</code> persistent field that maps to an XML column.
</p>
<div class="example" id="ref_guide_xmlmapping_myaddress"><p class="title"><b>Example&nbsp;7.18.&nbsp;
myaddress.xsd
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;?xml version="1.0" ?&gt;
&lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" &gt;
&lt;xs:complexType name="Address"&gt;
&lt;xs:sequence&gt;
&lt;xs:element name="Name" type="xs:string" /&gt;
&lt;xs:element name="Street" type="xs:string"
minOccurs="1" maxOccurs="3" /&gt;
&lt;xs:element name="City" type="xs:string" /&gt;
&lt;/xs:sequence&gt;
&lt;/xs:complexType&gt;
&lt;xs:complexType name="CAN_Address"&gt;
&lt;xs:complexContent&gt;
&lt;xs:extension base="Address"&gt;
&lt;xs:sequence&gt;
&lt;xs:element name="Province" type="xs:string" /&gt;
&lt;xs:element name="PostalCode" type="xs:string" /&gt;
&lt;/xs:sequence&gt;
&lt;/xs:extension&gt;
&lt;/xs:complexContent&gt;
&lt;/xs:complexType&gt;
&lt;xs:simpleType name="USPS_ZIP"&gt;
&lt;xs:restriction base="xs:integer"&gt;
&lt;xs:minInclusive value="01000" /&gt;
&lt;xs:maxInclusive value="99999" /&gt;
&lt;/xs:restriction&gt;
&lt;/xs:simpleType&gt;
&lt;xs:complexType name="USA_Address"&gt;
&lt;xs:complexContent&gt;
&lt;xs:extension base="Address"&gt;
&lt;xs:sequence&gt;
&lt;xs:element name="State" type="xs:string" /&gt;
&lt;xs:element name="ZIP" type="USPS_ZIP" /&gt;
&lt;/xs:sequence&gt;
&lt;/xs:extension&gt;
&lt;/xs:complexContent&gt;
&lt;/xs:complexType&gt;
&lt;xs:element name="MailAddress" type="Address" /&gt;
&lt;xs:element name="AddrCAN" type="CAN_Address"
substitutionGroup="MailAddress" /&gt;
&lt;xs:element name="AddrUSA" type="USA_Address"
substitutionGroup="MailAddress" /&gt;
&lt;/xs:schema&gt;
</pre>
</div></div><br class="example-break">
<p>
Java classes <a class="link" href="#ref_guide_xmlmapping_address" title="Example&nbsp;7.19.&nbsp; Address.java">Address</a>,
<a class="link" href="#ref_guide_xmlmapping_usaaddress" title="Example&nbsp;7.20.&nbsp; USAAddress.java">USAAddress</a> and
<a class="link" href="#ref_guide_xmlmapping_canaddress" title="Example&nbsp;7.21.&nbsp; CANAddress.java">CANAddress</a>
are produced from <code class="literal">myaddress</code> schema by using the
<code class="literal">xjc</code> generator.
</p>
<div class="example" id="ref_guide_xmlmapping_address"><p class="title"><b>Example&nbsp;7.19.&nbsp;
Address.java
</b></p><div class="example-contents">
<pre class="programlisting">
...
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Address", propOrder = {
"name",
"street",
"city"
})
public class Address {
@XmlElement(name = "Name", required = true)
protected String name;
@XmlElement(name = "Street", required = true)
protected List&lt;String&gt; street;
@XmlElement(name = "City", required = true)
protected String city;
/**
* Getter and Setter methods.
*
*/
...
}
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_xmlmapping_usaaddress"><p class="title"><b>Example&nbsp;7.20.&nbsp;
USAAddress.java
</b></p><div class="example-contents">
<pre class="programlisting">
...
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "USA_Address", propOrder = {
"state",
"zip"
})
public class USAAddress
extends Address
{
@XmlElement(name = "State")
protected String state;
@XmlElement(name = "ZIP")
protected int zip;
/**
* Getter and Setter methods.
*
*/
...
}
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_xmlmapping_canaddress"><p class="title"><b>Example&nbsp;7.21.&nbsp;
CANAddress.java
</b></p><div class="example-contents">
<pre class="programlisting">
...
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CAN_Address", propOrder = {
"province",
"postalCode"
})
public class CANAddress
extends Address
{
@XmlElement(name = "Province")
protected String province;
@XmlElement(name = "PostalCode")
protected String postalCode;
/**
* Getter and Setter methods.
*
*/
...
}
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_xmlmapping_annorder"><p class="title"><b>Example&nbsp;7.22.&nbsp;
Showing annotated Order entity with XML mapping strategy
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
public class Order {
@Id private into id;
@Persistent
@Strategy ("org.apache.openjpa.jdbc.meta.strats.XMLValueHandler")
private Address shipAddress;
...
}
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_xmlmapping_createorder"><p class="title"><b>Example&nbsp;7.23.&nbsp;
Showing creation of Order entity having shipAddress mapped to XML column
</b></p><div class="example-contents">
<pre class="programlisting">
...
myaddress.ObjectFactory addressFactory = new myaddress.ObjectFactory();
Customer c1 = new Customer();
c1.setCid( new Customer.CustomerKey("USA", 1) );
c1.setName("Harry's Auto");
Order o1 = new Order( 850, false, c1);
USAAddress addr1 = addressFactory.createUSAAddress();
addr1.setCity("San Jose");
addr1.setState("CA");
addr1.setZIP(new Integer("95141"));
addr1.getStreet().add("12500 Monterey");
addr1.setName( c1.getName());
o1.setShipAddress(addr1);
em.persist(o1);
...
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_xmlmapping_jpqlquery"><p class="title"><b>Example&nbsp;7.24.&nbsp;
Sample JPQL queries for XML column mapping
</b></p><div class="example-contents">
<pre class="programlisting">
. select o from Order o where o.shipAddress.city = "San Jose" or
o.shipAddress.city = "San Francisco" (OK)
. select o.shipaAddress from Order o (OK)
. select o.shipAddress.city from Order o (INVALID)
. select o from Order o where o.shipAddress.street = "San Jose" (INVALID multi-valued)
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_streamsupport"><div class="titlepage"><div><div><h3 class="title">7.11.&nbsp;
LOB Streaming
</h3></div></div></div>
<a class="indexterm" name="d5e14888"></a>
<p>
In addition to handling LOBs in a standard JPA manner
(<code class="classname">LOB</code> annotation and <code class="literal">lob</code> XML element),
OpenJPA supports LOB streaming. This feature
makes it possible to stream large amounts of data into and out of persistent
field without ever holding all the data in memory at the same time.
</p>
<p>
LOB streaming is supported on the following databases.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
MySQL
</p>
</li><li class="listitem">
<p>
Oracle
</p>
</li><li class="listitem">
<p>
PostgreSQL
</p>
</li><li class="listitem">
<p>
SQL Server
</p>
</li><li class="listitem">
<p>
DB2
</p>
</li></ul></div>
<p>
See <a class="xref" href="#supported_databases" title="Appendix&nbsp;2.&nbsp; Supported Databases">Appendix&nbsp;2, <i>
Supported Databases
</i></a> for possible database-specific
restrictions.
</p>
<p>
To persist a stream, apply the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Persistent.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.Persistent</code></a>
annotation to either <code class="classname">java.io.InputStream</code> or
<code class="classname">java.io.Reader</code> field.
</p>
<div class="example" id="ref_guide_streamsupport_example"><p class="title"><b>Example&nbsp;7.25.&nbsp;
Annotated InputStream and Reader
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
public class Employee {
...
@Persistent
private InputStream photoStream;
@Persistent
private Reader photoDescription;
...
}
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_mapping_limits"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;
Mapping Limitations
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_limits_tpc">8.1.
Table Per Class
</a></span></dt></dl></div>
<a class="indexterm" name="d5e14917"></a>
<p>
The following sections outline the limitations OpenJPA places on specific
mapping strategies.
</p>
<div class="section" id="ref_guide_mapping_limits_tpc"><div class="titlepage"><div><div><h3 class="title">8.1.&nbsp;
Table Per Class
</h3></div></div></div>
<a class="indexterm" name="d5e14923"></a>
<p>
Table-per-class inheritance mapping has the following limitations:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
You cannot traverse polymorphic relations to non-leaf classes in a
table-per-class inheritance hierarchy in queries.
</p>
</li><li class="listitem">
<p>
You cannot map a one-sided polymorphic relation to a non-leaf class in a
table-per-class inheritance hierarchy using an inverse foreign key.
</p>
</li><li class="listitem">
<p>
You cannot use an order column in a polymorphic relation to a non-leaf class in
a table-per-class inheritance hierarchy mapped with an inverse foreign key.
</p>
</li><li class="listitem">
<p>
Table-per-class hierarchies impose limitations on eager fetching. See
<a class="xref" href="#ref_guide_perfpack_eager_consider" title="8.2.&nbsp; Eager Fetching Considerations and Limitations">Section&nbsp;8.2, &#8220;
Eager Fetching Considerations and Limitations
&#8221;</a>.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Non-polymorphic relations do not suffer from these limitations. You can declare
a non-polymorphic relation using the extensions described in
<a class="xref" href="#nonpolymorphic" title="9.2.2.&nbsp; Nonpolymorphic">Section&nbsp;9.2.2, &#8220;
Nonpolymorphic
&#8221;</a>.
</p>
</div>
</div>
</div>
<div class="section" id="ref_guide_mapping_ext"><div class="titlepage"><div><div><h2 class="title" style="clear: both">9.&nbsp;
Mapping Extensions
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_ext_cls">9.1.
Class Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#subclass-fetch-mode">9.1.1.
Subclass Fetch Mode
</a></span></dt><dt><span class="section"><a href="#class-strategy">9.1.2.
Strategy
</a></span></dt><dt><span class="section"><a href="#discriminator-strategy">9.1.3.
Discriminator Strategy
</a></span></dt><dt><span class="section"><a href="#version-strategy">9.1.4.
Version Strategy
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_mapping_ext_field">9.2.
Field Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#eager-fetch-mode">9.2.1.
Eager Fetch Mode
</a></span></dt><dt><span class="section"><a href="#nonpolymorphic">9.2.2.
Nonpolymorphic
</a></span></dt><dt><span class="section"><a href="#class-criteria">9.2.3.
Class Criteria
</a></span></dt><dt><span class="section"><a href="#strategy">9.2.4.
Strategy
</a></span></dt></dl></dd></dl></div>
<p>
Mapping extensions allow you to access OpenJPA-specific functionality from your
mappings. Note that all extensions below are specific to mappings. If you store
your mappings separately from your persistence metadata, these extensions must
be specified along with the mapping information, not the persistence metadata
information.
</p>
<div class="section" id="ref_guide_mapping_ext_cls"><div class="titlepage"><div><div><h3 class="title">9.1.&nbsp;
Class Extensions
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#subclass-fetch-mode">9.1.1.
Subclass Fetch Mode
</a></span></dt><dt><span class="section"><a href="#class-strategy">9.1.2.
Strategy
</a></span></dt><dt><span class="section"><a href="#discriminator-strategy">9.1.3.
Discriminator Strategy
</a></span></dt><dt><span class="section"><a href="#version-strategy">9.1.4.
Version Strategy
</a></span></dt></dl></div>
<p>
OpenJPA recognizes the following class extensions.
</p>
<div class="section" id="subclass-fetch-mode"><div class="titlepage"><div><div><h4 class="title">9.1.1.&nbsp;
Subclass Fetch Mode
</h4></div></div></div>
<a class="indexterm" name="d5e14949"></a>
<p>
This extension specifies how to eagerly fetch subclass state. It overrides the
global <a class="link" href="#openjpa.jdbc.SubclassFetchMode" title="6.16.&nbsp; openjpa.jdbc.SubclassFetchMode"><code class="literal">
openjpa.jdbc.SubclassFetchMode</code></a> property. Set the OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/SubclassFetchMode.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.SubclassFetchMode</code>
</a> annotation to a value from the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/FetchMode.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.FetchMode</code>
</a> enum: <code class="literal">JOIN</code>, <code class="literal">PARALLEL</code>, or
<code class="literal">NONE</code>. See <a class="xref" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">Section&nbsp;8, &#8220;
Eager Fetching
&#8221;</a>
for a discussion of eager fetching.
</p>
</div>
<div class="section" id="class-strategy"><div class="titlepage"><div><div><h4 class="title">9.1.2.&nbsp;
Strategy
</h4></div></div></div>
<a class="indexterm" name="d5e14967"></a>
<p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Strategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Strategy</code></a>
class annotation allows you to specify a custom mapping strategy for your class.
See <a class="xref" href="#ref_guide_mapping_custom" title="10.&nbsp; Custom Mappings">Section&nbsp;10, &#8220;
Custom Mappings
&#8221;</a> for information on custom
mappings.
</p>
</div>
<div class="section" id="discriminator-strategy"><div class="titlepage"><div><div><h4 class="title">9.1.3.&nbsp;
Discriminator Strategy
</h4></div></div></div>
<a class="indexterm" name="d5e14978"></a>
<p>
The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/DiscriminatorStrategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.DiscriminatorStrategy</code>
</a> class annotation allows you to specify a custom discriminator strategy.
See <a class="xref" href="#ref_guide_mapping_custom" title="10.&nbsp; Custom Mappings">Section&nbsp;10, &#8220;
Custom Mappings
&#8221;</a> for information on custom
mappings.
</p>
</div>
<div class="section" id="version-strategy"><div class="titlepage"><div><div><h4 class="title">9.1.4.&nbsp;
Version Strategy
</h4></div></div></div>
<a class="indexterm" name="d5e14989"></a>
<p>
The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/VersionStrategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.VersionStrategy</code>
</a> class annotation allows you to specify a custom version strategy. See
<a class="xref" href="#ref_guide_mapping_custom" title="10.&nbsp; Custom Mappings">Section&nbsp;10, &#8220;
Custom Mappings
&#8221;</a> for information on custom
mappings.
</p>
</div>
</div>
<div class="section" id="ref_guide_mapping_ext_field"><div class="titlepage"><div><div><h3 class="title">9.2.&nbsp;
Field Extensions
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#eager-fetch-mode">9.2.1.
Eager Fetch Mode
</a></span></dt><dt><span class="section"><a href="#nonpolymorphic">9.2.2.
Nonpolymorphic
</a></span></dt><dt><span class="section"><a href="#class-criteria">9.2.3.
Class Criteria
</a></span></dt><dt><span class="section"><a href="#strategy">9.2.4.
Strategy
</a></span></dt></dl></div>
<p>
OpenJPA recognizes the following field extensions.
</p>
<div class="section" id="eager-fetch-mode"><div class="titlepage"><div><div><h4 class="title">9.2.1.&nbsp;
Eager Fetch Mode
</h4></div></div></div>
<a class="indexterm" name="d5e15003"></a>
<p>
This extension specifies how to eagerly fetch related objects. It overrides the
global <a class="link" href="#openjpa.jdbc.EagerFetchMode" title="6.4.&nbsp; openjpa.jdbc.EagerFetchMode"><code class="literal">
openjpa.jdbc.EagerFetchMode</code></a> property. Set the OpenJPA
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/EagerFetchMode.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.EagerFetchMode</code>
</a> annotation to a value from the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/FetchMode.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.FetchMode</code>
</a> enum: <code class="literal">JOIN</code>, <code class="literal">PARALLEL</code>, or
<code class="literal">NONE</code>. See <a class="xref" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">Section&nbsp;8, &#8220;
Eager Fetching
&#8221;</a>
for a discussion of eager fetching.
</p>
</div>
<div class="section" id="nonpolymorphic"><div class="titlepage"><div><div><h4 class="title">9.2.2.&nbsp;
Nonpolymorphic
</h4></div></div></div>
<a class="indexterm" name="d5e15021"></a>
<p>
All fields in Java are polymorphic. If you declare a field of type <code class="literal">T
</code>, you can assign any subclass of <code class="literal">T</code> to the field as
well. This is very convenient, but can make relation traversal very inefficient
under some inheritance strategies. It can even make querying across the field
impossible. Often, you know that certain fields do not need to be entirely
polymorphic. By telling OpenJPA about such fields, you can improve the
efficiency of your relations.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
OpenJPA also includes the <code class="literal">type</code> metadata extension for
narrowing the declared type of a field. See <a class="xref" href="#type" title="4.2.6.&nbsp; Type">Section&nbsp;4.2.6, &#8220;
Type
&#8221;</a>.
</p>
</div>
<p>
OpenJPA defines the following extensions for nonpolymorphic values:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Nonpolymorphic.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Nonpolymorphic</code>
</a>
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ElementNonpolymorphic.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ElementNonpolymorphic</code>
</a>
</p>
</li></ul></div>
<p>
The value of these extensions is a constant from the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/NonpolymorphicType.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.NonpolymorphicType</code>
</a> enumeration. The default value, <code class="literal">EXACT</code>, indicates
that the relation will always be of the exact declared type. A value of
<code class="literal">JOINABLE</code>, on the other hand, means that the relation might
be to any joinable subclass of the declared type. This value only excludes
table-per-class subclasses.
</p>
</div>
<div class="section" id="class-criteria"><div class="titlepage"><div><div><h4 class="title">9.2.3.&nbsp;
Class Criteria
</h4></div></div></div>
<a class="indexterm" name="d5e15049"></a>
<a class="indexterm" name="d5e15054"></a>
<p>
This family of boolean extensions determines whether OpenJPA will use the
expected class of related objects as criteria in the SQL it issues to load a
relation field. Typically, this is not needed. The foreign key values uniquely
identify the record for the related object. Under some rare mappings, however,
you may need to consider both foreign key values and the expected class of the
related object - for example, if you have an inverse relation that shares the
foreign key with another inverse relation to an object of a different subclass.
In these cases, set the proper class criteria extension to <code class="literal">true
</code> to force OpenJPA to append class criteria to its select SQL.
</p>
<p>
OpenJPA defines the following class criteria annotations for field relations and
array or collection element relations, respectively:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ClassCriteria.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ClassCriteria</code></a>
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/ElementClassCriteria.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.ElementClassCriteria</code>
</a>
</p>
</li></ul></div>
</div>
<div class="section" id="strategy"><div class="titlepage"><div><div><h4 class="title">9.2.4.&nbsp;
Strategy
</h4></div></div></div>
<a class="indexterm" name="d5e15071"></a>
<p>
OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Strategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Strategy</code></a>
extension allows you to specify a custom mapping
strategy or value handler for a field. See
<a class="xref" href="#ref_guide_mapping_custom" title="10.&nbsp; Custom Mappings">Section&nbsp;10, &#8220;
Custom Mappings
&#8221;</a> for information on custom
mappings.
</p>
</div>
</div>
</div>
<div class="section" id="ref_guide_mapping_custom"><div class="titlepage"><div><div><h2 class="title" style="clear: both">10.&nbsp;
Custom Mappings
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_custom_class">10.1.
Custom Class Mapping
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_versdiscrim">10.2.
Custom Discriminator and Version Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field">10.3.
Custom Field Mapping
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_mapping_custom_vhandler">10.3.1.
Value Handlers
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_fieldstrat">10.3.2.
Field Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field_conf">10.3.3.
Configuration
</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e15082"></a>
<a class="indexterm" name="d5e15084"></a>
<p>
In OpenJPA, you are not limited to the set of standard mappings defined by the
specification. OpenJPA allows you to define custom class, discriminator,
version, and field mapping strategies with all the power of OpenJPA's built-in
strategies.
</p>
<div class="section" id="ref_guide_mapping_custom_class"><div class="titlepage"><div><div><h3 class="title">10.1.&nbsp;
Custom Class Mapping
</h3></div></div></div>
<p>
To create a custom class mapping, write an implementation of the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/ClassStrategy.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.ClassStrategy</code></a>
interface. You will probably want to extend one of the existing abstract or
concrete strategies in the <code class="literal">org.apache.openjpa.jdbc.meta.strats
</code> package.
</p>
<p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Strategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Strategy</code></a>
annotation allows you to declare a custom class mapping strategy in JPA mapping
metadata. Set the value of the annotation to the full class name of your custom
strategy. You can configure your strategy class' bean properties using
OpenJPA's plugin syntax, detailed in <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>.
</p>
</div>
<div class="section" id="ref_guide_mapping_custom_versdiscrim"><div class="titlepage"><div><div><h3 class="title">10.2.&nbsp;
Custom Discriminator and Version Strategies
</h3></div></div></div>
<p>
To define a custom discriminator or version strategy, implement the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/DiscriminatorStrategy.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.DiscriminatorStrategy</code>
</a> or
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/VersionStrategy.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.meta.VersionStrategy</code></a>
interface, respectively. You might extend one of the existing abstract or
concrete strategies in the <code class="literal">org.apache.openjpa.jdbc.meta.strats
</code> package.
</p>
<p>
OpenJPA includes the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/DiscriminatorStrategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.DiscriminatorStrategy</code>
</a> and
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/VersionStrategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.VersionStrategy</code>
</a> class annotations for declaring a custom discriminator or version
strategy in JPA mapping metadata. Set the string value of these annotations to
the full class name of your implementation, or to the class name or alias of an
existing OpenJPA implementation.
</p>
<p>
As with custom class mappings, you can configure your strategy class' bean
properties using OpenJPA's plugin syntax, detailed in
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>.
</p>
</div>
<div class="section" id="ref_guide_mapping_custom_field"><div class="titlepage"><div><div><h3 class="title">10.3.&nbsp;
Custom Field Mapping
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_mapping_custom_vhandler">10.3.1.
Value Handlers
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_fieldstrat">10.3.2.
Field Strategies
</a></span></dt><dt><span class="section"><a href="#ref_guide_mapping_custom_field_conf">10.3.3.
Configuration
</a></span></dt></dl></div>
<a class="indexterm" name="d5e15116"></a>
<p>
While custom class, discriminator, and version mapping can be useful, custom
field mappings are far more common. OpenJPA offers two types of custom field
mappings: value handlers, and full custom field strategies. The following
sections examine each.
</p>
<div class="section" id="ref_guide_mapping_custom_vhandler"><div class="titlepage"><div><div><h4 class="title">10.3.1.&nbsp;
Value Handlers
</h4></div></div></div>
<a class="indexterm" name="d5e15122"></a>
<p>
Value handlers make it trivial to map any type that you can break down into one
or more simple values. All value handlers implement the <code class="classname">
org.apache.openjpa.jdbc.meta.ValueHandler</code> interface; see its
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/ValueHandler.html" target="_top"> Javadoc
</a> for details. Also, examine the built-in handlers in the <code class="filename">
src/openjpa/jdbc/meta/strats</code> directory of your OpenJPA source
distribution. Use these functional implementations as examples when you
create your own value handlers.
</p>
</div>
<div class="section" id="ref_guide_mapping_custom_fieldstrat"><div class="titlepage"><div><div><h4 class="title">10.3.2.&nbsp;
Field Strategies
</h4></div></div></div>
<a class="indexterm" name="d5e15132"></a>
<p>
OpenJPA interacts with persistent fields through the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/meta/FieldStrategy" target="_top"><code class="classname">
org.apache.openjpa.jdbc.meta.FieldStrategy</code></a> interface. You
can implement this interface yourself to create a custom field strategy, or
extend one of the existing abstract or concrete strategies in the <code class="literal">
org.apache.openjpa.jdbc.meta.strats</code> package. Creating a custom field
strategy is more difficult than writing a custom value handler, but gives you
more freedom in how you interact with the database.
</p>
</div>
<div class="section" id="ref_guide_mapping_custom_field_conf"><div class="titlepage"><div><div><h4 class="title">10.3.3.&nbsp;
Configuration
</h4></div></div></div>
<a class="indexterm" name="d5e15142"></a>
<p>
OpenJPA gives you two ways to configure your custom field mappings. The
<code class="literal">FieldStrategies</code> property of the built-in <code class="classname">
MappingDefaults</code> implementations allows you to globally associate
field types with their corresponding custom value handler or strategy. OpenJPA
will automatically use your custom strategies when it encounters a field of the
associated type. OpenJPA will use your custom value handlers whenever it
encounters a field of the associated type.
<a class="xref" href="#ref_guide_mapping_defaults" title="4.&nbsp; Mapping Defaults">Section&nbsp;4, &#8220;
Mapping Defaults
&#8221;</a> described mapping
defaults in detail.
</p>
<p>
Your other option is to explicitly install a custom value handler or strategy on
a particular field. To do so, specify the full name of your implementation class
in the proper mapping metadata extension. OpenJPA includes the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/Strategy.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.Strategy</code></a>
annotation. You can configure the named strategy or handler's bean
properties in these extensions using OpenJPA's plugin format (see
<a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>).
</p>
</div>
</div>
</div>
<div class="section" id="ref_guide_orphan"><div class="titlepage"><div><div><h2 class="title" style="clear: both">11.&nbsp;
Orphaned Keys
</h2></div></div></div>
<p>
Unless you apply database foreign key constraints extensively, it is possible to
end up with orphaned keys in your database. For example, suppose <code class="classname">
Magazine</code> <code class="literal">m</code> has a reference to <code class="classname">Article
</code><code class="literal">a</code>. If you delete <code class="literal">a</code> without
nulling <code class="literal">m</code>'s reference, <code class="literal">m</code>'s database
record will wind up with an orphaned key to the non-existent <code class="literal">a
</code> record.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
One way of avoiding orphaned keys is to use <span class="emphasis"><em>dependent</em></span>
fields.
</p>
</div>
<p>
OpenJPA's <a class="link" href="#openjpa.OrphanedKeyAction" title="5.53.&nbsp; openjpa.OrphanedKeyAction"><code class="literal">
openjpa.OrphanedKeyAction</code></a> configuration property controls what
action to take when OpenJPA encounters an orphaned key. You can set this plugin
string (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) to a custom
implementation of the
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/OrphanedKeyAction.html" target="_top">
<code class="classname"> org.apache.openjpa.event.OrphanedKeyAction</code></a>
interface, or use one of the built-in options:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">log</code>: This is the default setting. This option logs a message
for each orphaned key. It is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/LogOrphanedKeyAction.html" target="_top">
<code class="classname">org.apache.openjpa.event.LogOrphanedKeyAction</code></a>
class, which has the following additional properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">Channel</code>: The channel to log to. Defaults to <code class="literal">
openjpa.Runtime</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">Level</code>: The level to log at. Defaults to <code class="literal">WARN
</code>.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<code class="literal">exception</code>: Throw an <code class="classname">
EntityNotFoundException</code> when OpenJPA discovers an
orphaned key. This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/ExceptionOrphanedKeyAction.html" target="_top">
<code class="classname">org.apache.openjpa.event.ExceptionOrphanedKeyAction</code>
</a> class.
</p>
</li><li class="listitem">
<p>
<code class="literal">none</code>: Ignore orphaned keys. This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/NoneOrphanedKeyAction.html" target="_top">
<code class="classname">org.apache.openjpa.event.NoneOrphanedKeyAction</code></a>
class.
</p>
</li></ul></div>
<div class="example" id="ref_guide_orphan_logex"><p class="title"><b>Example&nbsp;7.26.&nbsp;
Custom Logging Orphaned Keys
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.OrphanedKeyAction" value="log(Channel=Orphans, Level=DEBUG)"/&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="chapter" id="ref_guide_deploy"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;8.&nbsp;
Deployment
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_deploy_factory">1.
Factory Deployment
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_deploy_factory_standalone">1.1.
Standalone Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_deploy_inject">1.2.
EntityManager Injection
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_enterprise_trans">2.
Integrating with the Transaction Manager
</a></span></dt><dt><span class="section"><a href="#ref_guide_enterprise_xa">3.
XA Transactions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_enterprise_xa_req">3.1.
Using OpenJPA with XA Transactions
</a></span></dt></dl></dd></dl></div>
<p>
OpenJPA deployment includes choosing a factory deployment strategy, and in a
managed environment, optionally integrating with your application server's
managed and XA transactions. This chapter examines each aspect of deployment in
turn.
</p>
<div class="section" id="ref_guide_deploy_factory"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Factory Deployment
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_deploy_factory_standalone">1.1.
Standalone Deployment
</a></span></dt><dt><span class="section"><a href="#ref_guide_deploy_inject">1.2.
EntityManager Injection
</a></span></dt></dl></div>
<p>
OpenJPA offers two <code class="classname">EntityManagerFactory</code>
deployment options.
</p>
<div class="section" id="ref_guide_deploy_factory_standalone"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Standalone Deployment
</h3></div></div></div>
<a class="indexterm" name="d5e15212"></a>
<p>
The JPA Overview describes the <code class="classname">javax.persistence.Persistence
</code> class. You can use <code class="classname">Persistence</code> to obtain
<code class="classname">EntityManagerFactory</code> instances, as demonstrated in
<a class="xref" href="#jpa_overview_persistence" title="Chapter&nbsp;6.&nbsp; Persistence">Chapter&nbsp;6, <i>
Persistence
</i></a>. OpenJPA also extends
<code class="classname">Persistence</code> to add additional <code class="classname">
EntityManagerFactory</code> creation methods. The <code class="classname">
org.apache.openjpa.persistence.OpenJPAPersistence</code> class
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAPersistence.html" target="_top">
Javadoc</a> details these extensions.
</p>
<p>
After obtaining the factory, you can cache it for all <code class="classname">
EntityManager</code> creation duties. OpenJPA factories support being
bound to JNDI as well.
</p>
</div>
<div class="section" id="ref_guide_deploy_inject"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
EntityManager Injection
</h3></div></div></div>
<p>
Java EE application servers allow you to <span class="emphasis"><em>inject</em></span>
entity managers into your session beans using the <code class="literal">PersistenceContext
</code> annotation. See your application server documentation for details.
</p>
</div>
</div>
<div class="section" id="ref_guide_enterprise_trans"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Integrating with the Transaction Manager
</h2></div></div></div>
<a class="indexterm" name="d5e15234"></a>
<a class="indexterm" name="d5e15237"></a>
<a class="indexterm" name="d5e15240"></a>
<a class="indexterm" name="d5e15243"></a>
<p>
OpenJPA <code class="classname">EntityManager</code>s have the ability to automatically
synchronize their transactions with an external transaction manager. Whether
or not <code class="classname">EntityManager</code>s from a given <code class="classname">
EntityManagerFactory</code> exhibit this behavior by default depends on
the transaction type you set for the factory's persistence unit in
your <code class="filename">persistence.xml</code> file. OpenJPA uses the given
transaction type internally to set the
<a class="link" href="#openjpa.TransactionMode" title="5.69.&nbsp; openjpa.TransactionMode"><code class="literal">openjpa.TransactionMode
</code></a> configuration property. This property accepts the following
modes:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">local</code>: Perform transaction operations locally.
</p>
</li><li class="listitem">
<p>
<code class="literal">managed</code>: Integrate with the application server's managed
global transactions.
</p>
</li></ul></div>
<p>
You can override the global transaction mode setting when you obtain an
<code class="classname">EntityManager</code> using the
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/EntityManagerFactory.html" target="_top">
<code class="classname">EntityManagerFactory</code></a>'s
<code class="methodname">createEntityManager(Map props)</code> method. Simply set the
<code class="literal">openjpa.TransactionMode</code> key of the given <code class="classname">Map
</code> to the desired value.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
You can also override the <code class="literal">openjpa.ConnectionUserName</code>,
<code class="literal">openjpa.ConnectionPassword</code>, and <code class="literal">
openjpa.ConnectionRetainMode</code> settings using the given <code class="classname">
Map</code>.
</p>
</div>
<p>
<a class="indexterm" name="d5e15273"></a>
In order to use global transactions, OpenJPA must be able to access the
application server's <code class="classname">
javax.transaction.TransactionManager</code>. OpenJPA can automatically
discover the transaction manager for most major application servers.
Occasionally, however, you might have to point OpenJPA to the transaction
manager for an unrecognized or non-standard application server setup. This is
accomplished through the <a class="link" href="#openjpa.ManagedRuntime" title="5.45.&nbsp; openjpa.ManagedRuntime"><code class="literal">
openjpa.ManagedRuntime</code></a> configuration property. This
property describes an
<a class="ulink" href="../../apidocs/org/apache/openjpa/ee/ManagedRuntime.html" target="_top"><code class="classname">
org.apache.openjpa.ee.ManagedRuntime</code></a> implementation to use
for transaction manager discovery. You can specify your own implementation,
or use one of the built-ins:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">auto</code>: This is the default. It is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/ee/AutomaticManagedRuntime.html" target="_top">
<code class="classname">org.apache.openjpa.ee.AutomaticManagedRuntime</code></a>
class. This managed runtime is able to automatically integrate with several
common application servers.
</p>
</li><li class="listitem">
<p>
<code class="literal">invocation</code>: An alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/ee/InvocationManagedRuntime.html" target="_top">
<code class="classname">org.apache.openjpa.ee.InvocationManagedRuntime</code></a>
class. You can configure this runtime to invoke any static
method in order to obtain the appserver's transaction manager.
</p>
</li><li class="listitem">
<p>
<code class="literal">jndi</code>: An alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/ee/JNDIManagedRuntime.html" target="_top">
<code class="classname">org.apache.openjpa.ee.JNDIManagedRuntime</code></a>
class. You can configure this runtime to look up the transaction manager at
any JNDI location.
</p>
</li></ul></div>
<p>
See the Javadoc for of each class for details on the bean properties
you can pass to these plugins in your configuration string.
</p>
<div class="example" id="ref_guide_enterprise_transex"><p class="title"><b>Example&nbsp;8.1.&nbsp;Configuring Transaction Manager Integration</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.TransactionMode" value="managed"/&gt;
&lt;property name="openjpa.ManagedRuntime" value="jndi(TransactionManagerName=java:/TransactionManager)"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_enterprise_xa"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
XA Transactions
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_enterprise_xa_req">3.1.
Using OpenJPA with XA Transactions
</a></span></dt></dl></div>
<a class="indexterm" name="d5e15302"></a>
<a class="indexterm" name="d5e15305"></a>
<p>
The X/Open Distributed Transaction Processing (X/Open DTP) model, designed by
<a class="ulink" href="http://www.opengroup.org/" target="_top">The Open Group</a> (a vendor consortium),
defines a standard communication architecture that provides the following:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Concurrent execution of applications on shared resources.
</p>
</li><li class="listitem">
<p>
Coordination of transactions across applications.
</p>
</li><li class="listitem">
<p>
Components, interfaces, and protocols that define the architecture and provide
portability of applications.
</p>
</li><li class="listitem">
<p>
Atomicity of transaction systems.
</p>
</li><li class="listitem">
<p>
Single-thread control and sequential function-calling.
</p>
</li></ul></div>
<p>
The X/Open DTP XA standard defines the application programming interfaces that a
resource manager uses to communicate with a transaction manager. The XA
interfaces enable resource managers to join transactions, to perform two-phase
commit, and to recover in-doubt transactions following a failure.
</p>
<div class="section" id="ref_guide_enterprise_xa_req"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;
Using OpenJPA with XA Transactions
</h3></div></div></div>
<p>
OpenJPA supports XA-compliant transactions when used in a properly configured
managed environment. The following components are required:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
A managed environment that provides an XA compliant transaction manager.
Examples of this are application servers such as WebLogic or JBoss.
</p>
</li><li class="listitem">
<p>
Instances of a <code class="classname">javax.sql.XADataSource</code> for each of the
<code class="classname">DataSource</code>s that OpenJPA will use.
</p>
</li></ul></div>
<p>
Given these components, setting up OpenJPA to participate in distributed
transactions is a simple two-step process:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
Integrate OpenJPA with your application server's transaction manager, as
detailed in <a class="xref" href="#ref_guide_enterprise_trans" title="2.&nbsp; Integrating with the Transaction Manager">Section&nbsp;2, &#8220;
Integrating with the Transaction Manager
&#8221;</a> above.
</p>
</li><li class="listitem">
<p>
Point OpenJPA at an enlisted <code class="classname">XADataSource</code>, and configure
a second non-enlisted data source. See
<a class="xref" href="#ref_guide_dbsetup_thirdparty_enlist" title="2.1.&nbsp; Managed and XA DataSources">Section&nbsp;2.1, &#8220;
Managed and XA DataSources
&#8221;</a>.
</p>
</li></ol></div>
</div>
</div>
</div>
<div class="chapter" id="ref_guide_runtime"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;9.&nbsp;
Runtime Extensions
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_runtime_arch">1.
Architecture
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_broker_finalization">1.1.
Broker Finalization
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_broker_extension">1.2.
Broker Customization and Eviction
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_runtime_jpa">2.
JPA Extensions
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_runtime_emfactory">2.1.
OpenJPAEntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_em">2.2.
OpenJPAEntityManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquery">2.3.
OpenJPAQuery
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaextent">2.4.
Extent
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpacache">2.5.
StoreCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquerycache">2.6.
QueryResultCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpafetch">2.7.
FetchPlan
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpaentitytransaction">2.8.
OpenJPAEntityTransaction
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpapersistence">2.9.
OpenJPAPersistence
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_locking">3.
Object Locking
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_locking_default">3.1.
Configuring Default Locking
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_runtime">3.2.
Configuring Lock Levels at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_apis">3.3.
Object Locking APIs
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_lockmgr">3.4.
Lock Manager
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_rules">3.5.
Rules for Locking Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_issues">3.6.
Known Issues and Limitations
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_savepoints">4.
Savepoints
</a></span></dt><dd><dl><dt><span class="section"><a href="#reg_guide_savepoints_using">4.1.
Using Savepoints
</a></span></dt><dt><span class="section"><a href="#ref_guide_savepoints_conf">4.2.
Configuring Savepoints
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_enterprise_methodql">5.
MethodQL
</a></span></dt><dt><span class="section"><a href="#ref_guide_sequence">6.
Generators
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_sequence_runtime">6.1.
Runtime Access
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_runtime_pm_event">7.
Transaction Events
</a></span></dt><dt><span class="section"><a href="#ref_guide_enterprise_abstractstore">8.
Non-Relational Stores
</a></span></dt></dl></div>
<p>
This chapter describes OpenJPA extensions to the standard JPA
interfaces, and outlines some additional features of the OpenJPA runtime.
</p>
<div class="section" id="ref_guide_runtime_arch"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Architecture
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_runtime_broker_finalization">1.1.
Broker Finalization
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_broker_extension">1.2.
Broker Customization and Eviction
</a></span></dt></dl></div>
<p>
Internally, OpenJPA does not adhere to any persistence specification. The
OpenJPA kernel has its own set of APIs and components. Specifications like JPA
and JDO are simply different "personalities" that OpenJPA's native kernel
can adopt.
</p>
<p>
As an OpenJPA user, you will not normally see beneath
OpenJPA's JPA personality. OpenJPA allows you to access its feature set without
leaving the comfort of JPA. Where OpenJPA goes beyond standard JPA
functionality, we have crafted JPA-specific APIs to each OpenJPA extension for
as seamless an experience as possible.
</p>
<p>
When writing OpenJPA plugins or otherwise extending the OpenJPA runtime,
however, you will use OpenJPA's native APIs. So that you won't feel lost, the
list below associates each specification interface with its backing native
OpenJPA component:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="classname">javax.persistence.EntityManagerFactory</code>: <span class="emphasis"><em>
<code class="classname">org.apache.openjpa.kernel.BrokerFactory</code></em></span>
</p>
</li><li class="listitem">
<p>
<code class="classname">javax.persistence.EntityManager</code>: <span class="emphasis"><em><code class="classname">
org.apache.openjpa.kernel.Broker</code></em></span>
</p>
</li><li class="listitem">
<p>
<code class="classname">javax.persistence.Query</code>: <span class="emphasis"><em><code class="classname">
org.apache.openjpa.kernel.Query</code></em></span>
</p>
</li><li class="listitem">
<p>
<code class="classname">org.apache.openjpa.persistence.Extent</code>: <span class="emphasis"><em>
<code class="classname">org.apache.openjpa.kernel.Extent</code></em></span>
</p>
</li><li class="listitem">
<p>
<code class="classname">org.apache.openjpa.persistence.StoreCache</code>: <span class="emphasis"><em>
<code class="classname">org.apache.openjpa.datacache.DataCache</code></em></span>
</p>
</li><li class="listitem">
<p>
<code class="classname">org.apache.openjpa.persistence.QueryResultCache</code>:
<span class="emphasis"><em><code class="classname">org.apache.openjpa.datacache.QueryCache</code>
</em></span>
</p>
</li><li class="listitem">
<p>
<code class="classname">org.apache.openjpa.persistence.FetchPlan</code>: <span class="emphasis"><em>
<code class="classname">org.apache.openjpa.kernel.FetchConfiguration</code></em></span>
</p>
</li><li class="listitem">
<p>
<code class="classname">org.apache.openjpa.persistence.Generator</code>: <span class="emphasis"><em>
<code class="classname">org.apache.openjpa.kernel.Seq</code></em></span>
</p>
</li></ul></div>
<p>
The <a class="link" href="#ref_guide_runtime_openjpapersistence" title="2.9.&nbsp; OpenJPAPersistence"><code class="classname">
org.apache.openjpa.persistence.OpenJPAPersistence</code></a> helper
allows you to convert between <code class="classname">EntityManagerFactories</code> and
<code class="classname">BrokerFactories</code>, <code class="classname">EntityManager</code>s
and <code class="classname">Broker</code>s.
</p>
<div class="section" id="ref_guide_runtime_broker_finalization"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Broker Finalization
</h3></div></div></div>
<a class="indexterm" name="d5e15399"></a>
<p>
Outside of a Java EE application server or other JPA persistence container
environment, the default OpenJPAEntityManager implementation automatically
closes itself during instance finalization. This guards against accidental
resource leaks that may occur if a developer fails to explicitly close
EntityManagers when finished with them, but it also incurs a scalability
bottleneck, since the JVM must perform synchronization during instance creation,
and since the finalizer thread will have more instances to monitor. To avoid
this overhead, set the
<a class="link" href="#openjpa.BrokerImpl" title="5.4.&nbsp; openjpa.BrokerImpl"><code class="literal">openjpa.BrokerImpl</code></a>
configuration property to <code class="literal">non-finalizing</code>.
</p>
</div>
<div class="section" id="ref_guide_runtime_broker_extension"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Broker Customization and Eviction
</h3></div></div></div>
<a class="indexterm" name="d5e15409"></a>
<p>
As a <a class="link" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">plugin string</a>, this property
can be used to configure the <code class="classname"> BrokerImpl</code> with the
following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">EvictFromDataCache</code>: When evicting an object through the
<code class="methodname">OpenJPAEntityManager.evict</code> methods, whether to also
evict it from the OpenJPA's <a class="link" href="#ref_guide_cache" title="1.&nbsp; Data Cache">data cache</a>.
Defaults to <code class="literal">false</code>.
</p>
</li></ul></div>
<div class="example" id="ref_guide_runtime_pm_evictex"><p class="title"><b>Example&nbsp;9.1.&nbsp;
Evict from Data Cache
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.BrokerImpl" value="EvictFromDataCache=true"/&gt;
</pre>
</div></div><br class="example-break">
<p>
Additionally, some advanced users may want to add capabilities to OpenJPA's
internal <a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/BrokerImpl.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.BrokerImpl</code></a>. You can
configure OpenJPA to use a custom subclass of <code class="classname">BrokerImpl</code>
with the <a class="link" href="#openjpa.BrokerImpl" title="5.4.&nbsp; openjpa.BrokerImpl"><code class="literal">openjpa.BrokerImpl
</code></a> configuration property. Set this property to the full class
name of your custom subclass. When implementing your subclass, consider the
finalization issues mentioned in
<a class="xref" href="#ref_guide_runtime_broker_finalization" title="1.1.&nbsp; Broker Finalization">Section&nbsp;1.1, &#8220;
Broker Finalization
&#8221;</a>. It may be appropriate
to create a subtype of both
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/BrokerImpl.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.BrokerImpl</code></a> and
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/FinalizingBrokerImpl.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.FinalizingBrokerImpl</code></a>.
</p>
</div>
</div>
<div class="section" id="ref_guide_runtime_jpa"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
JPA Extensions
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_runtime_emfactory">2.1.
OpenJPAEntityManagerFactory
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_em">2.2.
OpenJPAEntityManager
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquery">2.3.
OpenJPAQuery
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaextent">2.4.
Extent
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpacache">2.5.
StoreCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpaquerycache">2.6.
QueryResultCache
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_jpafetch">2.7.
FetchPlan
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpaentitytransaction">2.8.
OpenJPAEntityTransaction
</a></span></dt><dt><span class="section"><a href="#ref_guide_runtime_openjpapersistence">2.9.
OpenJPAPersistence
</a></span></dt></dl></div>
<p>
The following sections outline the runtime interfaces you can use to access
OpenJPA-specific functionality from JPA. Each interface contains services and
convenience methods missing from the JPA specification. OpenJPA strives to use
the same naming conventions and API patterns as standard JPA methods in all
extensions, so that OpenJPA extension APIs feel as much as possible like
standard JPA.
</p>
<p>
You may have noticed the examples throughout this document using the
<code class="methodname">OpenJPAPersistence.cast</code> methods to cast from standard
JPA interfaces to OpenJPA extended interfaces. This is the recommended practice.
Some application server vendors may proxy OpenJPA's JPA implementation,
preventing a straight cast. <code class="classname">OpenJPAPersistence</code>'s
<code class="methodname">cast</code> methods work around these proxies.
</p>
<pre class="programlisting">
public static OpenJPAEntityManagerFactory cast(EntityManagerFactory emf);
public static OpenJPAEntityManager cast(EntityManager em);
public static OpenJPAQuery cast(Query q);
</pre>
<p>
We provide additional information on the <code class="classname">OpenJPAPersistence
</code> helper <a class="link" href="#ref_guide_runtime_openjpapersistence" title="2.9.&nbsp; OpenJPAPersistence">
below</a>.
</p>
<div class="section" id="ref_guide_runtime_emfactory"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
OpenJPAEntityManagerFactory
</h3></div></div></div>
<a class="indexterm" name="d5e15449"></a>
<a class="indexterm" name="d5e15451"></a>
<p>
The <code class="classname">org.apache.openjpa.persistence.OpenJPAEntityManagerFactory
</code> interface extends the basic <code class="classname">
javax.persistence.EntityManagerFactory</code> with OpenJPA-specific
features. The <code class="classname">OpenJPAEntityManagerFactory</code> offers APIs to
access the OpenJPA data and query caches and to perform other OpenJPA-specific
operations. See the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManagerFactory.html" target="_top">
interface Javadoc</a> for details.
</p>
</div>
<div class="section" id="ref_guide_runtime_em"><div class="titlepage"><div><div><h3 class="title">2.2.&nbsp;
OpenJPAEntityManager
</h3></div></div></div>
<a class="indexterm" name="d5e15462"></a>
<a class="indexterm" name="d5e15464"></a>
<p>
All OpenJPA <code class="classname">EntityManager</code>s implement the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.OpenJPAEntityManager</code>
</a> interface. This interface extends the standard <code class="classname">
javax.persistence.EntityManager</code>. Just as the standard <code class="classname">
EntityManager</code> is the primary window into JPA services, the
<code class="classname">OpenJPAEntityManager</code> is the primary window from JPA into
OpenJPA-specific functionality. We strongly encourage you to investigate the API
extensions this interface contains.
</p>
</div>
<div class="section" id="ref_guide_runtime_jpaquery"><div class="titlepage"><div><div><h3 class="title">2.3.&nbsp;
OpenJPAQuery
</h3></div></div></div>
<a class="indexterm" name="d5e15477"></a>
<a class="indexterm" name="d5e15479"></a>
<p>
OpenJPA extends JPA's standard query functionality with the <code class="classname">
org.apache.openjpa.persistence.OpenJPAQuery</code> interface. See its
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAQuery.html" target="_top">Javadoc
</a> for details on the convenience methods it provides.
</p>
</div>
<div class="section" id="ref_guide_runtime_jpaextent"><div class="titlepage"><div><div><h3 class="title">2.4.&nbsp;
Extent
</h3></div></div></div>
<a class="indexterm" name="d5e15488"></a>
<a class="indexterm" name="d5e15490"></a>
<p>
An <code class="classname">Extent</code> is a logical view of all persistent instances
of a given entity class, possibly including subclasses. OpenJPA adds the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Extent.html" target="_top"><code class="classname">
org.apache.openjpa.persistence.Extent</code></a> class to the set of
Java Persistence APIs. The following code illustrates iterating over all
instances of the <code class="classname">Magazine</code> entity, without subclasses:
</p>
<div class="example" id="ref_guide_runtime_jpaextentex"><p class="title"><b>Example&nbsp;9.2.&nbsp;
Using a JPA Extent
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManager kem = OpenJPAPersistence.cast(em);
Extent&lt;Magazine&gt; mags = kem.createExtent(Magazine.class, false);
for (Magazine m : mags)
processMagazine(m);
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_runtime_jpacache"><div class="titlepage"><div><div><h3 class="title">2.5.&nbsp;
StoreCache
</h3></div></div></div>
<a class="indexterm" name="d5e15504"></a>
<p>
In addition to the <code class="classname">EntityManager</code> object cache the JPA
specification provides access to a second level cache via the
javax.persistence.Cache interface. OpenJPA provides further extensions via
the org.apache.openjpa.persistence.StoreCache interface documented at
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/StoreCache.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.StoreCache</code></a>.
<a class="xref" href="#ref_guide_cache" title="1.&nbsp; Data Cache">Section&nbsp;1, &#8220;
Data Cache
&#8221;</a> has detailed information on OpenJPA's
data caching system, including the <code class="classname">StoreCache</code> facade.
</p>
</div>
<div class="section" id="ref_guide_runtime_jpaquerycache"><div class="titlepage"><div><div><h3 class="title">2.6.&nbsp;
QueryResultCache
</h3></div></div></div>
<a class="indexterm" name="d5e15514"></a>
<p>
OpenJPA can cache query results as well as persistent object data. The
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/QueryResultCache.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.QueryResultCache</code></a>
is an JPA-flavored facade to OpenJPA's internal query cache. See
<a class="xref" href="#ref_guide_cache_query" title="1.4.&nbsp; Query Cache">Section&nbsp;1.4, &#8220;
Query Cache
&#8221;</a> for details on query caching in
OpenJPA.
</p>
</div>
<div class="section" id="ref_guide_runtime_jpafetch"><div class="titlepage"><div><div><h3 class="title">2.7.&nbsp;
FetchPlan
</h3></div></div></div>
<a class="indexterm" name="d5e15522"></a>
<a class="indexterm" name="d5e15524"></a>
<p>
Many of the aforementioned OpenJPA interfaces give you access to an <code class="classname">
org.apache.openjpa.persistence.FetchPlan</code> instance. The <code class="classname">
FetchPlan</code> allows you to exercise some control over how objects are
fetched from the datastore, including <a class="link" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">
large result set support</a>, <a class="link" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">custom fetch
groups</a>, and <a class="link" href="#ref_guide_locking" title="3.&nbsp; Object Locking">lock levels</a>.
</p>
<p>
OpenJPA goes one step further, extending <code class="classname">FetchPlan</code> with
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/jdbc/JDBCFetchPlan.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.jdbc.JDBCFetchPlan</code></a>
to add additional JDBC-specific tuning methods. Unless you have customized
OpenJPA to use a non-relational back-end (see
<a class="xref" href="#ref_guide_enterprise_abstractstore" title="8.&nbsp; Non-Relational Stores">Section&nbsp;8, &#8220;
Non-Relational Stores
&#8221;</a> ), all <code class="classname">
FetchPlan</code>s in OpenJPA implement <code class="classname">
JDBCFetchPlan</code>, so feel free to cast to this interface.
</p>
<p>
Fetch plans pass on from parent components to child components. The <code class="classname">
EntityManagerFactory</code> settings (via your configuration properties)
for things like the fetch size, result set type, and custom fetch groups are
passed on to the fetch plan of the <code class="classname">EntityManager</code>s it
produces. The settings of each <code class="classname">EntityManager</code>, in turn,
are passed on to each <code class="classname">Query</code> and <code class="classname">Extent
</code> it returns. Note that the opposite, however, is not true. Modifying
the fetch plan of a <code class="classname">Query</code> or <code class="classname">Extent
</code> does not affect the <code class="classname">EntityManager</code>'s
configuration. Likewise, modifying an <code class="classname">EntityManager</code>'s
configuration does not affect the <code class="classname"> EntityManagerFactory</code>.
</p>
<p>
<a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a> includes examples using <code class="classname">
FetchPlan</code>s.
</p>
</div>
<div class="section" id="ref_guide_runtime_openjpaentitytransaction"><div class="titlepage"><div><div><h3 class="title">2.8.&nbsp;
OpenJPAEntityTransaction
</h3></div></div></div>
<a class="indexterm" name="d5e15556"></a>
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityTransaction.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.OpenJPAEntityTransaction</code></a>
extends <code class="classname">javax.persistence.EntityTransaction</code> to provide
additional transaction-debugging capabilities and some concurrency-related
commit and rollback features.
</p>
</div>
<div class="section" id="ref_guide_runtime_openjpapersistence"><div class="titlepage"><div><div><h3 class="title">2.9.&nbsp;
OpenJPAPersistence
</h3></div></div></div>
<a class="indexterm" name="d5e15564"></a>
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAPersistence.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.OpenJPAPersistence</code></a>
is a static helper class that adds OpenJPA-specific utility methods to
<code class="classname">javax.persistence.Persistence</code>.
</p>
</div>
</div>
<div class="section" id="ref_guide_locking"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Object Locking
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_locking_default">3.1.
Configuring Default Locking
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_runtime">3.2.
Configuring Lock Levels at Runtime
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_apis">3.3.
Object Locking APIs
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_lockmgr">3.4.
Lock Manager
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_rules">3.5.
Rules for Locking Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_locking_issues">3.6.
Known Issues and Limitations
</a></span></dt></dl></div>
<a class="indexterm" name="d5e15572"></a>
<p>
Controlling how and when objects are locked is an important part of maximizing
the performance of your application under load. This section describes OpenJPA's
APIs for explicit locking, as well as its rules for implicit locking.
</p>
<div class="section" id="ref_guide_locking_default"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;
Configuring Default Locking
</h3></div></div></div>
<a class="indexterm" name="d5e15577"></a>
<p>
<a class="indexterm" name="d5e15581"></a>
<a class="indexterm" name="d5e15584"></a>
<a class="indexterm" name="d5e15586"></a>
You can control OpenJPA's default transactional read and write lock levels
through the <a class="link" href="#openjpa.ReadLockLevel" title="5.60.&nbsp; openjpa.ReadLockLevel"><code class="literal">
openjpa.ReadLockLevel</code></a> and
<a class="link" href="#openjpa.WriteLockLevel" title="5.71.&nbsp; openjpa.WriteLockLevel"><code class="literal">openjpa.WriteLockLevel</code>
</a> configuration properties. Each property accepts a value of <code class="literal">
none</code>, <code class="literal">read</code>, <code class="literal">write</code>,
<code class="literal">optimistic</code>, <code class="literal">optimistic-force-increment</code>,
<code class="literal">pessimistic-read</code>, <code class="literal">pessimistic-write</code>,
<code class="literal">pessimistic-force-increment</code>, or a number
corresponding to a lock level defined by the
<a class="link" href="#ref_guide_locking_lockmgr" title="3.4.&nbsp; Lock Manager">lock manager</a> in use. These
properties apply only to non-optimistic transactions; during optimistic
transactions, OpenJPA never locks objects by default.
</p>
<p>
<a class="indexterm" name="d5e15602"></a>
<a class="indexterm" name="d5e15604"></a>
You can control the default amount of time OpenJPA will wait when trying to
obtain locks through the <a class="link" href="#openjpa.LockTimeout" title="5.43.&nbsp; openjpa.LockTimeout"><code class="literal">
openjpa.LockTimeout</code></a> configuration property. Set this property
to the number of milliseconds you are willing to wait for a lock before OpenJPA
will throw an exception, or to -1 for no limit. It defaults to -1.
</p>
<div class="example" id="ref_guide_locking_default_conf"><p class="title"><b>Example&nbsp;9.3.&nbsp;
Setting Default Lock Levels
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.ReadLockLevel" value="none"/&gt;
&lt;property name="openjpa.WriteLockLevel" value="write"/&gt;
&lt;property name="openjpa.LockTimeout" value="30000"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_locking_runtime"><div class="titlepage"><div><div><h3 class="title">3.2.&nbsp;
Configuring Lock Levels at Runtime
</h3></div></div></div>
<a class="indexterm" name="d5e15614"></a>
<p>
At runtime, you can override the default lock levels through the <code class="classname">
FetchPlan</code> interface described above. At the beginning of each
datastore transaction, OpenJPA initializes the <code class="classname"> EntityManager
</code>'s fetch plan with the default lock levels and timeouts described
in the previous section. By changing the fetch plan's locking properties, you
can control how objects loaded at different points in the transaction are
locked. You can also use the fetch plan of an individual <code class="classname">Query
</code> to apply your locking changes only to objects loaded through that
<code class="classname">Query</code>.
</p>
<pre class="programlisting">
public LockModeType getReadLockMode();
public FetchPlan setReadLockMode(LockModeType mode);
public LockModeType getWriteLockMode();
public FetchPlan setWriteLockMode(LockModeType mode);
long getLockTimeout();
FetchPlan setLockTimeout(long timeout);
</pre>
<p>
Controlling locking through these runtime APIs works even during optimistic
transactions. At the end of the transaction, OpenJPA resets the fetch plan's
lock levels to <code class="literal">none</code>. You cannot lock objects outside of a
transaction.
</p>
<div class="example" id="ref_guide_locking_fetch"><p class="title"><b>Example&nbsp;9.4.&nbsp;
Setting Runtime Lock Levels
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
EntityManager em = ...;
em.getTransaction().begin();
// load stock we know we're going to update at write lock mode
Query q = em.createQuery("select s from Stock s where symbol = :s");
q.setParameter("s", symbol);
OpenJPAQuery oq = OpenJPAPersistence.cast(q);
FetchPlan fetch = oq.getFetchPlan();
fetch.setReadLockMode(LockModeType.WRITE);
fetch.setLockTimeout(3000); // 3 seconds
Stock stock = (Stock) q.getSingleResult();
// load an object we don't need locked at none lock mode
fetch = OpenJPAPersistence.cast(em).getFetchPlan();
fetch.setReadLockMode(null);
Market market = em.find(Market.class, marketId);
stock.setPrice(market.calculatePrice(stock));
em.getTransaction().commit();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_locking_apis"><div class="titlepage"><div><div><h3 class="title">3.3.&nbsp;
Object Locking APIs
</h3></div></div></div>
<a class="indexterm" name="d5e15630"></a>
<p>
In addition to allowing you to control implicit locking levels, OpenJPA provides
explicit APIs to lock objects and to retrieve their current lock level.
</p>
<pre class="programlisting">
public LockModeType OpenJPAEntityManager.getLockMode(Object pc);
</pre>
<p>
Returns the level at which the given object is currently locked.
</p>
<p>
In addition to the standard
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/EntityManager.html" target="_top">
<code class="methodname">EntityManager.lock(Object, LockModeType)</code></a>
method, the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">OpenJPAEntityManager</code></a> exposes the following
methods to lock objects explicitly:
</p>
<pre class="programlisting">
public void lock(Object pc);
public void lock(Object pc, LockModeType mode, long timeout);
public void lockAll(Object... pcs);
public void lockAll(Object... pcs, LockModeType mode, long timeout);
public void lockAll(Collection pcs);
public void lockAll(Collection pcs, LockModeType mode, long timeout);
</pre>
<p>
Methods that do not take a lock level or timeout parameter default to the
current fetch plan. The example below demonstrates these methods in action.
</p>
<div class="example" id="ref_guide_locking_explicit"><p class="title"><b>Example&nbsp;9.5.&nbsp;
Locking APIs
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
// retrieve the lock level of an object
OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
Stock stock = ...;
LockModeType level = oem.getLockMode(stock);
if (level == OpenJPAModeType.WRITE) ...
...
oem.setOptimistic(true);
oem.getTransaction().begin();
// override default of not locking during an opt trans to lock stock object
oem.lock(stock, LockModeType.WRITE, 1000);
stock.setPrice(market.calculatePrice(stock));
oem.getTransaction().commit();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_locking_lockmgr"><div class="titlepage"><div><div><h3 class="title">3.4.&nbsp;
Lock Manager
</h3></div></div></div>
<a class="indexterm" name="d5e15648"></a>
<p>
<a class="indexterm" name="d5e15652"></a>
OpenJPA delegates the actual work of locking objects to the system's
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/LockManager.html" target="_top"><code class="classname">
org.apache.openjpa.kernel.LockManager</code></a>. This plugin is
controlled by the <a class="link" href="#openjpa.LockManager" title="5.42.&nbsp; openjpa.LockManager"><code class="literal">
openjpa.LockManager</code></a> configuration property. You can write your
own lock manager, or use one of the bundled options:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">mixed</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/MixedLockManager.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.MixedLockManager</code>
</a>, which implements the JPA 2.0 specification entity locking behaviors.
It combines both the optimistic and pessimistic semantics controlled by
lock mode argument in methods define in the EntityManager
and Query interfaces or OpenJPA lock level properties.
</p>
<p>
The <code class="literal">mixed</code> LockManager inherits all the properties available
from <code class="literal">version</code> and <code class="literal">pessimistic</code> LockManagers.
For example: <code class="literal">VersionCheckOnReadLock</code> and
<code class="literal">VersionUpdateOnWriteLock</code> properties.
</p>
<p>
This is the default <code class="literal">openjpa.LockManager</code> setting in OpenJPA.
</p>
</li><li class="listitem">
<p>
<code class="literal">pessimistic</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/PessimisticLockManager.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.PessimisticLockManager</code>
</a>, which
uses SELECT FOR UPDATE statements (or the database's equivalent) to lock the
database rows corresponding to locked objects. This lock
manager does not distinguish between read locks and write locks; all locks are
write locks.
</p>
<p>
The <code class="literal">pessimistic</code> LockManager can be configured to additionally
perform the version checking and incrementing behavior of the <code class="literal">version
</code> lock manager described below by setting its <code class="literal">
VersionCheckOnReadLock</code> and <code class="literal">VersionUpdateOnWriteLock</code>
properties:
</p>
<pre class="programlisting">
&lt;property name="openjpa.LockManager" value="pessimistic(VersionCheckOnReadLock=true,VersionUpdateOnWriteLock=true)"/&gt;
</pre>
</li><li class="listitem">
<p>
<code class="literal">version</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/VersionLockManager.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.VersionLockManager</code></a>.
This lock manager does not perform any exclusive locking, but instead ensures
read consistency by verifying that the version of all read-locked instances is
unchanged at the end of the transaction. Furthermore, a write lock will force an
increment to the version at the end of the transaction, even if the object is
not otherwise modified. This ensures read consistency with non-blocking
behavior.
</p>
</li><li class="listitem">
<p>
<code class="literal">none</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/NoneLockManager.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.NoneLockManager</code></a>, which
does not perform any locking at all.
</p>
</li></ul></div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
In order for the <code class="literal">version</code> or <code class="literal">mixed</code> lock
managers to prevent the dirty
read phenomenon, the underlying data store's transaction isolation level must be
set to the equivalent of "read committed" or higher.
</p>
</div>
<div class="example" id="ref_guide_locking_disable"><p class="title"><b>Example&nbsp;9.6.&nbsp;
Disabling Locking
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.LockManager" value="none"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_locking_rules"><div class="titlepage"><div><div><h3 class="title">3.5.&nbsp;
Rules for Locking Behavior
</h3></div></div></div>
<a class="indexterm" name="d5e15702"></a>
<a class="indexterm" name="d5e15705"></a>
<p>
Advanced persistence concepts like lazy-loading and object uniquing create
several locking corner-cases. The rules below outline OpenJPA's implicit locking
behavior in these cases.
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
When an object's state is first read within a transaction, the object is locked
at the fetch plan's current read lock level. Future reads of additional lazy
state for the object will use the same read lock level, even if the fetch plan's
level has changed.
</p>
</li><li class="listitem">
<p>
When an object's state is first modified within a transaction, the object is
locked at the write lock level in effect when the object was first read, even if
the fetch plan's level has changed. If the object was not read previously, the
current write lock level is used.
</p>
</li><li class="listitem">
<p>
When objects are accessed through a persistent relation field, the related
objects are loaded with the fetch plan's current lock levels, not the lock
levels of the object owning the field.
</p>
</li><li class="listitem">
<p>
Whenever an object is accessed within a transaction, the object is re-locked at
the current read lock level. The current read and write lock levels become those
that the object "remembers" according to rules one and two above.
</p>
</li><li class="listitem">
<p>
If you lock an object explicitly through the APIs demonstrated above, it is
re-locked at the specified level. This level also becomes both the read and
write level that the object "remembers" according to rules one and two above.
</p>
</li><li class="listitem">
<p>
When an object is already locked at a given lock level, re-locking at a lower
level has no effect. Locks cannot be downgraded during a transaction.
</p>
</li></ol></div>
</div>
<div class="section" id="ref_guide_locking_issues"><div class="titlepage"><div><div><h3 class="title">3.6.&nbsp;
Known Issues and Limitations
</h3></div></div></div>
<a class="indexterm" name="d5e15724"></a>
<p>
Due to performance concerns and database limitations, locking cannot be perfect.
You should be aware of the issues outlined in this section, as they may affect
your application.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Typically, during optimistic transactions OpenJPA does not start an actual
database transaction until you flush or the optimistic transaction commits. This
allows for very long-lived transactions without consuming database resources.
When using the pessimistic lock manager, however, OpenJPA must begin a database
transaction whenever you decide to lock an object during an optimistic
transaction. This is because the pessimistic lock manager uses database locks,
and databases cannot lock rows without a transaction in progress. OpenJPA will
log an INFO message to the <code class="literal">openjpa.Runtime</code> logging channel
when it begins a datastore transaction just to lock an object.
</p>
</li><li class="listitem">
<p>
In order to maintain reasonable performance levels when loading object state,
OpenJPA can only guarantee that an object is locked at the proper lock level
<span class="emphasis"><em>after</em></span> the state has been retrieved from the database. This
means that it is technically possible for another transaction to "sneak in" and
modify the database record after OpenJPA retrieves the state, but before it
locks the object. The only way to positively guarantee that the object is locked
and has the most recent state to refresh the object after locking it.
</p>
<p>
When using the pessimistic lock manager, the case above can only occur when
OpenJPA cannot issue the state-loading SELECT as a locking statement due to
database limitations. For example, some databases cannot lock SELECTs that use
joins. The pessimistic lock manager will log an INFO message to the <code class="literal">
openjpa.Runtime</code> logging channel whenever it cannot lock the initial
SELECT due to database limitations. By paying attention to these log messages,
you can see where you might consider using an object refresh to guarantee that
you have the most recent state, or where you might rethink the way you load the
state in question to circumvent the database limitations that prevent OpenJPA
from issuing a locking SELECT in the first place.
</p>
</li><li class="listitem">
<p>
When using the pessimistic lock manager and named queries you will see the following
<code class="literal">WARNING</code> message logged if you do not specify a lockMode on the named query
or you explicitly set it to <code class="literal">LockModeType.NONE</code>. When using the pessimistic
lock manager a <code class="literal">LockModeType.NONE</code> will always be promoted to <code class="literal">LockModeType.READ</code>.
</p><pre class="programlisting">
WARN [main] openjpa.MetaData - Encountered a read lock level less than LockModeType.READ when processing the NamedQuery annotation "findEmployeeById" in class "org.apache.openjpa.persistence.lockmgr.LockEmployee". Setting query lock level to LockModeType.READ.
</pre><p>
If you are using the pessimistic lock manager and you truly do want to set the lock mode to NONE for a
given query, you can use a fetch plan to do so.
</p><pre class="programlisting">
OpenJPAQuery q = em.createNamedQuery("findEmployeeById");
FetchPlan fp = q.getFetchPlan();
fp.setReadLockMode(LockModeType.NONE);
</pre><p>
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_savepoints"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Savepoints
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#reg_guide_savepoints_using">4.1.
Using Savepoints
</a></span></dt><dt><span class="section"><a href="#ref_guide_savepoints_conf">4.2.
Configuring Savepoints
</a></span></dt></dl></div>
<a class="indexterm" name="d5e15747"></a>
<p>
Savepoints allow for fine grained control over the transactional behavior of
your application. OpenJPA's savepoint API allow you to set intermediate rollback
points in your transaction. You can then choose to rollback changes made only
after a specific savepoint, then commit or continue making new changes in the
transaction. This feature is useful for multi-stage transactions, such as
editing a set of objects over several web pages or user screens. Savepoints also
provide more flexibility to conditional transaction behavior, such as choosing to
commit or rollback a portion of the transaction based on the results of the
changes. This chapter describes how to use and configure OpenJPA savepoints.
</p>
<div class="section" id="reg_guide_savepoints_using"><div class="titlepage"><div><div><h3 class="title">4.1.&nbsp;
Using Savepoints
</h3></div></div></div>
<p>
OpenJPA's
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">OpenJPAEntityManager</code></a> have the following
methods to control savepoint behavior. Note that the savepoints work in tandem
with the current transaction. This means that savepoints require an open
transaction, and that a rollback of the transaction will rollback all of the
changes in the transaction regardless of any savepoints set.
</p>
<pre class="programlisting">
void setSavepoint(String name);
void releaseSavepoint(String name);
void rollbackToSavepoint(String name);
</pre>
<p>
To set a savepoint, simply call <code class="methodname">setSavepoint</code>, passing
in a symbolic savepoint name. This savepoint will define a point at which you
can preserve the state of transactional objects for the duration of the current
transaction.
</p>
<p>
Having set a named savepoint, you can rollback changes made after that point by
calling <code class="methodname">rollbackToSavepoint</code>. This method will keep the
current transaction active, while restoring all transactional instances back to
their saved state. Instances that were deleted after the save point will no
longer be marked for deletion. Similarly, transient instances that were made
persistent after the savepoint will become transient again. Savepoints made
after this savepoint will be released and no longer valid, although you can
still set new savepoints. Savepoints will also be cleared after the current
transaction is committed or rolled back.
</p>
<p>
If a savepoint is no longer needed, you can release any resources it is
consuming resources by calling <code class="methodname">releaseSavepoint</code>. This
method should not be called for savepoints that have been
released automatically through other means, such as commit of a transaction or
rollback to a prior savepoint. While savepoints made after this savepoint will
also be released, there are no other effects on the current transaction.
</p>
<p>
The following simple example illustrates setting, releasing, and rolling back to
a savepoint.
</p>
<div class="example" id="ref_guide_savepoints_example"><p class="title"><b>Example&nbsp;9.7.&nbsp;
Using Savepoints
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
oem.getTransaction().begin();
Magazine mag = oem.find(Magazine.class, id);
mag.setPageCount(300);
oem.setSavepoint("pages");
mag.setPrice(mag.getPageCount() * pricePerPage);
// we decide to release "pages"...
oem.releaseSavepoint("pages");
// ... and set a new savepoint which includes all changes
oem.setSavepoint("price");
mag.setPrice(testPrice);
// we determine the test price is not good
oem.rollbackToSavepoint("price");
// had we chosen to not release "pages", we might have rolled back to
// "pages" instead
// the price is now restored to mag.getPageCount() * pricePerPage
oem.getTransaction().commit();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_savepoints_conf"><div class="titlepage"><div><div><h3 class="title">4.2.&nbsp;
Configuring Savepoints
</h3></div></div></div>
<p>
OpenJPA uses the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/SavepointManager" target="_top">
<code class="classname">org.apache.openjpa.kernel.SavepointManager</code></a>
<a class="link" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">plugin</a> to handle preserving the
savepoint state. OpenJPA includes the following <code class="classname">SavepointManager
</code> plugins:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">in-mem</code>: The default. This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/InMemorySavepointManager.html" target="_top"><code class="classname">
org.apache.openjpa.kernel.InMemorySavepointManager</code></a>. This
plugin stores all state, including field values, in memory. Due to this
behavior, each set savepoint is designed for small to medium transactional
object counts.
</p>
</li><li class="listitem">
<p>
<code class="literal">jdbc</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/JDBC3SavepointManager.html" target="_top"><code class="classname">
org.apache.openjpa.jdbc.kernel.JDBC3SavepointManager</code></a>. This
plugin requires <code class="literal">JDBC 3</code> and <code class="classname"> java.sql.Savepoint
</code> support to operate. Note that this plugin implements savepoints by
issuing a flush to the database.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_enterprise_methodql"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
MethodQL
</h2></div></div></div>
<a class="indexterm" name="d5e15788"></a>
<a class="indexterm" name="d5e15790"></a>
<p>
If JPQL and SQL queries do not match your needs, OpenJPA also allows you to name
a Java method to use to load a set of objects. In a <span class="emphasis"><em>MethodQL
</em></span> query, the query string names a static method to invoke to determine
the matching objects:
</p>
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
// the method query language is 'openjpa.MethodQL'.
// set the query string to the target method to execute, prefixed by fullly-
// qualified class name.
// If a candidate class has been specified for the query, then if the class is
// in the candidate class' package or in the query imports, you can omit the
// package. If the method is in the candidate class, you can omit the class name
// and just specify the method name.
OpenJPAEntityManager oem = OpenJPAPersistence.cast(emf);
OpenJPAQuery q = oem.createQuery("openjpa.MethodQL", "com.xyz.Finder.getByName");
// parameters are passed the same way as in standard queries
// but you have to declare the parameters with their types on the implementation
// Unwrap the implementation and declare parameters with types in a
// comma-separated list
q.unwrap(org.apache.openjpa.kernel.Query.class)
.declareParameters("String firstName, String lastName");
q.setParameter("firstName", "Fred").setParameter("lastName", "Lucas");
// this executes the target method to get the results
List results = q.getResultList();
// The result is returned as a list but the element(s) in the list is determined
// by the returned value of the target method
</pre>
<p>
For datastore queries, the method must have the following signature:
</p>
<pre class="programlisting">
public static <a class="ulink" href="../../apidocs/org/apache/openjpa/lib/rop/ResultObjectProvider.html" target="_top">ResultObjectProvider</a> xxx(<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/StoreContext.html" target="_top">StoreContext</a> ctx, <a class="ulink" href="../../apidocs/org/apache/openjpa/meta/ClassMetaData.html" target="_top">ClassMetaData</a> meta, boolean subclasses, Map params, <a class="ulink" href="../javadoc/org/apache/openjpa/kernel/FetchConfiguration.html" target="_top">FetchConfiguration </a> fetch)
</pre>
<p>
The returned result object provider should produce objects of the candidate
class that match the method's search criteria. If the returned objects do not
have all fields in the given fetch configuration loaded, OpenJPA will make
additional trips to the datastore as necessary to fill in the data for the
missing fields.
</p>
<p>
In-memory execution is slightly different, taking in one object at a time and
returning a boolean on whether the object matches the query:
</p>
<pre class="programlisting">
public static boolean xxx(<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/StoreContext.html" target="_top">StoreContext</a> ctx, <a class="ulink" href="../../apidocs/org/apache/openjpa/meta/ClassMetaData.html" target="_top">ClassMetaData</a> meta, boolean subclasses, Object obj, Map params, <a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/FetchConfiguration.html" target="_top">FetchConfiguration</a> fetch)
</pre>
<p>
In both method versions, the given <code class="literal">params</code> map contains the
names and values of all the parameters for the query.
</p>
</div>
<div class="section" id="ref_guide_sequence"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
Generators
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_sequence_runtime">6.1.
Runtime Access
</a></span></dt></dl></div>
<a class="indexterm" name="d5e15813"></a>
<p>
The JPA Overview's <a class="xref" href="#jpa_overview_mapping" title="Chapter&nbsp;13.&nbsp; Mapping Metadata">Chapter&nbsp;13, <i>
Mapping Metadata
</i></a> details using
generators to automatically populate identity fields in JPA.
</p>
<p>
OpenJPA represents all generators internally with the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/Seq.html" target="_top"><code class="classname">
org.apache.openjpa.kernel.Seq</code></a> interface. This interface
supplies all the context you need to create your own custom generators,
including the current persistence environment, the JDBC <code class="classname">DataSource
</code>, and other essentials. The
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/AbstractJDBCSeq.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq</code></a>
helps you create custom JDBC-based sequences. OpenJPA also supplies the
following built-in <code class="classname">Seq</code>s:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="indexterm" name="d5e15828"></a>
<code class="literal">table</code>: This is OpenJPA's default implementation. It is an
alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/TableJDBCSeq.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.TableJDBCSeq</code></a>
class. The <code class="classname">TableJDBCSeq</code> uses a special single-row table
to store a global sequence number. If the table does not already exist, it is
created the first time you run the
<a class="link" href="#ref_guide_mapping_mappingtool" title="1.&nbsp; Forward Mapping">mapping tool</a> on a class
that requires it. You can also use the class's <code class="methodname">main</code>
method to manipulate the table; see the
<code class="methodname">TableJDBCSeq.main</code> method Javadoc for usage details.
</p>
<p>
This <code class="classname">Seq</code> has the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">Table</code>: The name of the sequence number table to use.
Defaults to <code class="literal">OPENJPA_SEQUENCE_TABLE</code>. If the entities are
mapped to the same table name but with different schema name within one
PersistenceUnit, one <code class="literal">OPENJPA_SEQUENCE_TABLE</code> is created
for each schema.
</p>
</li><li class="listitem">
<p>
<code class="literal">PrimaryKeyColumn</code>: The name of the primary key column for the
sequence table. Defaults to <code class="literal">ID</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">SequenceColumn</code>: The name of the column that will hold the
current sequence value. Defaults to <code class="literal">SEQUENCE_VALUE</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">Allocate</code>: The number of values to allocate on each database
trip. Defaults to 50, meaning the class will set aside the next 50 numbers each
time it accesses the sequence table, which in turn means it only has to make a
database trip to get new sequence numbers once every 50 sequence number
requests.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e15859"></a>
<code class="literal">class-table</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/ClassTableJDBCSeq.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.ClassTableJDBCSeq</code></a>
. This <code class="classname">Seq</code> is like the <code class="classname">TableJDBCSeq
</code> above, but maintains a separate table row, and therefore a separate
sequence number, for each base persistent class. It has all the properties of
the <code class="classname">TableJDBCSeq</code>. Its table name defaults to <code class="literal">
OPENJPA_SEQUENCES_TABLE</code>. It also adds the following properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">IgnoreUnmapped</code>: Whether to ignore unmapped base classes, and
instead use one row per least-derived mapped class. Defaults to <code class="literal">
false</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">UseAliases</code>: Whether to use each class' entity name as the
primary key value of each row, rather than the full class name. Defaults to
<code class="literal">false</code>.
</p>
</li></ul></div>
<p>
As with the <code class="classname">TableJDBCSeq</code>, the <code class="classname">
ClassTableJDBCSeq</code> creates its table automatically during mapping
tool runs. However, you can manually manipulate the table through the class'
<code class="methodname">main</code> method. See the Javadoc for the
<code class="methodname"> ClassTableJDBCSeq.main</code> method for usage details.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e15885"></a>
<code class="literal">value-table</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/ValueTableJDBCSeq.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.ValueTableJDBCSeq</code></a>
. This <code class="classname">Seq</code> is like the <code class="classname">ClassTableJDBCSeq
</code> above, but has an arbitrary number of rows for sequence values,
rather than a fixed pattern of one row per class. Its table defaults to
<code class="literal">OPENJPA_SEQUENCES_TABLE</code>. It has all the properties of the
<code class="classname">TableJDBCSeq</code>, plus:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">PrimaryKeyValue</code>: The primary key value used by this instance.
</p>
</li></ul></div>
<p>
As with the <code class="classname">TableJDBCSeq</code>, the <code class="classname">
ValueTableJDBCSeq</code> creates its table automatically during mapping
tool runs. However, you can manually manipulate the table through the class'
<code class="methodname">main</code> method. See the Javadoc for the
<code class="methodname">ValueTableJDBCSeq.main</code> method for usage details.
</p>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e15906"></a>
<code class="literal">native</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/kernel/NativeJDBCSeq.html" target="_top">
<code class="classname">org.apache.openjpa.jdbc.kernel.NativeJDBCSeq</code></a>.
Many databases have a concept of "native sequences" - a built-in mechanism for
obtaining incrementing numbers. For example, in Oracle database, you can create a
database sequence with a statement like <code class="literal">CREATE SEQUENCE MYSEQUENCE
</code>. Sequence values can then be atomically obtained and incremented
with the statement <code class="literal">SELECT MYSEQUENCE.NEXTVAL FROM DUAL</code>.
OpenJPA provides support for this common mechanism of sequence generation with
the <code class="classname"> NativeJDBCSeq</code>, which accepts the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">Sequence</code>: The name of the database sequence. Defaults to
<code class="literal">OPENJPA_SEQUENCE</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">InitialValue</code>: The initial sequence value. Defaults to 1.
</p>
</li><li class="listitem">
<p>
<code class="literal">Increment</code>: The amount the sequence increments. Defaults to 1.
</p>
</li><li class="listitem">
<p>
<code class="literal">Allocate</code>: The number of values to allocate on each database
trip. Defaults to 50, meaning the class will set aside the next 50 numbers each
time it accesses the sequence, which in turn means it only has to make a
database trip to get new sequence numbers once every 50 sequence number
requests.
</p>
</li></ul></div>
</li><li class="listitem">
<p>
<a class="indexterm" name="d5e15931"></a>
<code class="literal">time</code>: This is an alias for the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/TimeSeededSeq.html" target="_top">
<code class="classname">org.apache.openjpa.kernel.TimeSeededSeq</code></a>. This
type uses an in-memory static counter, initialized to the current time in
milliseconds and monotonically incremented for each value requested. It is only
suitable for single-JVM environments.
</p>
</li></ul></div>
<p>
You can use JPA <code class="literal">SequenceGenerator</code>s to describe any built-in
<code class="classname">Seq</code>s or your own <code class="classname">Seq</code>
implementation. Set the <code class="literal">sequenceName</code> attribute to a plugin
string describing your choice.
</p>
<div class="blockquote"><blockquote class="blockquote">
<p>
If specifying your own class name, you must include parentheses at the end of
the class name, even if you have no plugin properties to configure.
(E.g., <code class="literal">sequenceName="com.example.SeqImpl()"</code>.
</p>
</blockquote></div>
<p>
See <a class="xref" href="#jpa_overview_mapping_sequence" title="5.&nbsp; Generators">Section&nbsp;5, &#8220;
Generators
&#8221;</a> in the JPA Overview for
details on defining <code class="literal">SequenceGenerator</code>s.
</p>
<p>
See <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a> for plugin string formatting.
</p>
<div class="example" id="ref_guide_sequence_named"><p class="title"><b>Example&nbsp;9.8.&nbsp;
Named Seq Sequence
</b></p><div class="example-contents">
<pre class="programlisting">
@Entity
@Table(name="AUTO")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="AuthorSeq")
@SequenceGenerator(name="AuthorSeq", sequenceName="table(Table=AUTO_SEQ)", allocationSize=100)
@Column(name="AID")
private long id;
...
}
</pre>
<p>
Note that if you want to use a plugin string without any arguments, you must
still suffix the plugin type with <code class="literal">()</code> to differentiate it from
a sequence name in the <code class="literal">SequenceGenerator.sequenceName</code> attribute:
</p>
<pre class="programlisting">
@SequenceGenerator(name="AuthorSeq", sequenceName="table()")
</pre>
</div></div><br class="example-break">
<p>
OpenJPA maintains a <span class="emphasis"><em>system</em></span> sequence to generate datastore
identity values for classes that do not declare a specific datastore identity
strategy. You can configure the system sequence through the
<a class="link" href="#openjpa.Sequence" title="5.67.&nbsp; openjpa.Sequence"><code class="literal">openjpa.Sequence</code></a>
configuration property. This property accepts a plugin string describing a
<code class="classname">Seq</code> instance.
</p>
<div class="example" id="ref_guide_sequence_systemex"><p class="title"><b>Example&nbsp;9.9.&nbsp;
System Sequence Configuration
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.Sequence" value="time(Increment=100)"/&gt;
</pre>
</div></div><br class="example-break">
<p>
In JPA, set your <code class="literal">GeneratedValue</code> annotation's <code class="literal">
strategy</code> attribute to <code class="literal">AUTO</code> to use the configured
system sequence. Or, because <code class="literal">AUTO</code> is the default strategy,
use the annotation without attributes:
</p>
<pre class="programlisting">
@GeneratedValue
private long id;
</pre>
<div class="section" id="ref_guide_sequence_runtime"><div class="titlepage"><div><div><h3 class="title">6.1.&nbsp;
Runtime Access
</h3></div></div></div>
<a class="indexterm" name="d5e15973"></a>
<p>
OpenJPA allows you to access named generators at runtime through the
<code class="methodname">OpenJPAEntityManager.getNamedGenerator</code> method:
</p>
<pre class="programlisting">
public Generator getNamedGenerator(String name);
</pre>
<p>
The returned
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/Generator.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.Generator</code></a> is a
facade over an internal OpenJPA <code class="classname">Seq</code>.
</p>
<p>
The <code class="classname">OpenJPAEntityManager</code> includes additional APIs to
retrieve the identity generator of any class, or the generator of any field.
With these APIs, you do not have to know the generator name. Additionally, they
allow you to access the implicit generator used by default for datastore
identity classes. See the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
Javadoc</a> for the <code class="methodname"> OpenJPAEntityManager.getIdentityGenerator
</code> and <code class="methodname">OpenJPAEntityManager.getFieldGenerator
</code> methods for API details.
</p>
</div>
</div>
<div class="section" id="ref_guide_runtime_pm_event"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
Transaction Events
</h2></div></div></div>
<a class="indexterm" name="d5e15990"></a>
<p>
The OpenJPA runtime supports broadcasting transaction-related events. By
registering one or more
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/TransactionListener.html" target="_top">
<code class="classname">org.apache.openjpa.event.TransactionListener</code></a> s,
you can receive notifications when transactions begin, flush, rollback, commit,
and more. Where appropriate, event notifications include the set of
persistence-capable objects participating in the transaction.
</p>
<pre class="programlisting">
public void addTransactionListener(Object listener);
public void removeTransactionListener(Object listener);
</pre>
<p>
These <code class="classname">OpenJPAEntityManagerSPI</code> methods allow you to add
and remove listeners. These methods are outside the bounds of the published OpenJPA APIs, and are subject to change in the future.
</p>
<p>
For details on the transaction framework, see the <code class="literal">
org.apache.openjpa.event</code> package
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/package-summary.html" target="_top">Javadoc</a>.
Also see <a class="xref" href="#ref_guide_event" title="2.&nbsp; Remote Event Notification Framework">Section&nbsp;2, &#8220;
Remote Event Notification Framework
&#8221;</a> for a description of OpenJPA's
remote event support.
</p>
</div>
<div class="section" id="ref_guide_enterprise_abstractstore"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;
Non-Relational Stores
</h2></div></div></div>
<p>
It is possible to adapt OpenJPA to access a non-relational datastore by creating
an implementation of the
<a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/StoreManager.html" target="_top"><code class="literal">
org.apache.openjpa.kernel.StoreManager</code></a> interface. OpenJPA
provides an abstract <code class="literal">StoreManager</code> implementation to
facilitate this process. See the <code class="literal">org.apache.openjpa.abstractstore
</code> package <a class="ulink" href="../../apidocs/org/apache/openjpa/abstractstore/package-summary.html" target="_top">
Javadoc</a> for details.
</p>
</div>
</div>
<div class="chapter" id="ref_guide_caching"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;10.&nbsp;
Caching
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_cache">1.
Data Cache
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache_conf">1.1.
Data Cache Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_data_cache">1.1.1.
openjpa.DataCache Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_shared_cache_mode_integration">1.1.2.
Integration with JPA standard shared cache mode
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_distribution">1.1.3. Distributing instances across cache partitions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_use">1.2.
Data Cache Usage
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache_use_JPA">1.2.1. Using the JPA standard Cache interface</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_use_openJPA">1.2.2. Using the OpenJPA StoreCache extensions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_statistics">1.3.
Cache Statistics
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_query">1.4.
Query Cache
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_extension">1.5.
Cache Extension
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_notes">1.6.
Important Notes
</a></span></dt><dt><span class="section"><a href="#datastore_cache_issues">1.7.
Known Issues and Limitations
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_querycomp">2.
Query Compilation Cache
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_querysql">3. Prepared SQL Cache</a></span></dt></dl></div>
<p>
OpenJPA utilizes several configurable caches to maximize performance. This
chapter explores OpenJPA's data cache, query cache, and query compilation cache.
</p>
<div class="section" id="ref_guide_cache"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Data Cache
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_cache_conf">1.1.
Data Cache Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_data_cache">1.1.1.
openjpa.DataCache Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_shared_cache_mode_integration">1.1.2.
Integration with JPA standard shared cache mode
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_distribution">1.1.3. Distributing instances across cache partitions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_use">1.2.
Data Cache Usage
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_cache_use_JPA">1.2.1. Using the JPA standard Cache interface</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_use_openJPA">1.2.2. Using the OpenJPA StoreCache extensions</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_cache_statistics">1.3.
Cache Statistics
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_query">1.4.
Query Cache
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_extension">1.5.
Cache Extension
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_notes">1.6.
Important Notes
</a></span></dt><dt><span class="section"><a href="#datastore_cache_issues">1.7.
Known Issues and Limitations
</a></span></dt></dl></div>
<a class="indexterm" name="d5e16016"></a>
<p>
The OpenJPA data cache is an optional cache of persistent object data that
operates at the <code class="classname">EntityManagerFactory</code> level. This cache is
designed to significantly increase performance while remaining in full
compliance with the JPA standard. This means that turning on the caching option
can transparently increase the performance of your application, with no changes
to your code.
</p>
<p>
OpenJPA's data cache is not related to the <code class="classname">EntityManager</code>
cache dictated by the JPA specification. The JPA specification mandates behavior
for the <code class="classname">EntityManager</code> cache aimed at guaranteeing
transaction isolation when operating on persistent objects.
</p>
<p>
OpenJPA's data cache is designed to provide significant performance increases
over cacheless operation, while guaranteeing that behavior will be identical in
both cache-enabled and cacheless operation.
</p>
<p>
There are five ways to access data via the OpenJPA APIs: standard relation
traversal, large result set relation traversal, queries, looking up an object by
id, and iteration over an <code class="classname">Extent</code>. OpenJPA's cache plugin
accelerates three of these mechanisms. It does not provide any caching of large
result set relations or <code class="classname">Extent</code> iterators. If you find
yourself in need of higher-performance <code class="classname">Extent</code> iteration,
see <a class="xref" href="#ref_guide_cache_limits_extent" title="Example&nbsp;10.25.&nbsp; Query Replaces Extent">Example&nbsp;10.25, &#8220;
Query Replaces Extent
&#8221;</a>.
</p>
<div class="table" id="d5e16030"><p class="title"><b>Table&nbsp;10.1.&nbsp;
Data access methods
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Data access methods&#xA; " border="1"><colgroup><col align="left" class="access-method"><col align="left" class="cacheable"></colgroup><thead><tr><th align="left">Access method</th><th align="left">Uses cache</th></tr></thead><tbody><tr><td align="left">
Standard relation traversal
</td><td align="left">
Yes
</td></tr><tr><td align="left">
Large result set relation traversal
</td><td align="left">No</td></tr><tr><td align="left">Query</td><td align="left">Yes</td></tr><tr><td align="left">
Lookups by object id
</td><td align="left">Yes</td></tr><tr><td align="left">
Iteration over an <code class="classname">Extent</code>
</td><td align="left">No</td></tr></tbody></table>
</div></div><br class="table-break">
<p>
When enabled, the cache is checked before making a trip to the datastore. Data
is stored in the cache when objects are committed and when persistent objects
are loaded from the datastore.
</p>
<p>
OpenJPA's data cache can operate in both single-JVM and multi-JVM environments.
Multi-JVM caching is achieved through the use of the distributed event
notification framework described in <a class="xref" href="#ref_guide_event" title="2.&nbsp; Remote Event Notification Framework">Section&nbsp;2, &#8220;
Remote Event Notification Framework
&#8221;</a>, or
through custom integrations with a third-party distributed cache.
</p>
<p>
The single JVM mode of operation maintains and shares a data cache across all
<code class="classname">EntityManager</code> instances obtained from a particular
<code class="classname">EntityManagerFactory</code>. This is not appropriate for use in
a distributed environment, as caches in different JVMs or created from different
<code class="classname">EntityManagerFactory</code> objects will not be synchronized.
</p>
<div class="section" id="ref_guide_cache_conf"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Data Cache Configuration
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_data_cache">1.1.1.
openjpa.DataCache Configuration
</a></span></dt><dt><span class="section"><a href="#ref_guide_shared_cache_mode_integration">1.1.2.
Integration with JPA standard shared cache mode
</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_distribution">1.1.3. Distributing instances across cache partitions</a></span></dt></dl></div>
<p>
There are two ways to enable the basic single-factory cache. One is using
<a class="link" href="#openjpa.DataCache" title="5.26.&nbsp; openjpa.DataCache"><code class="literal">openjpa.DataCache</code></a>
property, the other is using JPA standard shared-cache-mode element or the
javax.persistence.sharedCache.mode property.
</p>
<div class="section" id="ref_guide_data_cache"><div class="titlepage"><div><div><h4 class="title">1.1.1.&nbsp;
openjpa.DataCache Configuration
</h4></div></div></div>
<p>
To enable the basic single-factory cache set the
<a class="link" href="#openjpa.DataCache" title="5.26.&nbsp; openjpa.DataCache"><code class="literal">openjpa.DataCache</code></a>
property to <code class="literal">true</code>:
</p>
<div class="example" id="ref_guide_cache_conf_sjvm"><p class="title"><b>Example&nbsp;10.1.&nbsp;
Single-JVM Data Cache
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true"/&gt;
</pre>
</div></div><br class="example-break">
<p>
To configure the data cache to remain up-to-date in a distributed environment,
set the <a class="link" href="#openjpa.RemoteCommitProvider" title="5.61.&nbsp; openjpa.RemoteCommitProvider"><code class="literal">
openjpa.RemoteCommitProvider</code></a> property appropriately, or
integrate OpenJPA with a third-party caching solution. Remote commit providers
are described in <a class="xref" href="#ref_guide_event" title="2.&nbsp; Remote Event Notification Framework">Section&nbsp;2, &#8220;
Remote Event Notification Framework
&#8221;</a>.
</p>
<p>
<a class="indexterm" name="d5e16082"></a>
OpenJPA's default implementation maintains a map of object
ids to cache data. By default, 1000 elements are kept in cache. When the cache
overflows, random entries are evicted. The maximum cache size can be
adjusted by setting the <code class="literal">CacheSize</code> property in your plugin
string - see below for an example. Objects that are pinned into the cache are
not counted when determining if the cache size exceeds its maximum size.
</p>
<p>
Expired objects are moved to a soft reference map, so they may stick around for
a little while longer. You can control the number of soft references OpenJPA
keeps with the <code class="literal">SoftReferenceSize</code> property. Soft references
are unlimited by default. Set to 0 to disable soft references completely.
</p>
<p>
Both the QueryCache and DataCache can be configured to use a backing <code class="literal">Lru</code> map rather than the default
concurrent HashMap. Note that enabling the <code class="literal">Lru</code> cache can hurt performance as this map in not as
scalable as the default map.
</p>
<div class="example" id="ref_guide_cache_conf_lru"><p class="title"><b>Example&nbsp;10.2.&nbsp;
Lru Cache
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true(Lru=true)"/&gt;
&lt;property name="openjpa.QueryCache" value="true(Lru=true)"/&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_cache_conf_size"><p class="title"><b>Example&nbsp;10.3.&nbsp;
Data Cache Size
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true(CacheSize=5000, SoftReferenceSize=0)"/&gt;
</pre>
</div></div><br class="example-break">
<p>
<a class="indexterm" name="d5e16098"></a>
You can specify a cache timeout value for a class by setting the timeout
<a class="link" href="#ref_guide_meta_ext" title="4.&nbsp; Metadata Extensions">metadata extension</a> to the amount of
time in milliseconds a class's data is valid. Use a value of -1 for no
expiration. This is the default value.
</p>
<div class="example" id="ex_timeout_cache"><p class="title"><b>Example&nbsp;10.4.&nbsp;
Data Cache Timeout
</b></p><div class="example-contents">
<p>
Timeout <code class="classname">Employee</code> objects after 10 seconds.
</p>
<pre class="programlisting">
@Entity
@DataCache(timeout=10000)
public class Employee {
...
}
</pre>
</div></div><br class="example-break">
<p>
<a class="indexterm" name="d5e16108"></a>
Entities may be explicitly excluded from the cache by providing a
list of fully qualified class names in the <code class="literal">ExcludedTypes</code> argument.
The entities provided via <code class="literal">ExcludedTypes</code> will not be cached
regardless of the <code class="classname">DataCache</code> annotation.
</p>
<div class="example" id="ex_exclude_types_from_cache"><p class="title"><b>Example&nbsp;10.5.&nbsp;
Excluding entities
</b></p><div class="example-contents">
<p>
Exclude entities <code class="classname">foo.bar.Person</code> and
<code class="classname">foo.bar.Employee</code> from the cache.
</p><pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true(ExcludedTypes=foo.bar.Person;foo.bar.Employee)"/&gt;
</pre><p>
</p>
</div></div><br class="example-break">
<p>
<a class="indexterm" name="d5e16121"></a>
Entities may be explicitly included in the cache by providing a
list of fully qualified class names in the <code class="literal">Types</code> argument.
Any entities which are not included
in this list will not be cached.
</p>
<div class="example" id="ex_include_types_in_cache"><p class="title"><b>Example&nbsp;10.6.&nbsp;
Including entities
</b></p><div class="example-contents">
<p>
Include only entity <code class="classname">foo.bar.FullTimeEmployee</code> in the cache.
</p><pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true(Types=foo.bar.FullTimeEmployee)"/&gt;
</pre><p>
</p>
</div></div><br class="example-break">
<p>
See the <a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/DataCache.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.DataCache</code></a> Javadoc
for more information on the <code class="classname">DataCache</code> annotation.
</p>
<p>
<a class="indexterm" name="d5e16135"></a>
A cache can specify that it should be cleared at certain times rather than using
data timeouts. The <code class="literal">EvictionSchedule</code> property of OpenJPA's
cache implementation can be input in two different formats. The first is a <code class="literal">cron</code> style eviction schedule.
The format of this property is a whitespace-separated list of five tokens, where
the <code class="literal">*</code> symbol (asterisk), indicates match all. The tokens are,
in order:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Minute
</p>
</li><li class="listitem">
<p>
Hour of Day
</p>
</li><li class="listitem">
<p>
Day of Month
</p>
</li><li class="listitem">
<p>
Month
</p>
</li><li class="listitem">
<p>
Day of Week
</p>
</li></ul></div>
<p>
For example, the following <code class="literal">openjpa.DataCache</code> setting
schedules the default cache to evict values from the cache at 15 and 45 minutes
past 3 PM on Sunday.
</p>
<pre class="programlisting">
true(EvictionSchedule='15,45 15 * * 1')
</pre>
<p>
The second format for this property is an interval style eviction schedule. The
format of this property is a <code class="literal">+</code> followed by the number of minutes
between each time that the cache should be evicted.
</p>
<p>
For example, the following <code class="literal">openjpa.DataCache</code> setting schedules the default cache
to evict values from the cache every 120 minutes.
</p>
<p>
</p><pre class="programlisting">
true(EvictionSchedule='+120')
</pre><p>
</p>
<div class="example" id="bulk_update_evict_cache"><p class="title"><b>Example&nbsp;10.7.&nbsp;
Bulk updates and cache eviction
</b></p><div class="example-contents">
<p>
Setting <code class="literal">EvictOnBulkUpdate</code> to <code class="literal">false</code> will tell OpenJPA to not evict from the DataCache when executing
an UPDATE or DELETE statement. The default for the value is <code class="literal">true</code>.
</p>
<p>
</p><pre class="programlisting">&lt;property name="openjpa.DataCache" value="true(EvictOnBulkUpdate=false)"/&gt;</pre><p>
</p>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_shared_cache_mode_integration"><div class="titlepage"><div><div><h4 class="title">1.1.2.&nbsp;
Integration with JPA standard shared cache mode
</h4></div></div></div>
<p>
JPA 2.0 specification introduced the standard data cache configuration through the shared-cache-mode element or javax.persistence.
sharedCache.mode property.
</p>
<p>
When only the shared cache mode is configured to turn on the caching, the default data cache setting will be used. For example the
cache size will be set to default 1000.
</p>
<p>
When the shared cache mode and openjpa.DataCache are both configured, the JPA standard shared cache mode
configuration takes the precedence.
</p>
<p>
If the shared cache mode is to turn on the caching, the cache setting configured through openjpa.DataCache
, like cacheSize and SoftReferenceSize, will be used to initialize or manage the cache. The Types and ExcludeTypes
property in openjpa.DataCache will be ingnored since the shared cache mode in conjunction with the javax.persistence.Cacheable
annotation already defines what will be cached.
</p>
<div class="example" id="shared-cache-mode-none"><p class="title"><b>Example&nbsp;10.8.&nbsp;</b></p><div class="example-contents">
<p>
</p><pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true"/&gt;
&lt;property name="javax.persistence.sharedCache.mode" value="NONE"/&gt;
</pre><p>
</p>
<p>
When the shared cache mode is set to NONE, the data cache will be disabled no matter how openjpa.DataCache is configured.
</p>
</div></div><br class="example-break">
<div class="example" id="shared-cache-mode-all"><p class="title"><b>Example&nbsp;10.9.&nbsp;</b></p><div class="example-contents">
<p>
</p><pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true(ExcludedTypes=foo.bar.Person;foo.bar.Employee)"/&gt;
&lt;property name="javax.persistence.sharedCache.mode" value="ALL"/&gt;
</pre><p>
</p>
<p>
When the shared cache mode is set to ALL, all entities will be cached no matter how openjpa.DataCache is configured.
</p>
</div></div><br class="example-break">
<div class="example" id="shared-cache-mode-enable-selective"><p class="title"><b>Example&nbsp;10.10.&nbsp;</b></p><div class="example-contents">
<p>
</p><pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true(ExcludedTypes=foo.bar.Person;foo.bar.Employee)"/&gt;
&lt;property name="javax.persistence.sharedCache.mode" value="ENABLE_SELECTIVE"/&gt;
</pre><p>
</p>
<p>
When the shared cache mode set to ENABLE_SELECTIVE, the entities with Cacheable(true) anotation will be cached.
ExcludedTypes will be ignored.
</p>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_cache_distribution"><div class="titlepage"><div><div><h4 class="title">1.1.3.&nbsp;Distributing instances across cache partitions</h4></div></div></div>
<p>
OpenJPA also supports a partitioned cache configuration where the cached
instances can be distributed across partitions by an application-defined
policy. Each partition behaves as a data cache by itself, identified by its name and can
be configured individually. The distribution policy
determines the specific partition that stores the state of a managed instance.
The default distribution policy distributes the instances by their type
as specified by the <code class="literal">name</code> attribute in <code class="literal">@DataCache</code>
annotation. Cache distribution policy is a simple interface that can be implemented
by an application to distribute among the partitions on a per instance basis.
To enable a partitioned cache set the <code class="literal">openjpa.DataCache</code>
property to <code class="literal">partitioned</code>, and configure individual partitions
as follows:
</p>
<div class="example" id="ref_guide_cache_conf_partition"><p class="title"><b>Example&nbsp;10.11.&nbsp;
Partitioned Data Cache
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.CacheDistributionPolicy" value="org.acme.foo.DistributionPolicy"/&gt;
&lt;property name="openjpa.DataCache" value="partitioned(PartitionType=concurrent,partitions=
'(name=a,cacheSize=100),(name=b,cacheSize=200)')"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<p>
The distribution policy is configured by a full-qualified class name that implements
<code class="literal">org.apache.openjpa.datacahe.CacheDistributionPolicy</code>. The partitions
are specified as value of the <code class="literal">partitions</code> attribute as a series of
individually configurable plug-in strings. As the example shows, i) each partition plug-in configuration
must be enclosed in parentheses, ii) must be separated by comma and iii) the complete
set be enclosed in single quote. Each individual partition is a Data Cache by itself and
the class that implements the partition can be configured via <code class="literal">PartitionType</code>
attribute. The above example configuration will configure a partitioned cache with
two partitions named <code class="literal">a</code> and <code class="literal">b</code> of cache size 100 and 200,
respectively. The partitions are of <code class="literal">concurrent</code> type which is a mnemonic or alias
for <code class="literal">org.apache.openjpa.datacache.ConcurrentDataCache</code>. The <code class="literal">PartitionType</code>
is defaulted to <code class="literal">concurrent</code> though explicitly mentioned in this example.
</p>
</div>
<div class="section" id="ref_guide_cache_use"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Data Cache Usage
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_cache_use_JPA">1.2.1. Using the JPA standard Cache interface</a></span></dt><dt><span class="section"><a href="#ref_guide_cache_use_openJPA">1.2.2. Using the OpenJPA StoreCache extensions</a></span></dt></dl></div>
<p>
The <code class="literal">org.apache.openjpa.datacache</code> package defines OpenJPA's
data caching framework. While you may use this framework directly (see its
<a class="ulink" href="../../apidocs/org/apache/openjpa/datacache/package-summary.html" target="_top">
Javadoc</a> for details), its APIs are meant primarily for service
providers. In fact, <a class="xref" href="#ref_guide_cache_extension" title="1.5.&nbsp; Cache Extension">Section&nbsp;1.5, &#8220;
Cache Extension
&#8221;</a> below has
tips on how to use this package to extend OpenJPA's caching service yourself.
</p>
<p>
Rather than use the low-level <code class="literal">org.apache.openjpa.datacache</code>
package APIs, JPA users should typically access the data cache through the JPA
standard <code class="classname">javax.persistence.Cache</code> interface, or OpenJPA's
high-level
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/StoreCache.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.StoreCache</code></a> facade.
</p>
<p>
Both interfaces provide methods to evict data from the cache and detect whether
an entity is in the cache. The OpenJPA facade adds methods to pin and unpin
records, additional methods to evict data, and provides basic statistics of
number of read or write requests and hit ratio of the cache.
</p>
<div class="section" id="ref_guide_cache_use_JPA"><div class="titlepage"><div><div><h4 class="title">1.2.1.&nbsp;Using the JPA standard Cache interface</h4></div></div></div>
You may obtain the <code class="classname">javax.persistence.Cache</code> through
the EntityManagerFactory.getCache() method.
<div class="example" id="ref_guide_cache_access_jpa_standard"><p class="title"><b>Example&nbsp;10.12.&nbsp;
Accessing the Cache
</b></p><div class="example-contents">
<pre class="programlisting">
import javax.persistence.Cache;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
. . .
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("myPersistenceUnit");
Cache cache = emf.getCache();
. . .
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_cache_use_jpa_standard"><p class="title"><b>Example&nbsp;10.13.&nbsp;Using the javax.persistence.Cache interface</b></p><div class="example-contents">
<pre class="programlisting">
// Check whether the cache contains an entity with a provided ID
Cache cache = emf.getCache();
boolean contains = cache.contains(MyEntity.class, entityID);
// evict a specific entity from the cache
cache.evict(MyEntity.class, entityID);
// evict all instances of an entity class from the cache
cache.evict(AnotherEntity.class);
// evict everything from the cache
cache.evictAll();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_cache_use_openJPA"><div class="titlepage"><div><div><h4 class="title">1.2.2.&nbsp;Using the OpenJPA StoreCache extensions</h4></div></div></div>
<p>
You obtain the <code class="classname">StoreCache</code> through the <code class="methodname">
OpenJPAEntityManagerFactory.getStoreCache</code> method.
</p>
<div class="example" id="ref_guide_cache_access_jpa"><p class="title"><b>Example&nbsp;10.14.&nbsp;
Accessing the StoreCache
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast(emf);
StoreCache cache = oemf.getStoreCache();
...
</pre>
Alternatively you can just cast the same object returned from
the EntityManager.getCache() method.
<pre class="programlisting">
import org.apache.openjpa.persistence.StoreCache;
...
StoreCache cache = (StoreCache) emf.getCache();
</pre>
</div></div><br class="example-break">
<pre class="programlisting">
public void evict(Class cls, Object oid);
public void evictAll();
public void evictAll(Class cls, Object... oids);
public void evictAll(Class cls, Collection oids);
</pre>
<p>
The <code class="methodname">evict</code> methods tell the cache to release data. Each
method takes an entity class and one or more identity values, and releases the
cached data for the corresponding persistent instances. The <code class="methodname">
evictAll</code> method with no arguments clears the cache. Eviction is
useful when the datastore is changed by a separate process outside OpenJPA's
control. In this scenario, you typically have to manually evict the data from
the datastore cache; otherwise the OpenJPA runtime, oblivious to the changes,
will maintain its stale copy.
</p>
<pre class="programlisting">
public void pin(Class cls, Object oid);
public void pinAll(Class cls, Object... oids);
public void pinAll(Class cls, Collection oids);
public void unpin(Class cls, Object oid);
public void unpinAll(Class cls, Object... oids);
public void unpinAll(Class cls, Collection oids);
</pre>
<p>
Most caches are of limited size. Pinning an identity to the cache ensures that
the cache will not kick the data for the corresponding instance out of the
cache, unless you manually evict it. Note that even after manual eviction, the
data will get pinned again the next time it is fetched from the store. You can
only remove a pin and make the data once again available for normal cache
overflow eviction through the <code class="methodname">unpin</code> methods. Use
pinning when you want a guarantee that a certain object will always be available
from cache, rather than requiring a datastore trip.
</p>
<div class="example" id="ref_guide_cache_use_jpa"><p class="title"><b>Example&nbsp;10.15.&nbsp;
StoreCache Usage
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast(emf);
StoreCache cache = oemf.getStoreCache();
cache.pin(Magazine.class, popularMag.getId());
cache.evict(Magazine.class, changedMag.getId());
</pre>
</div></div><br class="example-break">
<p>
See the <code class="classname">StoreCache</code>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/StoreCache.html" target="_top">
Javadoc</a> for information on additional functionality it provides. Also,
<a class="xref" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">Chapter&nbsp;9, <i>
Runtime Extensions
</i></a> discusses OpenJPA's other extensions
to the standard set of JPA runtime interfaces.
</p>
</div>
<p>
The examples above include calls to <code class="methodname">evict</code> to manually
remove data from the data cache. Rather than evicting objects from the data
cache directly, you can also configure OpenJPA to automatically evict objects
from the data cache when you use the <code class="classname">
OpenJPAEntityManager</code>'s eviction APIs.
</p>
<div class="example" id="ref_guide_cache_pmevict"><p class="title"><b>Example&nbsp;10.16.&nbsp;
Automatic Data Cache Eviction
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.BrokerImpl" value="EvictFromDataCache=true"/&gt;
</pre>
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
oem.evict(changedMag); // will evict from data cache also
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_cache_statistics"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Cache Statistics
</h3></div></div></div>
<a class="indexterm" name="d5e16260"></a>
<p>
Number of requests to read and write requests and hit ratio of the
data cache is available via
<a class="ulink" href="../../apidocs/org/apache/openjpa/datacache/CacheStatistics.html" target="_top">
<code class="classname">org.apache.openjpa.datacache.CacheStatistics</code></a>
interface. The collection of cache statistics is disabled by default and needs to be enabled on a per cache basis. By default
all counts returned from the CacheStatistics interface will return 0.
</p><div class="example" id="ref_guide_cache_enablestats"><p class="title"><b>Example&nbsp;10.17.&nbsp;
Configuring CacheStatistics
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.DataCache" value="true(EnableStatistics=true)"/&gt;
</pre>
</div></div><p><br class="example-break">
Once cache statistics are enabled you can access them via StoreCache
</p><pre class="programlisting">
import org.apache.openjpa.datacache.CacheStatistics;
...
OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast(emf);
CacheStatistics statistics = oemf.getStoreCache().getCacheStatistics();
</pre><p>
The statistics includes number of read and write requests made to the cache
since start and last reset. The statistics can be obtained also per class basis.
</p><pre class="programlisting">
public interface org.apache.openjpa.datacache.CacheStatistics extends java.io.Serializable{
// Statistics since last reset
public long getReadCount();
public long getHitCount();
public long getWriteCount();
// Statistics since start
public long getTotalReadCount();
public long getTotalHitCount();
public long getTotalWriteCount();
// Per-Class statistics since last reset
public long getReadCount(java.lang.Class);
public long getHitCount(java.lang.Class);
public long getWriteCount(java.lang.Class);
// Per-Class statistics since start
public long getTotalReadCount(java.lang.Class);
public long getTotalHitCount(java.lang.Class);
public long getTotalWriteCount(java.lang.Class);
// Starting and last reset time
public java.util.Date since();
public java.util.Date start();
// Resets the statistics.
public void reset();
// Returns whether or not statistics will be collected.
public boolean isEnabled();
}
</pre><p>
Collecting per-class statistics depends on determining the runtime type of a
cached data element, when the given context does not permit determination of
exact runtime type, the statistics is registered against generic
<code class="classname">java.lang.Object</code>. Also each method that accepts Class
argument, treats null argument as <code class="classname">java.lang.Object</code>
</p>
</div>
<div class="section" id="ref_guide_cache_query"><div class="titlepage"><div><div><h3 class="title">1.4.&nbsp;
Query Cache
</h3></div></div></div>
<a class="indexterm" name="d5e16275"></a>
<a class="indexterm" name="d5e16278"></a>
<p>
In addition to the data cache, the <code class="literal">org.apache.openjpa.datacache
</code> package defines service provider interfaces for a query cache. The
query cache is disabled by default and needs to be enabled separately from the data cache.
The query cache stores the object ids returned by query executions. When you run a query,
OpenJPA assembles a key based on the query properties and the parameters used at
execution time, and checks for a cached query result. If one is found, the
object ids in the cached result are looked up, and the resultant
persistence-capable objects are returned. Otherwise, the query is executed
against the database, and the object ids loaded by the query are put into the
cache. The object id list is not cached until the list returned at query
execution time is fully traversed.
</p>
<p>
OpenJPA exposes a high-level interface to the query cache through the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/QueryResultCache.html" target="_top">
<code class="classname">org.apache.openjpa.persistence.QueryResultCache</code></a>
class. You can access this class through the <code class="classname">
OpenJPAEntityManagerFactory</code>.
</p>
<div class="example" id="ref_guide_cache_queryaccess"><p class="title"><b>Example&nbsp;10.18.&nbsp;
Accessing the QueryResultCache
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast(emf);
QueryResultCache qcache = oemf.getQueryResultCache();
</pre>
</div></div><br class="example-break">
<p>
The default query cache implementation caches 100 query executions in a
least-recently-used cache. This can be changed by setting the cache size in the
<code class="literal">CacheSize</code> plugin property. Like the data cache, the query
cache also has a backing soft reference map. The <code class="literal">SoftReferenceSize
</code> property controls the size of this map. It is disabled by default.
</p>
<div class="example" id="ref_guide_cache_cachesize"><p class="title"><b>Example&nbsp;10.19.&nbsp;
Query Cache Size
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.QueryCache" value="true(CacheSize=1000, SoftReferenceSize=100)"/&gt;
</pre>
</div></div><br class="example-break">
<p>
To disable the query cache (default), set the <code class="literal">openjpa.QueryCache
</code> property to <code class="literal">false</code>:
</p>
<div class="example" id="ref_guide_cache_disablequery"><p class="title"><b>Example&nbsp;10.20.&nbsp;
Disabling the Query Cache
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.QueryCache" value="false"/&gt;
</pre>
</div></div><br class="example-break">
<p>
Query Cache's default behaviour on eviction is to evict all the queries from
the cache if any of the entities that are in the access path of the query are
modified. Scanning through the whole query cache to evict the queries upon an
entity update slows down the entity update action.
The configurable eviction policy "timestamp" is to track the timestamp of the
query and the timestamp of last update for each entity class and compare the
timestamps when retrieving the query for reuse. If the timestamp of the query
result is older than the last update time of any entity in the access path of
the query, the query result would not be reused and the query result would be
evicted from the query cache.
To configure the <code class="literal">EvictPolicy</code> to timestamp,
here is an example:
</p>
<div class="example" id="ref_guide_cache_evictionPolicy"><p class="title"><b>Example&nbsp;10.21.&nbsp;
Query Cache Eviction Policy
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.QueryCache" value="true(EvictPolicy='timestamp')"/&gt;
</pre>
</div></div><br class="example-break">
<p>
There are certain situations in which the query cache is bypassed:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Caching is not used for in-memory queries (queries in which the candidates are a
collection instead of a class or <code class="classname">Extent</code>).
</p>
</li><li class="listitem">
<p>
Caching is not used in transactions that have <code class="literal">IgnoreChanges</code>
set to <code class="literal">false</code> and in which modifications to classes in the
query's access path have occurred. If none of the classes in the access path
have been touched, then cached results are still valid and are used.
</p>
</li><li class="listitem">
<p>
Caching is not used in pessimistic transactions, since OpenJPA must go to the
database to lock the appropriate rows.
</p>
</li><li class="listitem">
<p>
Caching is not used when the data cache does not have any cached data for an
id in a query result.
</p>
</li><li class="listitem">
<p>
Queries that use persistence-capable objects as parameters are only cached if
the parameter is directly compared to field, as in:
</p>
<pre class="programlisting">
select e from Employee e where e.company.address = :addr
</pre>
<p>
If you extract field values from the parameter in your query string, or if the
parameter is used in collection element comparisons, the query is not cached.
</p>
</li><li class="listitem">
<p>
Queries that result in projections of custom field types or <code class="classname">
BigDecimal</code> or <code class="classname">BigInteger</code> fields are not
cached.
</p>
</li></ul></div>
<p>
Cache results are removed from the cache when instances of classes in a cached
query's access path are touched. That is, if a query accesses data in class
<code class="classname">A</code>, and instances of class <code class="classname">A</code> are
modified, deleted, or inserted, then the cached query result is dropped from the
cache.
</p>
<p>
It is possible to tell the query cache that a class has been altered. This is
only necessary when the changes occur via direct modification of the database
outside of OpenJPA's control. You can also evict individual queries, or clear
the entire cache.
</p>
<pre class="programlisting">
public void evict(Query q);
public void evictAll(Class cls);
public void evictAll();
</pre>
<p>
For JPA queries with parameters, set the desired parameter values into the
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/Query.html" target="_top">
<code class="classname">Query</code></a> instance before calling the above methods.
</p>
<div class="example" id="ref_guide_cache_query_classchange"><p class="title"><b>Example&nbsp;10.22.&nbsp;
Evicting Queries
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast(emf);
QueryResultCache qcache = oemf.getQueryResultCache();
// evict all queries that can be affected by changes to Magazines
qcache.evictAll(Magazine.class);
// evict an individual query with parameters
EntityManager em = emf.createEntityManager();
Query q = em.createQuery(...).
setParameter(0, paramVal0).
setParameter(1, paramVal1);
qcache.evict(q);
</pre>
</div></div><br class="example-break">
<p>
When using one of OpenJPA's distributed cache implementations, it is necessary
to perform this in every JVM - the change notification is not propagated
automatically. When using a third-party coherent caching solution,
it is not necessary to do this in every JVM (although it won't hurt to do so),
as the cache results are stored directly in the coherent cache.
</p>
<p>
Queries can also be pinned and unpinned through the <code class="classname">
QueryResultCache</code>. The semantics of these operations are the same
as pinning and unpinning data from the data cache.
</p>
<pre class="programlisting">
public void pin(Query q);
public void unpin(Query q);
</pre>
<p>
For JPA queries with parameters, set the desired parameter values into the
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/persistence/Query.html" target="_top">
<code class="classname">Query</code></a> instance before calling the above methods.
</p>
<p>
The following example shows these APIs in action.
</p>
<div class="example" id="ref_guide_cache_query_pin"><p class="title"><b>Example&nbsp;10.23.&nbsp;
Pinning, and Unpinning Query Results
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManagerFactory oemf = OpenJPAPersistence.cast(emf);
QueryResultCache qcache = oemf.getQueryResultCache();
EntityManager em = emf.createEntityManager();
Query pinQuery = em.createQuery(...).
setParameter(0, paramVal0).
setParameter(1, paramVal1);
qcache.pin(pinQuery);
Query unpinQuery = em.createQuery(...).
setParameter(0, paramVal0).
setParameter(1, paramVal1);
qcache.unpin(unpinQuery);
</pre>
</div></div><br class="example-break">
<p>
Pinning data into the cache instructs the cache to not expire the pinned results
when cache flushing occurs. However, pinned results will be removed from the
cache if an event occurs that invalidates the results.
</p>
<p>
You can disable caching on a per-<code class="classname">EntityManager</code> or
per-<code class="classname">Query</code> basis:
</p>
<div class="example" id="ref_guide_cache_query_disable"><p class="title"><b>Example&nbsp;10.24.&nbsp;
Disabling and Enabling Query Caching
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
// temporarily disable query caching for all queries created from em
OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
oem.getFetchPlan().setQueryResultCacheEnabled(false);
// re-enable caching for a particular query
OpenJPAQuery oq = oem.createQuery(...);
oq.getFetchPlan().setQueryResultCacheEnabled(true);
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_cache_extension"><div class="titlepage"><div><div><h3 class="title">1.5.&nbsp;
Cache Extension
</h3></div></div></div>
<a class="indexterm" name="d5e16359"></a>
<a class="indexterm" name="d5e16363"></a>
<p>
The provided data cache classes can be easily extended to add additional
functionality. If you are adding new behavior, you should extend <code class="classname">
org.apache.openjpa.datacache.ConcurrentDataCache</code>. To use your own storage
mechanism, extend <code class="classname">org.apache.openjpa.datacache.AbstractDataCache
</code> (preferred), or implement <code class="classname">org.apache.openjpa.datacache.DataCache
</code> directly. If you want to implement a distributed cache that uses an
unsupported method for communications, create an implementation of <code class="classname">
org.apache.openjpa.event.RemoteCommitProvider</code>. This process is
described in greater detail in
<a class="xref" href="#ref_guide_event_customization" title="2.2.&nbsp; Customization">Section&nbsp;2.2, &#8220;
Customization
&#8221;</a>.
</p>
<p>
The query cache is just as easy to extend. Add functionality by extending the
default <code class="classname">org.apache.openjpa.datacache.ConcurrentQueryCache</code>.
Implement your own storage mechanism for query results by extending <code class="classname">
org.apache.openjpa.datacache.AbstractQueryCache</code> (preferred) or implementing the
<code class="classname">org.apache.openjpa.datacache.QueryCache</code> interface
directly.
</p>
</div>
<div class="section" id="ref_guide_cache_notes"><div class="titlepage"><div><div><h3 class="title">1.6.&nbsp;
Important Notes
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The default cache implementations <span class="emphasis"><em>do not</em></span> automatically
refresh objects in other <code class="classname">EntityManager</code>s when the cache
is updated or invalidated. This behavior would not be compliant with the JPA
specification.
</p>
</li><li class="listitem">
<p>
Invoking <code class="methodname">OpenJPAEntityManager.evict</code><span class="emphasis"><em> does not
</em></span> result in the corresponding data being dropped from the data cache,
unless you have set the proper configuration options as explained above (see
<a class="xref" href="#ref_guide_cache_pmevict" title="Example&nbsp;10.16.&nbsp; Automatic Data Cache Eviction">Example&nbsp;10.16, &#8220;
Automatic Data Cache Eviction
&#8221;</a>). Other methods related to the
<code class="classname">EntityManager</code> cache also do not affect the data cache.
</p>
<p>
The data cache assumes that it is up-to-date with respect to the datastore, so
it is effectively an in-memory extension of the database. To manipulate the data
cache, you should generally use the data cache facades presented in this
chapter.
</p>
</li></ul></div>
</div>
<div class="section" id="datastore_cache_issues"><div class="titlepage"><div><div><h3 class="title">1.7.&nbsp;
Known Issues and Limitations
</h3></div></div></div>
<a class="indexterm" name="d5e16393"></a>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
When using datastore (pessimistic) transactions in concert with the distributed
caching implementations, it is possible to read stale data when reading data
outside a transaction.
</p>
<p>
For example, if you have two JVMs (JVM A and JVM B) both communicating with each
other, and JVM A obtains a data store lock on a particular object's underlying
data, it is possible for JVM B to load the data from the cache without going to
the datastore, and therefore load data that should be locked. This will only
happen if JVM B attempts to read data that is already in its cache during the
period between when JVM A locked the data and JVM B received and processed the
invalidation notification.
</p>
<p>
This problem is impossible to solve without putting together a two-phase commit
system for cache notifications, which would add significant overhead to the
caching implementation. As a result, we recommend that people use optimistic
locking when using data caching. If you do not, then understand that some of
your non-transactional data may not be consistent with the datastore.
</p>
<p>
Note that when loading objects in a transaction, the appropriate datastore
transactions will be obtained. So, transactional code will maintain its
integrity.
</p>
</li><li class="listitem">
<p>
<code class="classname">Extent</code>s are not cached. So, if you plan on iterating
over a list of all the objects in an <code class="classname">Extent</code> on a regular
basis, you will only benefit from caching if you do so with a <code class="classname">Query
</code> instead:
</p>
<div class="example" id="ref_guide_cache_limits_extent"><p class="title"><b>Example&nbsp;10.25.&nbsp;
Query Replaces Extent
</b></p><div class="example-contents">
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
...
OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
Extent extent = oem.createExtent(Magazine.class, false);
// This iterator does not benefit from caching...
Iterator uncachedIterator = extent.iterator();
// ... but this one does.
OpenJPAQuery extentQuery = oem.createQuery(...);
extentQuery.setSubclasses(false);
Iterator cachedIterator = extentQuery.getResultList().iterator();
</pre>
</div></div><br class="example-break">
</li></ul></div>
</div>
</div>
<div class="section" id="ref_guide_cache_querycomp"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Query Compilation Cache
</h2></div></div></div>
<a class="indexterm" name="d5e16412"></a>
<p>
The query compilation cache is a <code class="classname">Map</code> used to cache
parsed query strings. As a result, most queries are only parsed once in
OpenJPA, and cached thereafter. You can control the compilation cache through
the <a class="link" href="#openjpa.QueryCompilationCache" title="5.59.&nbsp; openjpa.QueryCompilationCache"><code class="literal">
openjpa.QueryCompilationCache</code></a> configuration property. This
property accepts a plugin string (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>)
describing the <code class="classname">Map</code> used to associate query strings and
their parsed form. This property accepts the following aliases:
</p>
<div class="table" id="d5e16421"><p class="title"><b>Table&nbsp;10.2.&nbsp;
Pre-defined aliases
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Pre-defined aliases&#xA; " border="1"><colgroup><col align="left" class="alias"><col align="left" class="value"><col align="left" class="notes"></colgroup><thead><tr><th align="left">Alias</th><th align="left">Value</th><th align="left">Notes</th></tr></thead><tbody><tr><td align="left">
<code class="literal">true</code>
</td><td align="left">
<code class="literal">org.apache.openjpa.util.CacheMap</code>
</td><td align="left">
The default option. Uses a
<a class="ulink" href="../../apidocs/org/apache/openjpa/util/CacheMap.html" target="_top">
<code class="literal">CacheMap</code></a> to store compilation data.
<code class="literal">CacheMap</code> maintains a fixed number of cache entries, and an
optional soft reference map for entries that are moved out of the LRU space.
So, for applications that have a monotonically increasing number of distinct
queries, this option can be used to ensure that a fixed amount of memory is
used by the cache.
</td></tr><tr><td align="left"><code class="literal">all</code></td><td align="left">
<code class="literal">org.apache.openjpa.lib.util.ConcurrentHashMap</code>
</td><td align="left">
This is the fastest option, but compilation data is never dropped from the
cache, so if you use a large number of dynamic queries, this option may result
in ever-increasing memory usage. Note that if your queries only differ in the
values of the parameters, this should not be an issue.
</td></tr><tr><td align="left"><code class="literal">false</code></td><td align="left"><span class="emphasis"><em>none</em></span></td><td align="left">
Disables the compilation cache.
</td></tr></tbody></table>
</div></div><br class="table-break">
</div>
<div class="section" id="ref_guide_cache_querysql"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;Prepared SQL Cache</h2></div></div></div>
<a class="indexterm" name="d5e16456"></a>
<p>
Prepared SQL Cache caches SQL statements corresponding to JPQL queries.
If a query is executed more than once in the same or different persistence
contexts, the SQL statement generated during the first execution is cached and
executed directly for subsequent execution. Direct execution of SQL offers
significant performance gain as it saves the cost of parsing query string and,
more importantly, populating the query expression tree during every execution.
Relative performance gain becomes higher as the complexity of forming a SQL
query from a JPQL string increases. For example, a JPQL query <code class="code">Q1</code>
that involves multiple joins across tables takes more computation to translate
into a SQL statement than a JPQL query <code class="code">Q2</code> to select by simple
primary key identifier. Correspondingly, repeated execution of <code class="code">Q1</code>
will gain more performance advantage than <code class="code">Q2</code> with Prepared SQL
Cache.
</p>
<p>
Prepared SQL Cache is configured by the <a class="link" href="#openjpa.jdbc.QuerySQLCache" title="6.10.&nbsp; openjpa.jdbc.QuerySQLCache">
<code class="literal">openjpa.jdbc.QuerySQLCache</code></a> configuration property. This
property accepts a plugin string (see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>)
with value of <code class="literal">true</code> or <code class="literal">false</code>. The default
is <code class="literal">true</code>. The execution statistics of the cached queries can be
optionally collected as
</p><pre class="programlisting">
&lt;property name="openjpa.jdbc.QuerySQLCache" value="true(EnableStatistics=true)"&gt;
</pre><p>
The <a class="ulink" href="../../apidocs/org/apache/openjpa/kernel/QueryStatistics.html" target="_top">
<code class="code">QueryStatistics</code></a> can be accessed via <code class="code">PreparedQueryCache.getStatistics()</code>.
</p>
<div class="table" id="d5e16475"><p class="title"><b>Table&nbsp;10.3.&nbsp;
Pre-defined aliases
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Pre-defined aliases&#xA; " border="1"><colgroup><col align="left" class="alias"><col align="left" class="value"><col align="left" class="notes"></colgroup><thead><tr><th align="left">Alias</th><th align="left">Value</th><th align="left">Notes</th></tr></thead><tbody><tr><td align="left">
<code class="literal">true</code>
</td><td align="left">
<code class="literal">org.apache.openjpa.util.CacheMap</code>
</td><td align="left">
The default option. Uses a
<a class="ulink" href="../../apidocs/org/apache/openjpa/util/CacheMap.html" target="_top">
<code class="literal">CacheMap</code></a> to store SQL string.
<code class="literal">CacheMap</code> maintains a fixed number of cache entries, and an
optional soft reference map for entries that are moved out of the LRU space.
So, for applications that have a monotonically increasing number of distinct
queries, this option can be used to ensure that a fixed amount of memory is
used by the cache.
</td></tr><tr><td align="left"><code class="literal">false</code></td><td align="left"><span class="emphasis"><em>none</em></span></td><td align="left">
Disables the SQL cache.
</td></tr></tbody></table>
</div></div><br class="table-break">
<p>
Following salient points to be noted regarding usage of Prepared Query Cache.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Prepared Query Cache uses the original JPQL string as the key to index the
corresponding SQL statement. Hence the JPQL strings that are semantically
identical but differ by character case or identification variables are
considered as different by this cache. One of the implications is that the
applications can gain better advantage from the Prepared Query Cache by
using parameters in their JPQL query rather than concatenating the parameter
values in the query string itself .
</p>
<p>
For example, contrast the following two examples of executing JPQL queries.
</p><div class="example" id="jpa_caching_hardcode_jpql"><p class="title"><b>Example&nbsp;10.26.&nbsp;Hardcoded Selection Value in JPQL Query</b></p><div class="example-contents">
<pre class="programlisting">
String jpql = "SELECT p FROM Person p WHERE p.name='John'";
List johns = em.createQuery(jpql).getResultList();
jpql = "SELECT p FROM Person p WHERE p.name='Tom'";
List toms = em.createQuery(jpql).getResultList();
</pre>
</div></div><p><br class="example-break">
In <a class="xref" href="#jpa_caching_hardcode_jpql" title="Example&nbsp;10.26.&nbsp;Hardcoded Selection Value in JPQL Query">Example&nbsp;10.26, &#8220;Hardcoded Selection Value in JPQL Query&#8221;</a>, the queries have
<span class="emphasis"><em>hardcoded</em></span> the selection value for the <code class="code">p.name</code>
field. Prepared Query Cache will not recognize the second execution as
same as the first, though both will result in same SQL statement.
</p>
<p>
While in <a class="xref" href="#jpa_caching_parametrize_jpql" title="Example&nbsp;10.27.&nbsp;Parameterized Selection Value in JPQL Query">Example&nbsp;10.27, &#8220;Parameterized Selection Value in JPQL Query&#8221;</a>, the
selection value for the <code class="code">p.name</code> field is parameterized.
Prepared Query Cache will recognize the second execution as
same as the first, and will execute the cached SQL statement directly.
</p><div class="example" id="jpa_caching_parametrize_jpql"><p class="title"><b>Example&nbsp;10.27.&nbsp;Parameterized Selection Value in JPQL Query</b></p><div class="example-contents">
<pre class="programlisting">
String jpql = "SELECT p FROM Person p WHERE p.name=:name";
List johns = em.createQuery(jpql).setParameter("name","John").getResultList();
List toms = em.createQuery(jpql).setParameter("name","Tom").getResultList();
</pre>
</div></div><p><br class="example-break">
</p>
</li><li class="listitem">
A JPQL query may not always translate into a <span class="emphasis"><em>single</em></span>
SQL query. The JPQL queries that require multiple select statements are
never cached.
</li><li class="listitem">
Same JPQL query may result into different SQL statements under different
execution context. Execution context parameters such as fetch configuration
or locking mode determine the resultant SQL. However, Prepared SQL Cache
<span class="emphasis"><em>does not</em></span> capture the execution context parameters
while caching a generated SQL.
</li><li class="listitem">
The named or positional parameters of a JPQL query can be set to different
values across executions. In general, the corresponding cached SQL statement
will be re-parameterized accordingly. However, the parameter value itself can
determine the SQL query. For example, when a JPQL query compares a relation
field for equality against a parameter <code class="code">p</code>, whether the actual
value of <code class="code">p</code> is <code class="code">null</code> or not will determine the
generated SQL statement. Another example is collection valued parameter for
<code class="code">IN</code> expression. Each element of a collection valued parameter
results into a SQL parameter. If a collection valued parameter across
executions are set to different number of elements, then the parameters of
the cached SQL do not correspond. If such situations are encountered while
re-parameterizing the cached SQL, the cached version is not reused and the
original JPQL query is used to generate a new SQL statement for execution.
</li><li class="listitem">
JPQL query that returns a <span class="emphasis"><em>numeric</em></span> value such as
<code class="code">SELECT count(p) FROM PObject p</code> is never cached.
</li></ul></div><p>
</p>
<p>
Several mechanisms are available to the application to bypass SQL caching
for a JPQL query.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">A user application can disable Prepared SQL Cache
for entire lifetime of a persistence context by invoking the following
method on OpenJPA's EntityManager SPI interface:
<pre class="programlisting">
<code class="methodname">OpenJPAEntityManagerSPI.setQuerySQLCache(boolean)</code>
</pre>
</li><li class="listitem">
A user application can instruct particular execution of a JPQL query to
ignore any cached SQL query, by setting
<code class="literal">QueryHints.HINT_IGNORE_PREPARED_QUERY</code> or
<code class="literal">"openjpa.hint.IgnorePreparedQuery"</code> to <code class="literal">true</code>
via standard <code class="literal">javax.persistence.Query.setHint(String, Object)</code> method. If a
SQL query has been cached corresponding to the JPQL query prior to this
execution, then the cached SQL remains in the cache and will be reused
for any subsequent execution of the same JPQL query.
</li><li class="listitem">
A user application can instruct all subsequent execution of a JPQL query to
ignore any cached SQL query, by setting
<code class="literal">QueryHints.HINT_INVALIDATE_PREPARED_QUERY</code> or
<code class="literal">"openjpa.hint.InvalidatePreparedQuery"</code> to <code class="literal">true</code>
The SQL query is removed from the cache. Also the JPQL query will never be
cached again during the lifetime of the entire persistence unit.
</li><li class="listitem">
Plug-in property <code class="literal">openjpa.jdbc.QuerySQLCache</code> can be
configured to exclude certain JPQL queries as shown below.
<pre class="programlisting">
&lt;property name="openjpa.jdbc.QuerySQLCache" value="true(excludes='select c from Company c;select d from Department d')"/&gt;
</pre>
will never cache JPQL queries <code class="code">select c from Company c</code> and
<code class="code">select d from Department d</code>.
</li></ul></div><p>
</p>
</div>
</div>
<div class="chapter" id="ref_guide_encryption"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;11.&nbsp;
Encryption Provider
</h2></div></div></div>
<p>
OpenJPA provides an interface for a provider to implement
connection password encryption. Whenever a connection password
is needed, the <code class="methodname">decrypt(String)</code> method will be invoked. See
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/encryption/EncryptionProvider.html" target="_top">
<code class="classname">org.apache.openjpa.lib.encryption.EncryptionProvider</code>
</a> for the detailed Javadoc.
</p>
<p>
Notes:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
It is an OpenJPA user responsibility to implement the
<code class="classname">EncryptionProvider</code>
interface. There is no default implementation.
</p>
</li><li class="listitem">
<p>
The interface has an <code class="methodname">encrypt(String)</code> method,
but it is not called by the OpenJPA runtime.
</p>
</li></ul></div><p>
</p>
</div>
<div class="chapter" id="ref_guide_remote"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;12.&nbsp;
Remote and Offline Operation
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_detach">1.
Detach and Attach
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach_behavior">1.1.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_attach_behavior">1.2.
Attach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_graph">1.3.
Defining the Detached Object Graph
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach_state">1.3.1.
Detached State
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_field">1.3.2.
Detached State Field
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#ref_guide_event">2.
Remote Event Notification Framework
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_event_conf">2.1.
Remote Commit Provider Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_event_conf_jms">2.1.1.
JMS
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_tcp">2.1.2.
TCP
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_common">2.1.3.
Common Properties
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_event_customization">2.2.
Customization
</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e16566"></a>
<a class="indexterm" name="d5e16568"></a>
<p>
The standard JPA runtime environment was originally just
<span class="emphasis"><em>local</em></span> and
<span class="emphasis"><em>online</em></span>. It is <span class="emphasis"><em>local</em></span> in that components
such as <code class="classname">EntityManager</code>s and queries connect directly to
the datastore and execute their actions in the same JVM as the code using them.
It is <span class="emphasis"><em>online</em></span> in that all changes to managed objects must be
made in the context of an active <code class="classname"> EntityManager</code>. These
two properties, combined with the fact that <code class="classname">
EntityManager</code>s cannot be serialized for storage or network transfer,
made the standard JPA runtime difficult to incorporate into some enterprise and
client/server program designs.
</p>
<p>
JPA has now provided <span class="emphasis"><em>offline</em></span> capability through the
detach() and merge() methods on the EntityManager interface. OpenJPA has
extended this to include additional detach...() and merge...() methods. All of
these are documented in
<a class="link" href="#ref_guide_detach" title="1.&nbsp; Detach and Attach">Detach and Attach APIs</a>. In addition,
OpenJPA has added <span class="emphasis"><em>remote</em></span> capability in the form of
<a class="link" href="#ref_guide_event" title="2.&nbsp; Remote Event Notification Framework">Remote Commit Events</a>. The following
sections explain these capabilities in detail.
</p>
<div class="section" id="ref_guide_detach"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Detach and Attach
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_detach_behavior">1.1.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_attach_behavior">1.2.
Attach Behavior
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_graph">1.3.
Defining the Detached Object Graph
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_detach_state">1.3.1.
Detached State
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_field">1.3.2.
Detached State Field
</a></span></dt></dl></dd></dl></div>
<a class="indexterm" name="d5e16586"></a>
<a class="indexterm" name="d5e16588"></a>
<p>
The JPA Overview describes the specification's standard detach and attach APIs
in <a class="xref" href="#jpa_overview_em_lifecycle" title="2.&nbsp; Entity Lifecycle Management">Section&nbsp;2, &#8220;
Entity Lifecycle Management
&#8221;</a>. This section enumerates
OpenJPA's enhancements to the standard behavior.
</p>
<div class="section" id="ref_guide_detach_behavior"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Detach Behavior
</h3></div></div></div>
<a class="indexterm" name="d5e16595"></a>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
In version 2.0, the detach behavior has changed from the previous
version. See the migration section
<a class="link" href="#migration_detach_behavior" title="1.1.2.&nbsp; Detach Behavior">Detach Behavior</a> for details.
</p>
</div>
<p>
In JPA, objects detach automatically when they are serialized or when a
<a class="link" href="#jpa_overview_emfactory_perscontext" title="3.&nbsp; Persistence Context">persistence context</a>
ends. The specification also allows objects to be explicitly detached using
the following javax.persistence.EntityManager method:
</p>
<pre class="programlisting">
public void detach(Object)
</pre>
<p>
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">OpenJPAEntityManager</code></a>, however, provides
additional detach methods.
</p>
<pre class="programlisting">
public &lt;T&gt; T detachCopy(T pc):
public Object[] detachAll(Object... pcs):
public Collection detachAll(Collection pcs):
</pre>
<p>
The behavior of the detach operation is as follows:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
The detached objects are removed from the persistent context.
</li><li class="listitem">
The objects are <span class="emphasis"><em>not</em></span> flushed to the database.
</li><li class="listitem">
If Cascade=detach is specified for a referenced entity, the detach
operation is cascaded. Otherwise, it is not.
</li><li class="listitem">
For the detachCopy method only, the entity is copied for the return
value.
</li></ul></div><p>
</p>
</div>
<div class="section" id="ref_guide_attach_behavior"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Attach Behavior
</h3></div></div></div>
<a class="indexterm" name="d5e16617"></a>
<p>
When attaching, OpenJPA uses several strategies to determine the optimal way to
merge changes made to the detached instance. As you will see, these strategies
can even be used to attach changes made to a transient instance which was never
detached in the first place.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
If the instance was detached and <a class="link" href="#ref_guide_detach_graph" title="1.3.&nbsp; Defining the Detached Object Graph">
detached state</a> is enabled, OpenJPA will use the detached state to
determine the object's version and primary key values. In addition, this state
will tell OpenJPA which fields were loaded at the time of detach, and in turn
where to expect changes. Loaded detached fields with null values will set the
attached instance's corresponding fields to null.
</p>
</li><li class="listitem">
<p>
If the instance has a <code class="literal">Version</code> field,
OpenJPA will consider the object detached if the version field has a non-default
value, and new otherwise. Similarly, if the instance has
<code class="literal">GeneratedValue</code> primary key fields, OpenJPA will consider the
object detached if any of these fields have non-default values, and new
otherwise.
</p>
<p>
When attaching null fields in these cases, OpenJPA cannot distinguish between a
field that was unloaded and one that was intentionally set to null. In this
case, OpenJPA will use the current <a class="link" href="#ref_guide_detach_graph" title="1.3.&nbsp; Defining the Detached Object Graph">
detach state</a> setting to determine how to handle null fields: fields that
would have been included in the detached state are treated as loaded, and will
in turn set the corresponding attached field to null.
</p>
</li><li class="listitem">
<p>
If neither of the above cases apply, OpenJPA will check to see if an instance
with the same primary key values exists in the database. If so, the object is
considered detached. Otherwise, it is considered new.
</p>
</li></ul></div>
<p>
These strategies will be assigned on a per-instance basis, such that during the
attachment of an object graph more than one of the above strategies may be used.
</p>
<p>
If you attempt to attach a versioned instance whose representation has changed
in the datastore since detachment, OpenJPA will throw an optimistic concurrency
exception upon commit or flush, just as if a normal optimistic conflict was
detected. When attaching an instance whose database record has been deleted
since detaching, or when attaching a detached instance into a manager that has a
stale version of the object, OpenJPA will throw an optimistic concurrency
exception from the attach method. In these cases, OpenJPA sets the <code class="literal">
RollbackOnly</code> flag on the transaction.
</p>
</div>
<div class="section" id="ref_guide_detach_graph"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Defining the Detached Object Graph
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_detach_state">1.3.1.
Detached State
</a></span></dt><dt><span class="section"><a href="#ref_guide_detach_field">1.3.2.
Detached State Field
</a></span></dt></dl></div>
<a class="indexterm" name="d5e16638"></a>
<p>
When detached objects lose their association with the OpenJPA runtime, they also
lose the ability to load additional state from the datastore. It is important,
therefore, to populate objects with all the persistent state you will need
before detaching them. While you are free to do this manually, OpenJPA includes
facilities for automatically populating objects when they detach.
</p>
<div class="section" id="ref_guide_detach_state"><div class="titlepage"><div><div><h4 class="title">1.3.1.&nbsp;
Detached State
</h4></div></div></div>
<a class="indexterm" name="d5e16644"></a>
<p>
The <a class="link" href="#openjpa.DetachState" title="5.30.&nbsp; openjpa.DetachState"><code class="literal">openjpa.DetachState</code>
</a> configuration property determines which fields and relations are
detached by default. All settings are recursive. They are:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<p>
<code class="literal">loaded</code>: Detach all fields and relations that are already
loaded, but don't include unloaded fields in the detached graph. This is the
default.
</p>
</li><li class="listitem">
<p>
<code class="literal">fetch-groups</code>: Detach all fields and relations in the current
<a class="link" href="#ref_guide_runtime" title="Chapter&nbsp;9.&nbsp; Runtime Extensions">fetch configuration</a>. For more
information on custom fetch groups, see <a class="xref" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">Section&nbsp;7, &#8220;
Fetch Groups
&#8221;</a>.
</p>
</li><li class="listitem">
<p>
<code class="literal">all</code>: Detach all fields and relations. Be very careful when
using this mode; if you have a highly-connected domain model, you could end up
bringing every object in the database into memory!
</p>
</li></ol></div>
<p>
Any field that is not included in the set determined by the detach mode is set
to its Java default value in the detached instance.
</p>
<p>
The <code class="literal">openjpa.DetachState</code> option is actually a plugin string
(see <a class="xref" href="#ref_guide_conf_plugins" title="4.&nbsp; Plugin Configuration">Section&nbsp;4, &#8220;
Plugin Configuration
&#8221;</a>) that allows you to also
configure the following options related to detached state:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">DetachedStateField</code>: As described in
<a class="xref" href="#ref_guide_attach_behavior" title="1.2.&nbsp; Attach Behavior">Section&nbsp;1.2, &#8220;
Attach Behavior
&#8221;</a> above, OpenJPA can take
advantage of a <span class="emphasis"><em>detached state field</em></span> to make the attach
process more efficient. This field is added by the enhancer and is not visible
to your application. Set this property to one of the following values:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
<code class="literal">transient</code>: Use a transient detached state field. This gives
the benefits of a detached state field to local objects that are never
serialized, but retains serialization compatibility for client tiers without
access to the enhanced versions of your classes or the OpenJPA runtime.
This is the default.
</p>
</li><li class="listitem">
<p>
<code class="literal">true</code>: Use a non-transient detached state field so that
objects crossing serialization barriers can still be attached efficiently. This
requires, however, that your client tier have the enhanced versions of your
classes and the OpenJPA runtime.
</p>
</li><li class="listitem">
<p>
<code class="literal">false</code>: Do not use a detached state field. No OpenJPA runtime
will be required for client tiers.
</p>
</li></ul></div>
<p>
The detached state field is also used to determine when proxies should be
removed from entities during serialization. See the
<a class="xref" href="#ref_guide_pc_scos_proxy_serial" title="6.4.4.&nbsp; Serialization">Section&nbsp;6.4.4, &#8220;
Serialization
&#8221;</a> section for more details.
</p>
<p>
You can override the setting of this property or declare your own detached state
field on individual classes using OpenJPA's metadata extensions. See
<a class="xref" href="#ref_guide_detach_field" title="1.3.2.&nbsp; Detached State Field">Section&nbsp;1.3.2, &#8220;
Detached State Field
&#8221;</a> below.
</p>
</li><li class="listitem">
<p>
<code class="literal">DetachedStateManager</code>: Whether to use a detached state
manager. A detached state manager makes attachment much more efficient. Like a
detached state field, however, it breaks serialization compatibility with the
unenhanced class if it isn't transient.
</p>
<p>
This setting piggybacks on the <code class="literal">DetachedStateField</code> setting
above. If your detached state field is transient, the detached state manager
will also be transient. If the detached state field is disabled, the detached
state manager will also be disabled. This is typically what you'll want. By
setting <code class="literal"> DetachedStateField</code> to true (or transient) and
setting this property to false, however, you can use a detached state field
<span class="bold"><strong>without</strong></span> using a detached state manager. This
may be useful for debugging or for legacy OpenJPA users who find differences
between OpenJPA's behavior with a detached state manager and OpenJPA's older
behavior without one.
</p>
</li><li class="listitem">
<p>
<code class="literal">AccessUnloaded</code>: Whether to allow access to unloaded fields
of detached objects. Defaults to true. Set to false to throw an exception
whenever an unloaded field is accessed. This option is only available when you
use detached state managers, as determined by the settings above.
</p>
</li><li class="listitem">
<p>
<code class="literal">LiteAutoDetach</code>: <span class="bold"><strong>This option is ONLY valid for the <code class="literal">loaded</code>
DetachState setting.</strong></span> Detach all fields and relations as described by the loaded
property when an explicit detach is requested or when a
single Entity is being detached as part of serialization. When the entire
persistence context is being auto-detached ( <code class="literal">openjpa.AutoDetach</code> ),
the minimal amount of work will be completed to disassociate all Entities from
the persistence context. <span class="bold"><strong>It is highly recommended that all Entities have a
@Version field when using this property</strong></span>. In addition, care needs to be taken
when this value is set to true as the following caveats apply:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<p>
A relationship from a managed Entity to an unmanaged Entity which was detached by the lite detach setting will not be persisted.
</p>
</li><li class="listitem">
<p>
When merging a detached Entity back into the persistence context any lazily loaded fields that were marked to null when detached will not be persisted.
</p>
</li></ul></div><p>
</p>
</li><li class="listitem">
<p>
<code class="literal">DetachProxyFields</code>: <span class="bold"><strong>This option is ONLY valid when used in conjunction with the <code class="literal">LiteAutoDetach</code>
DetachState setting.</strong></span> When detaching the persistence context, all proxies will be left in place. Note, that
all <code class="literal">Large Result Sets</code> will be removed.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem">
<code class="literal">true(default)</code>: All proxies will be removed and LRS fields will be removed.
</li><li class="listitem">
<code class="literal">false</code>: All proxies will be left in place and LRS fields will be removed.
</li></ul></div>
</li></ul></div>
<div class="example" id="ref_guide_detach_graph_confex"><p class="title"><b>Example&nbsp;12.1.&nbsp;
Configuring Detached State
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.DetachState" value="fetch-groups(DetachedStateField=true)"/&gt;
</pre>
</div></div><br class="example-break">
<p>
You can also alter the set of fields that will be included in the detached graph
at runtime.
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">OpenJPAEntityManager</code></a>s expose the following APIs
for controlling detached state:
</p>
<pre class="programlisting">
public DetachStateType getDetachState();
public void setDetachState(DetachStateType type);
</pre>
<p>
The <code class="classname">DetachStateType</code> enum contains the following values:
</p>
<pre class="programlisting">
enum DetachStateType {
FETCH_GROUPS,
LOADED,
ALL
}
</pre>
</div>
<div class="section" id="ref_guide_detach_field"><div class="titlepage"><div><div><h4 class="title">1.3.2.&nbsp;
Detached State Field
</h4></div></div></div>
<a class="indexterm" name="d5e16731"></a>
<p>
When the detached state field is enabled, the OpenJPA enhancer adds an
additional field to the enhanced version of your class. This field of type
<code class="classname">Object</code>. OpenJPA uses this field for bookkeeping
information, such as the versioning data needed to detect optimistic concurrency
violations when the object is re-attached.
</p>
<p>
It is possible to define this detached state field yourself. Declaring this
field in your class metadata prevents the enhancer from adding any extra fields
to the class, and keeps the enhanced class serialization-compatible with the
unenhanced version. The detached state field must not be persistent. See
<a class="xref" href="#detached-state-field" title="4.1.3.&nbsp; Detached State">Section&nbsp;4.1.3, &#8220;
Detached State
&#8221;</a> for details on how to declare a
detached state field.
</p>
<pre class="programlisting">
import org.apache.openjpa.persistence.*;
@Entity
public class Magazine
implements Serializable {
private String name;
@DetachedState private Object state;
...
}
</pre>
</div>
</div>
</div>
<div class="section" id="ref_guide_event"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Remote Event Notification Framework
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_event_conf">2.1.
Remote Commit Provider Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_event_conf_jms">2.1.1.
JMS
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_tcp">2.1.2.
TCP
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_common">2.1.3.
Common Properties
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_event_customization">2.2.
Customization
</a></span></dt></dl></div>
<a class="indexterm" name="d5e16741"></a>
<a class="indexterm" name="d5e16744"></a>
<p>
<a class="indexterm" name="d5e16749"></a>
<a class="indexterm" name="d5e16753"></a>
The remote event notification framework allows a subset of the information
available through OpenJPA's transaction events (see
<a class="xref" href="#ref_guide_runtime_pm_event" title="7.&nbsp; Transaction Events">Section&nbsp;7, &#8220;
Transaction Events
&#8221;</a>) to be broadcast to remote
listeners. OpenJPA's <a class="link" href="#ref_guide_cache" title="1.&nbsp; Data Cache">data cache</a>, for
example, uses remote events to remain synchronized when deployed in multiple
JVMs.
</p>
<p>
To enable remote events, you must configure the <code class="classname"> EntityManagerFactory
</code> to use a <code class="literal">RemoteCommitProvider</code> (see below).
</p>
<p>
When a <code class="literal">RemoteCommitProvider</code> is properly configured, you can
register
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/RemoteCommitListener.html" target="_top">
<code class="classname">RemoteCommitListener</code></a>s that will be alerted with
a list of modified object ids whenever a transaction on a remote machine
successfully commits.
</p>
<div class="section" id="ref_guide_event_conf"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
Remote Commit Provider Configuration
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_event_conf_jms">2.1.1.
JMS
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_tcp">2.1.2.
TCP
</a></span></dt><dt><span class="section"><a href="#ref_guide_event_conf_common">2.1.3.
Common Properties
</a></span></dt></dl></div>
<a class="indexterm" name="d5e16768"></a>
<p>
OpenJPA includes built in remote commit providers for JMS and TCP communication.
</p>
<div class="section" id="ref_guide_event_conf_jms"><div class="titlepage"><div><div><h4 class="title">2.1.1.&nbsp;
JMS
</h4></div></div></div>
<a class="indexterm" name="d5e16775"></a>
<p>
The JMS remote commit provider can be configured by setting the
<a class="link" href="#openjpa.RemoteCommitProvider" title="5.61.&nbsp; openjpa.RemoteCommitProvider"><code class="literal">
openjpa.RemoteCommitProvider</code></a> property to contain the
appropriate configuration properties. The JMS provider understands the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Topic</code>: The topic that the remote commit provider should
publish notifications to and subscribe to for notifications sent from other
JVMs. Defaults to <code class="literal">topic/OpenJPACommitProviderTopic</code>
</p>
</li><li class="listitem">
<p>
<code class="literal">TopicConnectionFactory</code>: The JNDI name of a <code class="classname">
javax.jms.TopicConnectionFactory</code> factory to use for finding topics.
Defaults to <code class="literal"> java:/ConnectionFactory</code>. This setting may vary
depending on the application server in use; consult the application server's
documentation for details of the default JNDI name for the <code class="classname">
javax.jms.TopicConnectionFactory</code> instance. For example, under
Weblogic, the JNDI name for the TopicConnectionFactory is <code class="literal">
javax.jms.TopicConnectionFactory</code>.
</p>
</li><li class="listitem">
<p>
<code class="literal">ExceptionReconnectAttempts</code>: The number of times to attempt
to reconnect if the JMS system notifies OpenJPA of a serious connection error.
Defaults to 0, meaning OpenJPA will log the error but otherwise ignore it,
hoping the connection is still valid.
</p>
</li><li class="listitem">
<p>
<code class="literal">*</code>: All other configuration properties will be interpreted as
settings to pass to the JNDI <code class="classname">InitialContext</code> on
construction. For example, you might set the <code class="literal">java.naming.provider.url
</code> property to the URL of the context provider.
</p>
</li></ul></div>
<p>
To configure a factory to use the JMS provider, your properties might look like
the following:
</p>
<div class="example" id="ref_guide_event_conf_jmsex"><p class="title"><b>Example&nbsp;12.2.&nbsp;
JMS Remote Commit Provider Configuration
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.RemoteCommitProvider"
value="jms(ExceptionReconnectAttempts=5)"/&gt;
</pre>
</div></div><br class="example-break">
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Because of the nature of JMS, it is important that you invoke <code class="methodname">
EntityManagerFactory.close</code> when finished with a factory. If you do
not do so, a daemon thread will stay up in the JVM, preventing the JVM from
exiting.
</p>
</div>
</div>
<div class="section" id="ref_guide_event_conf_tcp"><div class="titlepage"><div><div><h4 class="title">2.1.2.&nbsp;
TCP
</h4></div></div></div>
<a class="indexterm" name="d5e16811"></a>
<p>
The TCP remote commit provider has several options that are defined as host
specifications containing a host name or IP address and an optional port
separated by a colon. For example, the host specification <code class="literal">
saturn.bea.com:1234</code> represents an <code class="classname">InetAddress</code>
retrieved by invoking <code class="methodname">InetAddress.getByName("saturn.bea.com")
</code> and a port of 1234.
</p>
<p>
<a class="indexterm" name="d5e16820"></a>
The TCP provider can be configured by setting the <code class="literal">
openjpa.RemoteCommitProvider</code> plugin property to contain the
appropriate configuration settings. The TCP provider understands the following
properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">Port</code>: The TCP port that the provider should listen on for
commit notifications. Defaults to 5636.
</p>
</li><li class="listitem">
<p>
<code class="literal">Addresses</code>: A semicolon-separated list of IP addresses to
which notifications should be sent. No default value.
</p>
</li><li class="listitem">
<p>
<code class="literal">NumBroadcastThreads</code>: The number of threads to create for the
purpose of transmitting events to peers. You should increase this value as the
number of concurrent transactions increases. The maximum number of concurrent
transactions is a function of the size of the connection pool. See the
<code class="literal">MaxTotal</code> property of <code class="literal">
openjpa.ConnectionFactoryProperties</code> in
<a class="xref" href="#ref_guide_dbsetup_builtin" title="1.&nbsp; Using the OpenJPA DataSource">Section&nbsp;1, &#8220;
Using the OpenJPA DataSource
&#8221;</a>. Setting a value of 0 will
result in behavior where the thread invoking <code class="methodname">commit</code>
will perform the broadcast directly. Defaults to 2.
</p>
</li><li class="listitem">
<p>
<code class="literal">RecoveryTimeMillis</code>: Amount of time to wait in milliseconds
before attempting to reconnect to a peer of the cluster when connectivity to the
peer is lost. Defaults to 15000.
</p>
</li><li class="listitem">
<p>
<code class="literal">MaxIdle</code>: The number of TCP sockets (channels) to keep open
to each peer in the cluster for the transmission of events. Defaults to 2.
</p>
</li><li class="listitem">
<p>
<code class="literal">MaxTotal</code>: Total allowed number of TCP sockets
(channels) to open simultaneously between each peer in the cluster. Defaults to
2.
</p>
</li></ul></div>
<p>
To configure a factory to use the TCP provider, your properties might look like
the following:
</p>
<div class="example" id="ref_guide_event_conf_tcpex"><p class="title"><b>Example&nbsp;12.3.&nbsp;
TCP Remote Commit Provider Configuration
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.RemoteCommitProvider"
value="tcp(Addresses=10.0.1.10;10.0.1.11;10.0.1.12;10.0.1.13)"/&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_event_conf_common"><div class="titlepage"><div><div><h4 class="title">2.1.3.&nbsp;
Common Properties
</h4></div></div></div>
<a class="indexterm" name="d5e16852"></a>
<p>
In addition to the provider-specific configuration options above, all providers
accept the following plugin properties:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<code class="literal">TransmitPersistedObjectIds</code>: Whether remote commit events
will include the object ids of instances persisted in the transaction. By
default only the class names of types persisted in the transaction are sent.
This results in smaller events and more efficient network utilization. If you
have registered your own remote commit listeners, however, you may require the
persisted object ids as well.
</p>
</li></ul></div>
<p>
To transmit persisted object ids in our remote commit events using the JMS
provider, we modify the previous example as follows:
</p>
<div class="example" id="ref_guide_event_conf_jms2ex"><p class="title"><b>Example&nbsp;12.4.&nbsp;
JMS Remote Commit Provider transmitting Persisted Object Ids
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;property name="openjpa.RemoteCommitProvider"
value="jms(ExceptionReconnectAttempts=5, TransmitPersistedObjectIds=true)"/&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_event_customization"><div class="titlepage"><div><div><h3 class="title">2.2.&nbsp;
Customization
</h3></div></div></div>
<a class="indexterm" name="d5e16867"></a>
<p>
You can develop additional mechanisms for remote event notification be by
creating an implementation of the
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/RemoteCommitProvider.html" target="_top">
<code class="classname"> RemoteCommitProvider</code></a> interface, possibly by
extending the
<a class="ulink" href="../../apidocs/org/apache/openjpa/event/AbstractRemoteCommitProvider.html" target="_top">
<code class="classname">AbstractRemoteCommitProvider</code></a> abstract class..
</p>
</div>
</div>
</div>
<div class="chapter" id="ref_guide_slice"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;13.&nbsp;
Slice: Distributed Persistence
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#slice_overview">1. Overview</a></span></dt><dt><span class="section"><a href="#features_and_limitations">2. Salient Features</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e16891">2.1. Transparency</a></span></dt><dt><span class="section"><a href="#d5e16897">2.2. Scaling</a></span></dt><dt><span class="section"><a href="#d5e16903">2.3. Distributed Query</a></span></dt><dt><span class="section"><a href="#d5e16926">2.4. Data Distribution</a></span></dt><dt><span class="section"><a href="#d5e16945">2.5. Data Replication</a></span></dt><dt><span class="section"><a href="#d5e16954">2.6. Heterogeneous Database</a></span></dt><dt><span class="section"><a href="#d5e16957">2.7. Distributed Transaction</a></span></dt><dt><span class="section"><a href="#collocation_constraint">2.8. Collocation Constraint</a></span></dt></dl></dd><dt><span class="section"><a href="#slice_configuration">3. Usage</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e16974">3.1. How to activate Slice Runtime?</a></span></dt><dt><span class="section"><a href="#d5e16978">3.2. How to configure each database slice?</a></span></dt><dt><span class="section"><a href="#distribution_policy">3.3. Implement DistributionPolicy interface</a></span></dt><dt><span class="section"><a href="#replication_policy">3.4. Implement ReplicationPolicy interface</a></span></dt></dl></dd><dt><span class="section"><a href="#d5e17032">4. Configuration Properties</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e17037">4.1. Global Properties</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e17039">4.1.1. openjpa.slice.DistributionPolicy</a></span></dt><dt><span class="section"><a href="#d5e17045">4.1.2. openjpa.slice.Lenient</a></span></dt><dt><span class="section"><a href="#d5e17052">4.1.3. openjpa.slice.Master</a></span></dt><dt><span class="section"><a href="#d5e17060">4.1.4. openjpa.slice.Names</a></span></dt><dt><span class="section"><a href="#d5e17068">4.1.5. openjpa.slice.ThreadingPolicy</a></span></dt><dt><span class="section"><a href="#d5e17094">4.1.6. openjpa.slice.TransactionPolicy</a></span></dt></dl></dd><dt><span class="section"><a href="#d5e17112">4.2. Per-Slice Properties</a></span></dt></dl></dd></dl></div>
<p>
The standard JPA runtime environment works with a <span class="emphasis"><em>single</em></span>
database instance. <span class="emphasis"><em>Slice</em></span> is a plug-in module for OpenJPA
to work with <span class="emphasis"><em>multiple</em></span> databases within the same
transaction. Following sections describe the features and usage of Slice for
distributed database environment.
</p>
<div class="section" id="slice_overview"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;Overview</h2></div></div></div>
<p>
Enterprise applications are increasingly deployed in distributed database
environment. A distributed, horizontally-partitioned
database environment can be an effective scaling strategy for growing data
volume, to support multiple clients on a multi-tenant hosting platform and
many other practical scenarios that can benefit from data partitioning.
</p>
<p>
Any JPA-based user application has to address demanding technical and
conceptual challenges to interact with multiple physical databases
within a single transaction.
OpenJPA Slice encapsulates the complexity of distributed database environment
via the abstraction of <span class="emphasis"><em>virtual</em></span> database which internally
manages multiple physical database instances referred
as <span class="emphasis"><em>slice</em></span>.
<span class="emphasis"><em>Virtualization</em></span> of distributed databases makes OpenJPA
object management kernel and the user application to work in the same way as
in the case of a single physical database.
</p>
</div>
<div class="section" id="features_and_limitations"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;Salient Features</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#d5e16891">2.1. Transparency</a></span></dt><dt><span class="section"><a href="#d5e16897">2.2. Scaling</a></span></dt><dt><span class="section"><a href="#d5e16903">2.3. Distributed Query</a></span></dt><dt><span class="section"><a href="#d5e16926">2.4. Data Distribution</a></span></dt><dt><span class="section"><a href="#d5e16945">2.5. Data Replication</a></span></dt><dt><span class="section"><a href="#d5e16954">2.6. Heterogeneous Database</a></span></dt><dt><span class="section"><a href="#d5e16957">2.7. Distributed Transaction</a></span></dt><dt><span class="section"><a href="#collocation_constraint">2.8. Collocation Constraint</a></span></dt></dl></div>
<div class="section" id="d5e16891"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;Transparency</h3></div></div></div>
<p>
The primary design objective for Slice is to make the user
application transparent to the change in storage strategy where
data resides in multiple (possibly heterogeneous) databases instead
of a single database. Slice achieves this transparency by
virtualization of multiple databases as a single database such
that OpenJPA object management kernel continues to interact in
exactly the same manner with storage layer. Similarly,
the existing application or the persistent domain model requires
<span class="emphasis"><em>no change</em></span> to upgrade from a single database
to a distributed database environment.
</p>
<p>
An existing application developed for a single database can be
adapted to work with multiple databases purely by configuring
a persistence unit via <code class="classname">META-INF/persistence.xml</code>.
</p>
</div>
<div class="section" id="d5e16897"><div class="titlepage"><div><div><h3 class="title">2.2.&nbsp;Scaling</h3></div></div></div>
<p>
The primary performance characteristics for Slice is to scale against
growing data volume by <span class="emphasis"><em>horizontal</em></span> partitioning data
across many databases.
</p>
<p>
Slice executes the database operations such as query or flush <span class="emphasis"><em>in
parallel</em></span> across each physical database. Hence, scaling characteristics
against data volume are bound by the size of the maximum data
partition instead of the size of the entire data set. The use cases
where the data is naturally amenable to horizontal partitions,
for example, by temporal interval (e.g. Purchase Orders per month)
or by geographical regions (e.g. Customer by Zip Code) can derive
significant performance benefit and favorable scaling behavior by
using Slice.
</p>
</div>
<div class="section" id="d5e16903"><div class="titlepage"><div><div><h3 class="title">2.3.&nbsp;Distributed Query</h3></div></div></div>
<p>
The queries are executed in parallel across one or more slices and the
individual query results are merged into a single list before being
returned to the caller application. The <span class="emphasis"><em>merge</em></span> operation is
more complex for the queries that involve sorting and/or specify a
range. Slice supports both sorting and range queries.
</p>
<p>
Slice also supports aggregate queries where the aggregate operation
is <span class="emphasis"><em>commutative</em></span> to partitioning such as
<code class="classname">COUNT()</code> or <code class="classname">MAX()</code> but not <code class="classname">AVG()</code>.
</p>
<p>
By default, any query is executed against all available slices.
However, the application can target the query only to a subset of
slices by setting <span class="emphasis"><em>hint</em></span> on <code class="classname">javax.persistence.Query</code>.
The hint key is <code class="classname">openjpa.hint.slice.Target</code> and
hint value is an array of slice identifiers. The following
example shows how to target a query only to a pair of slices
with logical identifier <code class="classname">"One"</code> and <code class="classname">"Two"</code>.
</p><pre class="programlisting">
EntityManager em = ...;
em.getTransaction().begin();
String hint = "openjpa.hint.slice.Target";
Query query = em.createQuery("SELECT p FROM PObject")
.setHint(hint, new String[]{"One", "Two"});
List result = query.getResultList();
// verify that each instance is originating from the hinted slices
for (Object pc : result) {
String sliceOrigin = SlicePersistence.getSlice(pc);
assertTrue ("One".equals(sliceOrigin) || "Two".equals(sliceOrigin));
}
</pre><p>
</p>
<p>
To confine queries to a subset of slices via setting query hints can be considered
intrusive to existing application. The alternative means of targeting queries is to
configure a <span class="emphasis"><em>Query Target Policy</em></span>. This policy is configured
via plug-in property <code class="classname">openjpa.slice.QueryTargetPolicy</code>. The
plug-in property is fully-qualified class name of an implementation
for <code class="classname">org.apache.openjpa.slice.QueryTargetPolicy</code> interface.
This interface contract allows a user application to target a query to a subset
of slices based on the query and its bound parameters. The query target policy is consulted
only when no explicit target hint is set on the query. By default, the policy
executes a query on all available slices.
</p>
<p>
A similar policy interface <code class="classname">org.apache.openjpa.slice.FinderTargetPolicy</code>
is available to target queries that originate from <code class="classname">find()</code>
by primary key. This finder target policy is consulted
only when no explicit target hint is set on the current fetch plan. By default, the policy
executes a query on all available slices to find an instance by its primary key.
</p>
</div>
<div class="section" id="d5e16926"><div class="titlepage"><div><div><h3 class="title">2.4.&nbsp;Data Distribution</h3></div></div></div>
<p>
The user application decides how the newly persistent instances be
distributed across the slices. The user application specifies the
data distribution policy by implementing
<code class="classname">org.apache.openjpa.slice.DistributionPolicy</code>.
The <code class="classname">DistributionPolicy</code> interface
is simple with a single method. The complete listing of the
documented interface follows:
</p><pre class="programlisting">
public interface DistributionPolicy {
/**
* Gets the name of the slice where the given newly persistent
* instance will be stored.
*
* @param pc The newly persistent or to-be-merged object.
* @param slices name of the configured slices.
* @param context persistence context managing the given instance.
*
* @return identifier of the slice. This name must match one of the
* configured slice names.
* @see DistributedConfiguration#getSliceNames()
*/
String distribute(Object pc, List&lt;String&gt; slices, Object context);
}
</pre><p>
</p>
<p>
Slice runtime invokes this user-supplied method for the newly
persistent instance that is explicit argument of the
<code class="classname">javax.persistence.EntityManager.persist(Object pc)</code>
method. The user application must return a valid slice name from
this method to designate the target slice for the given instance.
The data distribution policy may be based on the attribute
of the data itself. For example, all Customer whose first name
begins with character 'A' to 'M' will be stored in one slice
while names beginning with 'N' to 'Z' will be stored in another
slice. The noteworthy aspect of such policy implementation is
the attribute values that participate in
the distribution policy logic should be set before invoking
<code class="classname">EntityManager.persist()</code> method.
</p>
<p>
The user application needs to specify the target slice <span class="emphasis"><em>only</em></span>
for the <span class="emphasis"><em>root</em></span> instance i.e. the explicit argument for the
<code class="classname">EntityManager.persist(Object pc)</code> method. Slice computes
the transitive closure of the graph i.e. the set of all instances
directly or indirectly reachable from the root instance and stores
them in the same target slice.
</p>
<p>
Slice tracks the original database for existing instances. When
an application issues a query, the resultant instances can be loaded
from different slices. As Slice tracks the original slice for each
instance, any subsequent update to an instance is committed to the
appropriate original database slice.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
You can find the original slice of an instance <code class="classname">pc</code> by
the static utility method
<code class="methodname">SlicePersistence.getSlice(pc)</code>.
This method returns the slice identifier associated with the
given <span class="emphasis"><em>managed</em></span> instance. If the instance is not
being managed then the method return null because any unmanaged or
detached instance is not associated with any slice.
</p>
</div>
</div>
<div class="section" id="d5e16945"><div class="titlepage"><div><div><h3 class="title">2.5.&nbsp;Data Replication</h3></div></div></div>
<p>
While Slice ensures that the transitive closure is stored in the
same slice, there can be data elements that are commonly referred by
many instances such as Country or Currency code. Such quasi-static
master data can be stored as identical copies in multiple slices.
The user application must enumerate the replicated entity type names in
<code class="classname">openjpa.slice.ReplicatedTypes</code> as a comma-separated list
and implement a <code class="classname">org.apache.openjpa.slice.ReplicationPolicy</code>
interface. The <code class="classname">ReplicationPolicy</code> interface
is quite similar to <code class="classname">DistributionPolicy</code>
interface except it returns an array of target slice names instead
of a single slice.
</p><pre class="programlisting">
String[] replicate(Object pc, List&lt;String&gt; slices, Object context);
</pre><p>
</p>
<p>
The default implementation assumes that replicated instances are
stored in all available slices. If any such replicated instance
is modified then the modification is updated to all target slices
to maintain the critical assumption that the state of a replicated
instance is identical across all its target slices.
</p>
</div>
<div class="section" id="d5e16954"><div class="titlepage"><div><div><h3 class="title">2.6.&nbsp;Heterogeneous Database</h3></div></div></div>
<p>
Each slice can be configured independently with its own JDBC
driver and other connection parameters. Hence the target database
environment can constitute of heterogeneous databases.
</p>
</div>
<div class="section" id="d5e16957"><div class="titlepage"><div><div><h3 class="title">2.7.&nbsp;Distributed Transaction</h3></div></div></div>
<p>
The database slices participate in a global transaction provided
each slice is configured with a XA-compliant JDBC driver, even
when the persistence unit is configured for <code class="classname">RESOURCE_LOCAL</code>
transaction.
</p>
<p>
</p><div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Warning</h3>
If any of the configured slices is not XA-compliant <span class="emphasis"><em>and</em></span>
the persistence unit is configured for <code class="classname">RESOURCE_LOCAL</code>
transaction then each slice is committed without any two-phase
commit protocol. If commit on any slice fails, then atomic nature of
the transaction is not ensured.
</div><p>
</p>
</div>
<div class="section" id="collocation_constraint"><div class="titlepage"><div><div><h3 class="title">2.8.&nbsp;Collocation Constraint</h3></div></div></div>
<p>
No relationship can exist across database slices. In O-R mapping parlance,
this condition translates to the limitation that the transitive closure of an object graph must be
<span class="emphasis"><em>collocated</em></span> in the same database.
For example, consider a domain model where Person relates to Address.
Person X refers to Address A while Person Y refers to Address B.
Collocation Constraint means that <span class="emphasis"><em>both</em></span> X and A
must be stored in the same
database slice. Similarly Y and B must be stored in a single slice.
</p>
<p>
Slice, however, helps to maintain collocation constraint automatically.
The instances in the closure set of any newly persistent instance
reachable via cascaded relationship is stored in the same slice.
The user-defined distribution policy requires to supply the slice
for the root instance only.
</p>
</div>
</div>
<div class="section" id="slice_configuration"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;Usage</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#d5e16974">3.1. How to activate Slice Runtime?</a></span></dt><dt><span class="section"><a href="#d5e16978">3.2. How to configure each database slice?</a></span></dt><dt><span class="section"><a href="#distribution_policy">3.3. Implement DistributionPolicy interface</a></span></dt><dt><span class="section"><a href="#replication_policy">3.4. Implement ReplicationPolicy interface</a></span></dt></dl></div>
<p>
Slice is activated via the following property settings:
</p>
<div class="section" id="d5e16974"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;How to activate Slice Runtime?</h3></div></div></div>
<p>
The basic configuration property is
</p><pre class="programlisting">
&lt;property name="openjpa.BrokerFactory" value="slice"/&gt;
</pre><p>
This critical configuration activates a specialized object management
kernel that can work against multiple databases.
</p>
</div>
<div class="section" id="d5e16978"><div class="titlepage"><div><div><h3 class="title">3.2.&nbsp;How to configure each database slice?</h3></div></div></div>
<p>
Each database slice is identified by a logical name unique within a
persistent unit. The list of the slices is specified by
<code class="classname">openjpa.slice.Names</code> property.
For example, specify three slices named <code class="classname">"One"</code>,
<code class="classname">"Two"</code> and <code class="classname">"Three"</code> as follows:
</p><pre class="programlisting">
&lt;property name="openjpa.slice.Names" value="One, Two, Three"/&gt;
</pre><p>
</p>
<p>
This property is not mandatory. If this property is not specified then
the configuration is scanned for logical slice names. Any property
<code class="classname">"abc"</code> of the form <code class="classname">openjpa.slice.XYZ.abc</code> will
register a slice with logical
name <code class="classname">"XYZ"</code>.
</p>
<p>
The order of the names is significant when no <code class="classname">openjpa.slice.Master</code>
property is not specified. The persistence unit is then scanned to find
all configured slice names and they are ordered alphabetically.
</p>
<p>
Each database slice properties can be configured independently.
For example, the
following configuration will register two slices with logical name
<code class="classname">One</code> and <code class="classname">Two</code>.
</p><pre class="programlisting">
&lt;property name="openjpa.slice.One.ConnectionURL" value="jdbc:mysql:localhost//slice1"/&gt;
&lt;property name="openjpa.slice.Two.ConnectionURL" value="jdbc:mysql:localhost//slice2"/&gt;
</pre><p>
</p>
<p>
Any OpenJPA specific property can be configured per slice basis.
For example, the following configuration will use two different JDBC
drivers for slice <code class="classname">One</code> and <code class="classname">Two</code>.
</p><pre class="programlisting">
&lt;property name="openjpa.slice.One.ConnectionDriverName" value="com.mysql.jdbc.Driver"/&gt;
&lt;property name="openjpa.slice.Two.ConnectionDriverName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"/&gt;
</pre><p>
</p>
<p>
Any property if unspecified for a particular slice will be defaulted by
corresponding OpenJPA property. For example, consider following three slices
</p><pre class="programlisting">
&lt;property name="openjpa.slice.One.ConnectionURL" value="jdbc:mysql:localhost//slice1"/&gt;
&lt;property name="openjpa.slice.Two.ConnectionURL" value="jdbc:mysql:localhost//slice2"/&gt;
&lt;property name="openjpa.slice.Three.ConnectionURL" value="jdbc:oracle:localhost//slice3"/&gt;
&lt;property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/&gt;
&lt;property name="openjpa.slice.Three.ConnectionDriverName" value="oracle.jdbc.Driver"/&gt;
</pre><p>
In this example, <code class="classname">Three</code> will use slice-specific
<code class="classname">oracle.jdbc.Driver</code> driver while slice
<code class="classname">One</code> and <code class="classname">Two</code> will use
the driver <code class="classname">com.mysql.jdbc.Driver</code> as
specified by <code class="classname">openjpa.ConnectionDriverName</code>
property value.
</p>
<p>
A connection pool may also be used with Slice by using the <code class="literal">openjpa.ConnectionProperties</code> property.
For example to use commons-dbcp with Derby you might use the following properties :
</p><pre class="programlisting">
&lt;property name="openjpa.BrokerFactory" value="slice"/&gt;
&lt;property name="openjpa.ConnectionDriverName" value="org.apache.commons.dbcp.BasicDataSource"/&gt;
&lt;property name="openjpa.slice.Names" value="One,Two"/&gt;
&lt;property name="openjpa.slice.Master" value="Two"/&gt;
&lt;property name="openjpa.slice.One.ConnectionProperties" value="Url=jdbc:derby:target/database/openjpa-slice1;create=true, DriverClassName=org.apache.derby.jdbc.EmbeddedDriver"/&gt;
&lt;property name="openjpa.slice.Two.ConnectionProperties" value="Url=jdbc:derby:target/database/openjpa-slice2;create=true, DriverClassName=org.apache.derby.jdbc.EmbeddedDriver"/&gt;
&lt;property name="openjpa.jdbc.DBDictionary" value="derby"/&gt;
</pre><p>
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Note</h3>
<p>
Be aware that you need to set the DBDictionary when using commons-dbcp.
</p>
</div><p>
</p>
</div>
<div class="section" id="distribution_policy"><div class="titlepage"><div><div><h3 class="title">3.3.&nbsp;Implement DistributionPolicy interface</h3></div></div></div>
<p>
Slice needs to determine which slice will persist a new instance.
The application can only decide this policy (for example,
all PurchaseOrders before April 30 goes to slice <code class="classname">One</code>,
all the rest goes to slice <code class="classname">Two</code>). This is why
the application has to implement
<code class="classname">org.apache.openjpa.slice.DistributionPolicy</code> and
specify the implementation class in configuration
</p><pre class="programlisting">
&lt;property name="openjpa.slice.DistributionPolicy" value="com.acme.foo.MyOptimialDistributionPolicy"/&gt;
</pre><p>
</p>
<p>
The interface <code class="classname">org.apache.openjpa.slice.DistributionPolicy</code>
is simple with a single method. The complete listing of the
documented interface follows:
</p><pre class="programlisting">
public interface DistributionPolicy {
/**
* Gets the name of the slice where a given instance will be stored.
*
* @param pc The newly persistent or to-be-merged object.
* @param slices name of the configured slices.
* @param context persistence context managing the given instance.
*
* @return identifier of the slice. This name must match one of the
* configured slice names.
* @see DistributedConfiguration#getSliceNames()
*/
String distribute(Object pc, List&lt;String&gt; slices, Object context);
}
</pre><p>
</p>
<p>
While implementing a distribution policy the most important thing to
remember is <a class="link" href="#collocation_constraint" title="2.8.&nbsp;Collocation Constraint">collocation constraint</a>.
Because Slice can not establish or query any cross-database relationship, all the
related instances must be stored in the same database slice.
Slice can determine the closure of a root object by traversal of
cascaded relationships. Hence user-defined policy has to only decide the
database for the root instance that is the explicit argument to
<code class="methodname">EntityManager.persist()</code> call.
Slice will ensure that all other related instances that get persisted by cascade
are assigned to the same database slice as that of the root instance.
However, the user-defined distribution policy must return the
same slice identifier for the instances that are logically related but
not cascaded for persist.
</p>
</div>
<div class="section" id="replication_policy"><div class="titlepage"><div><div><h3 class="title">3.4.&nbsp;Implement ReplicationPolicy interface</h3></div></div></div>
<p>
The entities that are enumerated in <code class="classname">openjpa.slice.ReplicatedTypes</code>
property can be stored in multiple slices as identical copies.
Specify the implementation class of <code class="classname">ReplicationPolicy</code> in configuration as
</p><pre class="programlisting">
&lt;property name="openjpa.slice.ReplicationPolicy" value="com.acme.foo.MyReplicationPolicy"/&gt;
</pre><p>
</p>
</div>
</div>
<div class="section" id="d5e17032"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;Configuration Properties</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#d5e17037">4.1. Global Properties</a></span></dt><dd><dl><dt><span class="section"><a href="#d5e17039">4.1.1. openjpa.slice.DistributionPolicy</a></span></dt><dt><span class="section"><a href="#d5e17045">4.1.2. openjpa.slice.Lenient</a></span></dt><dt><span class="section"><a href="#d5e17052">4.1.3. openjpa.slice.Master</a></span></dt><dt><span class="section"><a href="#d5e17060">4.1.4. openjpa.slice.Names</a></span></dt><dt><span class="section"><a href="#d5e17068">4.1.5. openjpa.slice.ThreadingPolicy</a></span></dt><dt><span class="section"><a href="#d5e17094">4.1.6. openjpa.slice.TransactionPolicy</a></span></dt></dl></dd><dt><span class="section"><a href="#d5e17112">4.2. Per-Slice Properties</a></span></dt></dl></div>
<p>
The properties to configure Slice can be classified in two broad groups.
The <span class="emphasis"><em>global</em></span> properties apply to all the slices, for example,
the thread pool used to execute the queries in parallel or the transaction
manager used to coordinate transaction across multiple slices.
The <span class="emphasis"><em>per-slice</em></span> properties apply to individual slice, for example,
the JDBC connection URL of a slice.
</p>
<div class="section" id="d5e17037"><div class="titlepage"><div><div><h3 class="title">4.1.&nbsp;Global Properties</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#d5e17039">4.1.1. openjpa.slice.DistributionPolicy</a></span></dt><dt><span class="section"><a href="#d5e17045">4.1.2. openjpa.slice.Lenient</a></span></dt><dt><span class="section"><a href="#d5e17052">4.1.3. openjpa.slice.Master</a></span></dt><dt><span class="section"><a href="#d5e17060">4.1.4. openjpa.slice.Names</a></span></dt><dt><span class="section"><a href="#d5e17068">4.1.5. openjpa.slice.ThreadingPolicy</a></span></dt><dt><span class="section"><a href="#d5e17094">4.1.6. openjpa.slice.TransactionPolicy</a></span></dt></dl></div>
<div class="section" id="d5e17039"><div class="titlepage"><div><div><h4 class="title">4.1.1.&nbsp;openjpa.slice.DistributionPolicy</h4></div></div></div>
<p>
This <span class="emphasis"><em>mandatory</em></span> plug-in property determines how newly
persistent instances are distributed across individual slices.
The value of this property is a fully-qualified class name that implements
<a class="ulink" href="../../apidocs/org/apache/openjpa/slice/DistributionPolicy.html" target="_top">
<code class="classname">org.apache.openjpa.slice.DistributionPolicy</code>
</a> interface.
</p>
</div>
<div class="section" id="d5e17045"><div class="titlepage"><div><div><h4 class="title">4.1.2.&nbsp;openjpa.slice.Lenient</h4></div></div></div>
<p>
This boolean plug-in property controls the behavior when one or more slice
can not be connected or unavailable for some other reasons.
If <code class="classname">true</code>, the unreachable slices are ignored. If
<code class="classname">false</code> then any unreachable slice will raise an exception
during startup.
</p>
<p>
By default this value is set to <code class="classname">false</code> i.e. all configured
slices must be available.
</p>
</div>
<div class="section" id="d5e17052"><div class="titlepage"><div><div><h4 class="title">4.1.3.&nbsp;openjpa.slice.Master</h4></div></div></div>
<p>
The user application often directs OpenJPA to generate primary keys
for persistence instances automatically or from a specific database
sequence. For such primary key value generation strategy where
a database instance is required, Slice uses a designated slice
referred to as <span class="emphasis"><em>master</em></span> slice.
</p>
<p>
The master slice can be specified explicitly via
<code class="classname">openjpa.slice.Master</code> property and whose value is one
of the configured slice names. If this property is not explicitly
specified then, by default, the master slice is the first slice
in the list of configured slice names.
</p>
<p>
</p><div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Warning</h3>
Currently, there is no provision to use sequence from
multiple slices.
</div><p>
</p>
</div>
<div class="section" id="d5e17060"><div class="titlepage"><div><div><h4 class="title">4.1.4.&nbsp;openjpa.slice.Names</h4></div></div></div>
<p>
This plug-in property can be used to register the logical slice names.
The value of this property is comma-separated list of slice names.
The ordering of the names in this list is
<span class="emphasis"><em>significant</em></span> because
<a class="link" href="#distribution_policy" title="3.3.&nbsp;Implement DistributionPolicy interface">DistributionPolicy</a> and
<a class="link" href="#replication_policy" title="3.4.&nbsp;Implement ReplicationPolicy interface">ReplicationPolicy</a> receive
the input argument of the slice names in the same order.
</p>
<p>
If logical slice names are not registered explicitly via this property,
then all logical slice names available in the persistence unit are
registered. The ordering of the slice names in this case is alphabetical.
</p>
<p>
If logical slice names are registered explicitly via this property, then
any logical slice that is available in the persistence unit but excluded
from this list is ignored.
</p>
</div>
<div class="section" id="d5e17068"><div class="titlepage"><div><div><h4 class="title">4.1.5.&nbsp;openjpa.slice.ThreadingPolicy</h4></div></div></div>
<p>
This plug-in property determines the nature of thread pool being used
for database operations such as query or flush on individual slices.
The value of the property is a
fully-qualified class name that implements
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html" target="_top">
<code class="classname">java.util.concurrent.ExecutorService</code>
</a> interface.
Two pre-defined pools can be chosen via their aliases namely
<code class="classname">fixed</code> or <code class="classname">cached</code>.
</p>
<p>
The pre-defined alias <code class="classname">cached</code> activates a
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()" target="_top">cached thread pool</a>.
A cached thread pool creates new threads as needed, but will reuse
previously constructed threads when they are available. This pool
is suitable in scenarios that execute many short-lived asynchronous tasks.
The way Slice uses the thread pool to execute database operations is
akin to such scenario and hence <code class="classname">cached</code> is the default
value for this plug-in property.
</p>
<p>
The <code class="classname">fixed</code> alias activates a
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)" target="_top">fixed thread pool</a>.
The fixed thread pool can be further parameterized with
<code class="classname">CorePoolSize</code>, <code class="classname">MaximumPoolSize</code>,
<code class="classname">KeepAliveTime</code> and <code class="classname">RejectedExecutionHandler</code>.
The meaning of these parameters are described in
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html" target="_top">JavaDoc</a>.
The users can exercise finer control on thread pool behavior via these
parameters.
By default, the core pool size is <code class="classname">10</code>, maximum pool size is
also <code class="classname">10</code>, keep alive time is <code class="classname">60</code> seconds and
rejected execution is
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.AbortPolicy.html" target="_top">aborted</a>.
</p>
<p>
Both of the pre-defined aliases can be parameterized with a fully-qualified
class name that implements
<a class="ulink" href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadFactory.html" target="_top">
<code class="classname">java.util.concurrent.ThreadFactory</code>
</a> interface.
</p>
</div>
<div class="section" id="d5e17094"><div class="titlepage"><div><div><h4 class="title">4.1.6.&nbsp;openjpa.slice.TransactionPolicy</h4></div></div></div>
<p>
This plug-in property determines the policy for transaction commit
across multiple slices. The value of this property is a fully-qualified
class name that implements
<a class="ulink" href="http://download.oracle.com/javaee/6/api/javax/transaction/TransactionManager.html" target="_top">
<code class="classname">javax.transaction.TransactionManager</code>
</a> interface.
</p>
<p>
Three pre-defined policies can be chosen
by their aliases namely <code class="classname">default</code>,
<code class="classname">xa</code> and <code class="classname">jndi</code>.
</p>
<p>
The <code class="classname">default</code> policy employs
a Transaction Manager that commits or rolls back transaction on individual
slices <span class="emphasis"><em>without</em></span> a two-phase commit protocol.
It does <span class="emphasis"><em>not</em></span>
guarantee atomic nature of transaction across all the slices because if
one or more slice fails to commit, there is no way to rollback the transaction
on other slices that committed successfully.
</p>
<p>
The <code class="classname">xa</code> policy employs a Transaction Manager that that commits
or rolls back transaction on individual
slices using a two-phase commit protocol. The prerequisite to use this scheme
is, of course, that all the slices must be configured to use
XA-compliant JDBC driver.
</p>
<p>
The <code class="classname">jndi</code> policy employs a Transaction Manager by looking up the
JNDI context. The prerequisite to use this transaction
manager is, of course, that all the slices must be configured to use
XA-compliant JDBC driver.
</p><div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><h3 class="title">Warning</h3>This JNDI based policy is not available currently.</div><p>
</p>
</div>
</div>
<div class="section" id="d5e17112"><div class="titlepage"><div><div><h3 class="title">4.2.&nbsp;Per-Slice Properties</h3></div></div></div>
<p>
Any OpenJPA property can be configured for each individual slice. The property name
is of the form <code class="classname">openjpa.slice.[Logical slice name].[OpenJPA Property Name]</code>.
For example, <code class="classname">openjpa.slice.One.ConnectionURL</code> where <code class="classname">One</code>
is the logical slice name and <code class="classname">ConnectionURL</code> is an OpenJPA property
name.
</p>
<p>
If a property is not configured for a specific slice, then the value for
the property equals to the corresponding <code class="classname">openjpa.*</code> property.
</p>
</div>
</div>
</div>
<div class="chapter" id="ref_guide_integration"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;14.&nbsp;
Third Party Integration
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_integration_ant">1.
Apache Ant
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_conf">1.1.
Common Ant Configuration Options
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_enhance">1.2.
Enhancer Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_appidtool">1.3.
Application Identity Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_mappingtool">1.4.
Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_revmappingtool">1.5.
Reverse Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_schematool">1.6.
Schema Tool Ant Task
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_integration_dbcp">2.
Apache Commons DBCP
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_integration_dbcp_conf">2.1.
Apache Commons DBCP Configuration Options
</a></span></dt></dl></dd></dl></div>
<p>
OpenJPA provides a number of mechanisms for integrating with third-party tools.
The following chapter will illustrate these integration features.
</p>
<div class="section" id="ref_guide_integration_ant"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Apache Ant
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_integration_conf">1.1.
Common Ant Configuration Options
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_enhance">1.2.
Enhancer Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_appidtool">1.3.
Application Identity Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_mappingtool">1.4.
Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_revmappingtool">1.5.
Reverse Mapping Tool Ant Task
</a></span></dt><dt><span class="section"><a href="#ref_guide_integration_schematool">1.6.
Schema Tool Ant Task
</a></span></dt></dl></div>
<a class="indexterm" name="d5e17126"></a>
<p>
Ant is a very popular tool for building Java projects. It is similar to the
<code class="literal">make</code> command, but is Java-centric and has more modern
features. Ant is open source, and can be downloaded from Apache's Ant web page
at <a class="ulink" href="http://ant.apache.org/" target="_top"> http://ant.apache.org/
</a>. Ant has become the de-facto standard build tool for Java, and many
commercial integrated development environments provide some support for using
Ant build files. The remainder of this section assumes familiarity with writing
Ant <code class="filename">build.xml</code> files.
</p>
<p>
OpenJPA provides pre-built Ant task definitions for all bundled tools:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="link" href="#ref_guide_integration_enhance" title="1.2.&nbsp; Enhancer Ant Task">Enhancer Task</a>
</p>
</li><li class="listitem">
<p>
<a class="link" href="#ref_guide_integration_appidtool" title="1.3.&nbsp; Application Identity Tool Ant Task">Application Identity Tool Task
</a>
</p>
</li><li class="listitem">
<p>
<a class="link" href="#ref_guide_integration_mappingtool" title="1.4.&nbsp; Mapping Tool Ant Task">Mapping Tool Task</a>
</p>
</li><li class="listitem">
<p>
<a class="link" href="#ref_guide_integration_revmappingtool" title="1.5.&nbsp; Reverse Mapping Tool Ant Task">Reverse Mapping Tool Task
</a>
</p>
</li><li class="listitem">
<p>
<a class="link" href="#ref_guide_integration_schematool" title="1.6.&nbsp; Schema Tool Ant Task">Schema Tool Task</a>
</p>
</li></ul></div>
<p>
The source code for all the Ant tasks is provided with the distribution under
the <code class="filename">src</code> directory. This allows you to customize various
aspects of the Ant tasks in order to better integrate into your development
environment.
</p>
<div class="section" id="ref_guide_integration_conf"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Common Ant Configuration Options
</h3></div></div></div>
<a class="indexterm" name="d5e17153"></a>
<p>
All OpenJPA tasks accept a nested <code class="literal">config</code> element, which
defines the configuration environment in which the specified task will run. The
attributes for the <code class="literal">config</code> tag are defined by the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/conf/JDBCConfiguration.html" target="_top">
<code class="classname">JDBCConfiguration</code></a> bean methods. Note that
excluding the <code class="literal">config</code> element will cause the Ant task to use
the default system configuration mechanism, such as the configuration defined in
the <code class="filename">org.apache.openjpa.xml</code> file.
</p>
<p>
Following is an example of how to use the nested <code class="literal">config</code> tag
in a <code class="filename">build.xml</code> file:
</p>
<div class="example" id="ref_guide_integration_conf_config"><p class="title"><b>Example&nbsp;14.1.&nbsp;
Using the &lt;config&gt; Ant Tag
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;mappingtool&gt;
&lt;fileset dir="${basedir}"&gt;
&lt;include name="**/model/*.java" /&gt;
&lt;/fileset&gt;
&lt;config connectionUserName="scott" connectionPassword="tiger"
connectionURL="jdbc:oracle:thin:@saturn:1521:solarsid"
connectionDriverName="oracle.jdbc.driver.OracleDriver" /&gt;
&lt;/mappingtool&gt;
</pre>
</div></div><br class="example-break">
<p>
It is also possible to specify a <code class="literal">properties</code> or <code class="literal">
propertiesFile</code> attribute on the <code class="literal">config</code> tag, which
will be used to locate a properties resource or file. The resource will be
loaded relative to the current CLASSPATH.
</p>
<div class="example" id="ref_guide_integration_props"><p class="title"><b>Example&nbsp;14.2.&nbsp;
Using the Properties Attribute of the &lt;config&gt; Tag
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;mappingtool&gt;
&lt;fileset dir="${basedir}"&gt;
&lt;include name="**/model/*.java"/&gt;
&lt;/fileset&gt;
&lt;config properties="openjpa-dev.xml"/&gt;
&lt;/mappingtool&gt;
</pre>
</div></div><br class="example-break">
<div class="example" id="ref_guide_integration_propsfile"><p class="title"><b>Example&nbsp;14.3.&nbsp;
Using the PropertiesFile Attribute of the &lt;config&gt; Tag
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;mappingtool&gt;
&lt;fileset dir="${basedir}"&gt;
&lt;include name="**/model/*.java"/&gt;
&lt;/fileset&gt;
&lt;config propertiesFile="../conf/openjpa-dev.xml"/&gt;
&lt;/mappingtool&gt;
</pre>
</div></div><br class="example-break">
<p>
Tasks also accept a nested <code class="literal">classpath</code> element, which you can
use in place of the default classpath. The <code class="literal">classpath</code> argument
behaves the same as it does for Ant's standard <code class="literal">javac</code> element.
It is sometimes the case that projects are compiled to a separate directory than
the source tree. If the target path for compiled classes is not included in the
project's classpath, then a <code class="literal">classpath</code> element that includes
the target class directory needs to be included so the enhancer and mapping tool
can locate the relevant classes.
</p>
<p>
Following is an example of using a <code class="literal">classpath</code> tag:
</p>
<div class="example" id="ref_guide_integration_conf_classpath"><p class="title"><b>Example&nbsp;14.4.&nbsp;
Using the &lt;classpath&gt; Ant Tag
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;openjpac&gt;
&lt;fileset dir="${basedir}/source"&gt;
&lt;include name="**/model/*.java" /&gt;
&lt;/fileset&gt;
&lt;classpath&gt;
&lt;pathelement location="${basedir}/classes"/&gt;
&lt;pathelement location="${basedir}/source"/&gt;
&lt;pathelement path="${java.class.path}"/&gt;
&lt;/classpath&gt;
&lt;/openjpac&gt;
</pre>
</div></div><br class="example-break">
<p>
Finally, tasks that invoke code-generation tools like the application identity
tool and reverse mapping tool accept a nested <code class="literal">codeformat</code>
element. See the code formatting documentation in
<a class="xref" href="#ref_guide_conf_devtools_format" title="3.1.&nbsp; Code Formatting">Section&nbsp;3.1, &#8220;
Code Formatting
&#8221;</a> for a list of code
formatting attributes.
</p>
<div class="example" id="ref_guide_integration_conf_codeformat"><p class="title"><b>Example&nbsp;14.5.&nbsp;
Using the &lt;codeformat&gt; Ant Tag
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;reversemappingtool package="com.xyz.jdo" directory="${basedir}/src"&gt;
&lt;codeformat tabSpaces="4" spaceBeforeParen="true" braceOnSameLine="false"/&gt;
&lt;/reversemappingtool&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_integration_enhance"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Enhancer Ant Task
</h3></div></div></div>
<a class="indexterm" name="d5e17197"></a>
<a class="indexterm" name="d5e17200"></a>
<p>
The enhancer task allows you to invoke the OpenJPA enhancer directly from within
the Ant build process. The task's parameters correspond exactly to the long
versions of the command-line arguments to the
<a class="link" href="#ref_guide_pc_enhance" title="2.&nbsp; Enhancement"><code class="classname">
org.apache.openjpa.enhance.PCEnhancer</code></a>.
</p>
<p>
The enhancer task accepts a nested <code class="literal">fileset</code> tag to specify the
files that should be processed. You can specify <code class="filename">.java</code> or
<code class="filename">.class</code> files. If you do not specify any files, the task
will run on the classes listed in your <code class="filename">persistence.xml</code> or
<a class="link" href="#openjpa.MetaDataFactory" title="5.48.&nbsp; openjpa.MetaDataFactory"><code class="literal">
openjpa.MetaDataFactory</code></a> property. You must, however, supply the
classpath you wish the enhancer to run with. This classpath must include, at
minimum, the openjpa jar(s), persistence.xml and the target classes.
</p>
<p>
Following is an example of using the enhancer task in a <code class="filename">build.xml
</code> file:
</p>
<div class="example" id="ref_guide_integration_enhance_task"><p class="title"><b>Example&nbsp;14.6.&nbsp;
Invoking the Enhancer from Ant
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;target name="enhance"&gt;
&lt;!-- Define the classpath to include the necessary files. --&gt;
&lt;!-- ex. openjpa jars, persistence.xml, orm.xml, and target classes --&gt;
&lt;path id="jpa.enhancement.classpath"&gt;
&lt;!-- Assuming persistence.xml/orm.xml are in resources/META-INF --&gt;
&lt;pathelement location="resources/" /&gt;
&lt;!-- Location of the .class files --&gt;
&lt;pathelement location="bin/" /&gt;
&lt;!-- Add the openjpa jars --&gt;
&lt;fileset dir="."&gt;
&lt;include name="**/lib/*.jar" /&gt;
&lt;/fileset&gt;
&lt;/path&gt;
&lt;!-- define the openjpac task; this can be done at the top of the --&gt;
&lt;!-- build.xml file, so it will be available for all targets --&gt;
&lt;taskdef name="openjpac" classname="org.apache.openjpa.ant.PCEnhancerTask" classpathref="jpa.enhancement.classpath" /&gt;
&lt;!-- invoke enhancer on all .class files below the model directory --&gt;
&lt;openjpac&gt;
&lt;classpath refid="jpa.enhancement.classpath" /&gt;
&lt;fileset dir="."&gt;
&lt;include name="**/model/*.class" /&gt;
&lt;/fileset&gt;
&lt;/openjpac&gt;
&lt;echo message="Enhancement complete" /&gt;
&lt;/target&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_integration_appidtool"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Application Identity Tool Ant Task
</h3></div></div></div>
<a class="indexterm" name="d5e17220"></a>
<a class="indexterm" name="d5e17223"></a>
<p>
The application identity tool task allows you to invoke the application identity
tool directly from within the Ant build process. The task's parameters
correspond exactly to the long versions of the command-line arguments to the
<a class="link" href="#ref_guide_pc_appid_appidtool" title="Example&nbsp;5.8.&nbsp; Using the Application Identity Tool"><code class="classname">
org.apache.openjpa.enhance.ApplicationIdTool</code></a>.
</p>
<p>
The application identity tool task accepts a nested <code class="literal">fileset</code>
tag to specify the files that should be processed. You can specify <code class="filename">
.java</code> or <code class="filename">.class</code> files. If you do not specify any
files, the task will run on the classes listed in your <code class="filename">persistence.xml
</code> file or <a class="link" href="#openjpa.MetaDataFactory" title="5.48.&nbsp; openjpa.MetaDataFactory"><code class="literal">
openjpa.MetaDataFactory</code></a> property.
</p>
<p>
Following is an example of using the application identity tool task in a
<code class="filename">build.xml</code> file:
</p>
<div class="example" id="ref_guide_integration_appidtool_task"><p class="title"><b>Example&nbsp;14.7.&nbsp;
Invoking the Application Identity Tool from Ant
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;target name="appids"&gt;
&lt;!-- define the appidtool task; this can be done at the top of --&gt;
&lt;!-- the build.xml file, so it will be available for all targets --&gt;
&lt;taskdef name="appidtool" classname="org.apache.openjpa.ant.ApplicationIdToolTask"/&gt;
&lt;!-- invoke tool on all .jdo files below the current directory --&gt;
&lt;appidtool&gt;
&lt;fileset dir="."&gt;
&lt;include name="**/model/*.java" /&gt;
&lt;/fileset&gt;
&lt;codeformat spaceBeforeParen="true" braceOnSameLine="false"/&gt;
&lt;/appidtool&gt;
&lt;/target&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_integration_mappingtool"><div class="titlepage"><div><div><h3 class="title">1.4.&nbsp;
Mapping Tool Ant Task
</h3></div></div></div>
<a class="indexterm" name="d5e17243"></a>
<a class="indexterm" name="d5e17246"></a>
<p>
The mapping tool task allows you to directly invoke the mapping tool from within
the Ant build process. It is useful for making sure that the database schema and
object-relational mapping data is always synchronized with your persistent class
definitions, without needing to remember to invoke the mapping tool manually.
The task's parameters correspond exactly to the long versions of the
command-line arguments to the <a class="link" href="#ref_guide_mapping_mappingtool" title="1.&nbsp; Forward Mapping">
<code class="classname">org.apache.openjpa.jdbc.meta.MappingTool</code></a>.
</p>
<p>
The mapping tool task accepts a nested <code class="literal">fileset</code> tag to specify
the files that should be processed. You can specify <code class="filename">.java</code>
or <code class="filename">.class</code> files. If you do not specify any files, the task
will run on the classes listed in your <code class="filename">persistence.xml</code> file
or <a class="link" href="#openjpa.MetaDataFactory" title="5.48.&nbsp; openjpa.MetaDataFactory"><code class="literal">
openjpa.MetaDataFactory</code></a> property.
</p>
<p>
Following is an example of a <code class="filename">build.xml</code> target that invokes
the mapping tool:
</p>
<div class="example" id="ref_guide_integration_mappingtool_task"><p class="title"><b>Example&nbsp;14.8.&nbsp;
Invoking the Mapping Tool from Ant
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;target name="refresh"&gt;
&lt;!-- define the mappingtool task; this can be done at the top of --&gt;
&lt;!-- the build.xml file, so it will be available for all targets --&gt;
&lt;taskdef name="mappingtool" classname="org.apache.openjpa.jdbc.ant.MappingToolTask"/&gt;
&lt;!-- add the schema components for all .jdo files below the --&gt;
&lt;!-- current directory --&gt;
&lt;mappingtool action="buildSchema"&gt;
&lt;fileset dir="."&gt;
&lt;include name="**/*.jdo" /&gt;
&lt;/fileset&gt;
&lt;/mappingtool&gt;
&lt;/target&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_integration_revmappingtool"><div class="titlepage"><div><div><h3 class="title">1.5.&nbsp;
Reverse Mapping Tool Ant Task
</h3></div></div></div>
<a class="indexterm" name="d5e17266"></a>
<a class="indexterm" name="d5e17269"></a>
<p>
The reverse mapping tool task allows you to directly invoke the reverse mapping
tool from within Ant. While many users will only run the reverse mapping process
once, others will make it part of their build process. The task's parameters
correspond exactly to the long versions of the command-line arguments to the
<a class="link" href="#ref_guide_pc_reverse_reversemappingtool" title="Example&nbsp;7.9.&nbsp; Using the Reverse Mapping Tool"><code class="classname">
org.apache.openjpa.jdbc.meta.ReverseMappingTool</code></a>.
</p>
<p>
Following is an example of a <code class="filename">build.xml</code> target that invokes
the reverse mapping tool:
</p>
<div class="example" id="ref_guide_integration_revmappingtool_task"><p class="title"><b>Example&nbsp;14.9.&nbsp;
Invoking the Reverse Mapping Tool from Ant
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;target name="reversemap"&gt;
&lt;!-- define the reversemappingtool task; this can be done at the top of --&gt;
&lt;!-- the build.xml file, so it will be available for all targets --&gt;
&lt;taskdef name="reversemappingtool"
classname="org.apache.openjpa.jdbc.ant.ReverseMappingToolTask"/&gt;
&lt;!-- reverse map the entire database --&gt;
&lt;reversemappingtool package="com.xyz.model" directory="${basedir}/src"
customizerProperties="${basedir}/conf/reverse.properties"&gt;
&lt;codeformat tabSpaces="4" spaceBeforeParen="true" braceOnSameLine="false"/&gt;
&lt;/reversemappingtool&gt;
&lt;/target&gt;
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="ref_guide_integration_schematool"><div class="titlepage"><div><div><h3 class="title">1.6.&nbsp;
Schema Tool Ant Task
</h3></div></div></div>
<a class="indexterm" name="d5e17282"></a>
<a class="indexterm" name="d5e17285"></a>
<p>
The schema tool task allows you to directly invoke the schema tool from within
the Ant build process. The task's parameters correspond exactly to the long
versions of the command-line arguments to the
<a class="link" href="#ref_guide_schema_schematool" title="13.&nbsp; Schema Tool"><code class="classname">
org.apache.openjpa.jdbc.schema.SchemaTool</code></a>.
</p>
<p>
Following is an example of a <code class="filename">build.xml</code> target that invokes
the schema tool:
</p>
<div class="example" id="ref_guide_integration_schematool_task"><p class="title"><b>Example&nbsp;14.10.&nbsp;
Invoking the Schema Tool from Ant
</b></p><div class="example-contents">
<pre class="programlisting">
&lt;target name="schema"&gt;
&lt;!-- define the schematool task; this can be done at the top of --&gt;
&lt;!-- the build.xml file, so it will be available for all targets --&gt;
&lt;taskdef name="schematool" classname="org.apache.openjpa.jdbc.ant.SchemaToolTask"/&gt;
&lt;!-- add the schema components for all .schema files below the --&gt;
&lt;!-- current directory --&gt;
&lt;schematool action="add"&gt;
&lt;fileset dir="."&gt;
&lt;include name="**/*.schema" /&gt;
&lt;/fileset&gt;
&lt;/schematool&gt;
&lt;/target&gt;
</pre>
</div></div><br class="example-break">
</div>
</div>
<div class="section" id="ref_guide_integration_dbcp"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Apache Commons DBCP
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_integration_dbcp_conf">2.1.
Apache Commons DBCP Configuration Options
</a></span></dt></dl></div>
<a class="indexterm" name="d5e17298"></a>
<p>
OpenJPA does not provide its own JDBC connection pooling, as this should already be supplied to applications running in a Java EE application server in container managed mode. For Java SE or applications running in application managed mode, the OpenJPA aggregate <code class="literal">openjpa-all.jar</code> artifact and the binary assembly contains copies of <a class="ulink" href="http://commons.apache.org/dbcp/" target="_top">Apache Commons DBCP</a>, which provides a robust connection pooling implementation.
</p>
<div class="section" id="ref_guide_integration_dbcp_conf"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;
Apache Commons DBCP Configuration Options
</h3></div></div></div>
<a class="indexterm" name="d5e17305"></a>
<p>
The <a class="link" href="#ref_guide_dbsetup_thirdparty" title="2.&nbsp; Using a Third-Party DataSource">JDBC DataSource configuration options</a> that we will need to modify in order to use Apache Commons DBCP for connection pooling are:
</p><pre class="programlisting">
connectionDriverName="org.apache.commons.dbcp.BasicDataSource"
connectionProperties="DriverClassName=&lt;prior connectionDriverName&gt;, ..."
</pre><p>
Additional Commons DBCP arguments can be provided in the connectionProperties value, such as:
</p><pre class="programlisting">
MaxTotal=10,MaxIdle=5,MinIdle=2,MaxWait=60000
</pre><p>
Please visit the Commons DBCP website for the entire list of <a class="ulink" href="http://commons.apache.org/dbcp/configuration.html" target="_top">configuration options</a> and explanations.
</p>
<div class="example" id="ref_guide_integration_dbcp_derby"><p class="title"><b>Example&nbsp;14.11.&nbsp;
Using Commons DBCP with Apache Derby
</b></p><div class="example-contents">
For example, to use Commons DBCP with an Apache Derby database server, we would need to provide the following settings, as either settings in the persistence.xml or as system environment overrides:
<pre class="programlisting">
&lt;property name="openjpa.ConnectionDriverName" value="org.apache.commons.dbcp.BasicDataSource"/&gt;
&lt;property name="openjpa.ConnectionProperties" value="DriverClassName=org.apache.derby.jdbc.EmbeddedDriver, Url=jdbc:derby://localhost:1527/openjpa, Username=uid, Password=pwd"/&gt;
</pre>
Notice that we supplied Username and Password settings, which are required by Commons DBCP for connecting to a database over the network, but can be dummy values if database security is not enabled.
</div></div><br class="example-break">
</div>
</div>
</div>
<div class="chapter" id="ref_guide_optimization"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;15.&nbsp;
Optimization Guidelines
</h2></div></div></div>
<a class="indexterm" name="d5e17318"></a>
<p>
There are numerous techniques you can use in order to ensure that OpenJPA
operates in the fastest and most efficient manner. Following are some
guidelines. Each describes what impact it will have on performance and
scalability. Note that general guidelines regarding performance or scalability
issues are just that - guidelines. Depending on the particular characteristics
of your application, the optimal settings may be considerably different than
what is outlined below.
</p>
<p>
In the following table, each row is labeled with a list of italicized keywords.
These keywords identify what characteristics the row in question may improve
upon. Many of the rows are marked with one or both of the <span class="emphasis"><em>performance
</em></span> and <span class="emphasis"><em>scalability</em></span> labels. It is important to bear
in mind the differences between performance and scalability (for the most part,
we are referring to system-wide scalability, and not necessarily only
scalability within a single JVM). The performance-related hints will probably
improve the performance of your application for a given user load, whereas the
scalability-related hints will probably increase the total number of users that
your application can service. Sometimes, increasing performance will decrease
scalability, and vice versa. Typically, options that reduce the amount of work
done on the database server will improve scalability, whereas those that push
more work onto the server will have a negative impact on scalability.
</p>
<div class="table" id="d5e17324"><p class="title"><b>Table&nbsp;15.1.&nbsp;
Optimization Guidelines
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Optimization Guidelines&#xA; " border="1"><colgroup><col align="left" class="name"><col align="left" class="desc"></colgroup><tbody valign="top"><tr><td align="left" valign="top">
<span class="bold"><strong>
Use a connection pool
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
OpenJPA's built-in datasource does not perform connection pooling or
prepared statement caching, but it can use Apache Commons DBCP for connection
pooling if it is provided on the classpath. Check out the
<a class="link" href="#ref_guide_dbsetup_builtin" title="1.&nbsp; Using the OpenJPA DataSource">DriverDataSource</a>
section, which describes how to use and configure Commons DBCP.
Also, you can manually plug in a third-party pooling datasource like
<a class="link" href="#ref_guide_integration_dbcp" title="2.&nbsp; Apache Commons DBCP">Apache Commons DBCP</a>,
included in the binary distribution and openjpa-all artifact, which may
drastically improve application performance.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Optimize database indexes
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
The default set of indexes created by OpenJPA's mapping tool may not always be
the most appropriate for your application. Manually setting indexes in your
mapping metadata or manually manipulating database indexes to include
frequently-queried fields (as well as dropping indexes on rarely-queried
fields) can yield significant performance benefits.
<p>
A database must do extra work on insert, update, and delete to maintain an
index. This extra work will benefit selects with WHERE clauses, which will
execute much faster when the terms in the WHERE clause are appropriately
indexed. So, for a read-mostly application, appropriate indexing will slow down
updates (which are rare) but greatly accelerate reads. This means that the
system as a whole will be faster, and also that the database will experience
less load, meaning that the system will be more scalable.
</p>
<p>
Bear in mind that over-indexing is a bad thing, both for scalability and
performance, especially for applications that perform lots of inserts, updates,
or deletes.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
JVM optimizations
</strong></span>
<p>
<span class="emphasis"><em>performance, reliability</em></span>
</p>
</td><td align="left" valign="top">
Manipulating various parameters of the Java Virtual Machine (such as hotspot
compilation modes and the maximum memory) can result in performance
improvements. For more details about optimizing the JVM execution environment,
please see <a class="ulink" href="http://www.oracle.com/technetwork/java/hotspotfaq-138619.html" target="_top">http://www.oracle.com/technetwork/java/hotspotfaq-138619.html</a>.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use the data cache
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
Using OpenJPA's <a class="link" href="#ref_guide_cache" title="1.&nbsp; Data Cache">data and query caching</a>
features can often result in a dramatic improvement in performance.
Additionally, these caches can significantly reduce the amount of load on
the database, increasing the scalability characteristics of your application.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Set <code class="literal">LargeTransaction</code> to true,
or set <code class="literal"> PopulateDataCache</code> to
false
</strong></span>
<p>
<span class="emphasis"><em>performance vs. scalability</em></span>
</p>
</td><td align="left" valign="top">
When using OpenJPA's <a class="link" href="#ref_guide_cache" title="1.&nbsp; Data Cache">data caching</a>
features in a transaction that will delete, modify, or create a very large
number of objects you can set <code class="literal">LargeTransaction</code> to true and
perform periodic flushes during your transaction to reduce its memory
requirements. See the Javadoc:
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
OpenJPAEntityManager.setTrackChangesByType</a>. Note that transactions in
large mode have to more aggressively flush items from the data cache.
<p>
If your transaction will visit objects that you know are very unlikely to be
accessed by other transactions, for example an exhaustive report run only once a
month, you can turn off population of the data cache so that the transaction
doesn't fill the entire data cache with objects that won't be accessed again.
Again, see the Javadoc:
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
OpenJPAEntityManager.setPopulateDataCache</a>
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Run the OpenJPA enhancer on your persistent classes,
either at build-time or deploy-time.
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability, memory footprint</em></span>
</p>
</td><td align="left" valign="top">
OpenJPA performs best when your persistent classes have been run through the
OpenJPA post-compilation bytecode enhancer. When dealing with enhanced classes,
OpenJPA can make a number of assumptions that reduce memory footprint and
accelerate persistent data access. When evaluating OpenJPA's performance,
build-time or deploy-time enhancement should be enabled. See
<a class="xref" href="#ref_guide_pc_enhance" title="2.&nbsp; Enhancement">Section&nbsp;2, &#8220;
Enhancement
&#8221;</a> for details.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Disable logging, performance tracking
</strong></span>
<p>
<span class="emphasis"><em>performance</em></span>
</p>
</td><td align="left" valign="top">
Developer options such as verbose logging and the JDBC performance tracker can
result in serious performance hits for your application. Before evaluating
OpenJPA's performance, these options should all be disabled.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Set <code class="literal">IgnoreChanges</code> to true, or
set <code class="literal">FlushBeforeQueries</code> to true
</strong></span>
<p>
<span class="emphasis"><em>performance vs. scalability</em></span>
</p>
</td><td align="left" valign="top">
When both the <a class="link" href="#openjpa.IgnoreChanges" title="5.37.&nbsp; openjpa.IgnoreChanges"><code class="literal">
openjpa.IgnoreChanges</code></a> and
<a class="link" href="#openjpa.FlushBeforeQueries" title="5.36.&nbsp; openjpa.FlushBeforeQueries"><code class="literal">openjpa.FlushBeforeQueries
</code></a> properties are set to false, OpenJPA needs to consider
in-memory dirty instances during queries. This can sometimes result in OpenJPA
needing to evaluate the entire extent objects in order to return the correct
query results, which can have drastic performance consequences. If it is
appropriate for your application, configuring <code class="literal">FlushBeforeQueries
</code> to automatically flush before queries involving dirty objects will
ensure that this never happens. Setting <code class="literal">IgnoreChanges</code> to
false will result in a small performance hit even if <code class="literal">FlushBeforeQueries
</code> is true, as incremental flushing is not as efficient overall as
delaying all flushing to a single operation during commit.
<p>
Setting <code class="literal">IgnoreChanges</code> to <code class="literal">true</code> will help
performance, since dirty objects can be ignored for queries, meaning that
incremental flushing or client-side processing is not necessary. It will also
improve scalability, since overall database server usage is diminished. On the
other hand, setting <code class="literal">IgnoreChanges</code> to <code class="literal">false</code>
will have a negative impact on scalability, even when using automatic flushing
before queries, since more operations will be performed on the database server.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Configure <code class="literal">openjpa.ConnectionRetainMode
</code> appropriately
</strong></span>
<p>
<span class="emphasis"><em>performance vs. scalability</em></span>
</p>
</td><td align="left" valign="top">
The <a class="link" href="#openjpa.ConnectionRetainMode" title="5.25.&nbsp; openjpa.ConnectionRetainMode"><code class="literal">ConnectionRetainMode
</code></a> configuration option controls when OpenJPA will obtain a
connection, and how long it will hold that connection. The optimal settings for
this option will vary considerably depending on the particular behavior of
your application. You may even benefit from using different retain modes for
different parts of your application.
<p>
The default setting of <code class="literal">on-demand</code> minimizes the amount of time
that OpenJPA holds onto a datastore connection. This is generally the best
option from a scalability standpoint, as database resources are held for a
minimal amount of time. However, if you are not using connection pooling, or
if your <code class="classname">DataSource</code> is not efficient at managing its
pool, then this default value could cause undesirable pool contention.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use flat inheritance
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability vs. disk space</em></span>
</p>
</td><td align="left" valign="top">
Mapping inheritance hierarchies to a single database table is faster for most
operations than other strategies employing multiple tables. If it is
appropriate for your application, you should use this strategy whenever
possible.
<p>
However, this strategy will require more disk space on the database side. Disk
space is relatively inexpensive, but if your object model is particularly large,
it can become a factor.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
High sequence increment
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
For applications that perform large bulk inserts, the retrieval of sequence
numbers can be a bottleneck. Increasing sequence allocation sizes can reduce or eliminate
this bottleneck. In some cases, implementing your own sequence factory can
further optimize sequence number retrieval.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use optimistic transactions
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
Using datastore transactions translates into pessimistic database row locking,
which can be a performance hit (depending on the database). If appropriate for
your application, optimistic transactions are typically faster than datastore
transactions.
<p>
Optimistic transactions provide the same transactional guarantees as datastore
transactions, except that you must handle a potential optimistic verification
exception at the end of a transaction instead of assuming that a transaction
will successfully complete. In many applications, it is unlikely that different
concurrent transactions will operate on the same set of data at the same time,
so optimistic verification increases the concurrency, and therefore both the
performance and scalability characteristics, of the application. A common
approach to handling optimistic verification exceptions is to simply present the
end user with the fact that concurrent modifications happened, and require that
the user redo any work.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use query aggregates and projections
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
Using aggregates to compute reporting data on the database server can
drastically speed up queries. Similarly, using projections when you are
interested in specific object fields or relations rather than the entire object
state can reduce the amount of data OpenJPA must transfer from the database to
your application.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Always close resources
</strong></span>
<p>
<span class="emphasis"><em>scalability</em></span>
</p>
</td><td align="left" valign="top">
<p>
Under certain settings, <code class="classname"> EntityManager</code> s, OpenJPA
<code class="classname">Extent</code> iterators, and <code class="classname">Query</code>
results may be backed by resources in the database.
</p>
<p>
For example, if you have configured OpenJPA to use scrollable cursors and lazy
object instantiation by default, each query result will hold open a <code class="classname">
ResultSet</code> object, which, in turn, will hold open a <code class="classname">
Statement</code> object (preventing it from being re-used). Garbage
collection will clean up these resources, so it is never necessary to explicitly
close them, but it is always faster if it is done at the application level.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use detached state managers
</strong></span>
<p>
<span class="emphasis"><em>performance</em></span>
</p>
</td><td align="left" valign="top">
<p>
Attaching and even persisting instances can be more efficient when your detached
objects use detached state managers. By default, OpenJPA does not use detached
state managers when serializing an instance across tiers. See
<a class="xref" href="#ref_guide_detach_graph" title="1.3.&nbsp; Defining the Detached Object Graph">Section&nbsp;1.3, &#8220;
Defining the Detached Object Graph
&#8221;</a> for how to force OpenJPA to use
detached state managers across tiers, and for other options for more efficient
attachment.
</p>
<p>
The downside of using a detached state manager across tiers is that your
enhanced persistent classes and the OpenJPA libraries must be available on the
client tier.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Utilize the <code class="classname">EntityManager</code>
cache
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
When possible and appropriate, re-using <code class="classname">EntityManager</code>s
and setting the <a class="link" href="#openjpa.RetainState" title="5.63.&nbsp; openjpa.RetainState"><code class="literal">RetainState
</code></a> configuration option to <code class="literal">true</code> may result in
significant performance gains, since the <code class="classname">EntityManager</code>'s
built-in object cache will be used.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Enable multithreaded operation only when necessary
</strong></span>
<p>
<span class="emphasis"><em>performance</em></span>
</p>
</td><td align="left" valign="top">
OpenJPA respects the <a class="link" href="#openjpa.Multithreaded" title="5.50.&nbsp; openjpa.Multithreaded"><code class="literal">
openjpa.Multithreaded</code></a> option in that it does not impose as
much synchronization overhead for applications that do not set this value to
<code class="literal">true</code>. If your application is guaranteed to only use
single-threaded access to OpenJPA resources and persistent objects, leaving
this option as <code class="literal">false</code> will reduce synchronization overhead,
and may result in a modest performance increase.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Enable large data set handling
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
If you execute queries that return large numbers of objects or have relations
(collections or maps) that are large, and if you often only access parts of
these data sets, enabling <a class="link" href="#ref_guide_dbsetup_lrs" title="10.&nbsp; Large Result Sets">large result
set handling</a> where appropriate can dramatically speed up your
application, since OpenJPA will bring the data sets into memory from the
database only as necessary.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Disable large data set handling
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
If you have enabled scrollable result sets and on-demand loading but you do not
require it, consider disabling it again. Some JDBC drivers and databases
(SQL Server for example) are much slower when used with scrolling result sets.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use the <code class="classname">DynamicSchemaFactory</code>
</strong></span>
<p>
<span class="emphasis"><em>performance, validation</em></span>
</p>
</td><td align="left" valign="top">
If you are using an <a class="link" href="#openjpa.jdbc.SchemaFactory" title="6.13.&nbsp; openjpa.jdbc.SchemaFactory"><code class="literal">
openjpa.jdbc.SchemaFactory</code></a> setting of something other than
the default of <code class="literal">dynamic</code>, consider switching back. While other
factories can ensure that object-relational mapping information is valid when
a persistent class is first used, this can be a slow process. Though the
validation is only performed once for each class, switching back to the
<code class="classname">DynamicSchemaFactory</code> can reduce the warm-up time for
your application.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Do not use XA transactions
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
<a class="link" href="#ref_guide_enterprise_xa" title="3.&nbsp; XA Transactions">XA transactions</a> can be orders of
magnitude slower than standard transactions. Unless distributed transaction
functionality is required by your application, use standard transactions.
<p>
Recall that XA transactions are distinct from managed transactions - managed
transaction services such as that provided by EJB declarative transactions can
be used both with XA and non-XA transactions. XA transactions should only be
used when a given business transaction involves multiple different transactional
resources (an Oracle database and an IBM transactional message queue, for
example).
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use <code class="classname">Set</code>s instead of
<code class="classname">List/Collection</code>s
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
There is a small amount of extra overhead for OpenJPA to maintain collections
where each element is not guaranteed to be unique. If your application does
not require duplicates for a collection, you should always declare your
fields to be of type <code class="classname">Set, SortedSet, HashSet,</code> or
<code class="classname">TreeSet</code>.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use query parameters instead of encoding search
data in filter strings
</strong></span>
<p>
<span class="emphasis"><em>performance</em></span>
</p>
</td><td align="left" valign="top">
If your queries depend on parameter data only known at runtime, you should use
query parameters rather than dynamically building different query strings.
OpenJPA performs aggressive caching of query compilation data, and the
effectiveness of this cache is diminished if multiple query filters are used
where a single one could have sufficed.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Tune your fetch groups appropriately
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
The <a class="link" href="#ref_guide_fetch" title="7.&nbsp; Fetch Groups">fetch groups</a> used when loading an
object control how much data is eagerly loaded, and by extension, which fields
must be lazily loaded at a future time. The ideal fetch group configuration
loads all the data that is needed in one fetch, and no extra fields - this
minimizes both the amount of data transferred from the database, and the
number of trips to the database.
<p>
If extra fields are specified in the fetch groups (in particular, large fields
such as binary data, or relations to other persistence-capable objects), then
network overhead (for the extra data) and database processing (for any necessary
additional joins) will hurt your application's performance. If too few fields
are specified in the fetch groups, then OpenJPA will have to make additional
trips to the database to load additional fields as necessary.
</p>
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Use eager fetching
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
Using <a class="link" href="#ref_guide_perfpack_eager" title="8.&nbsp; Eager Fetching">eager fetching</a> when
loading subclass data or traversing relations for each instance in a large
collection of results can speed up data loading by orders of magnitude.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Disable BrokerImpl finalization
</strong></span>
<p>
<span class="emphasis"><em>performance, scalability</em></span>
</p>
</td><td align="left" valign="top">
Outside of a Java EE application server or other JPA persistence container,
OpenJPA's EntityManagers use finalizers to ensure that resources
get cleaned up. If you are properly managing your resources, this finalization
is not necessary, and will introduce unneeded synchronization, leading to
scalability problems. You can disable this protective behavior by setting the
<code class="literal">openjpa.BrokerImpl</code> property to
<code class="literal">non-finalizing</code>. See <a class="xref" href="#ref_guide_runtime_broker_finalization" title="1.1.&nbsp; Broker Finalization">Section&nbsp;1.1, &#8220;
Broker Finalization
&#8221;</a> for details.
</td></tr><tr><td align="left" valign="top">
<span class="bold"><strong>
Preload MetaDataRepository
</strong></span>
<p>
<span class="emphasis"><em>scalability</em></span>
</p>
</td><td align="left" valign="top">
By default, the MetaDataRepository is lazily loaded which means that fair amounts of locking
is used to ensure that metadata is processed properly. Enabling preloading allows OpenJPA to
load metadata upfront and remove locking. See <a class="xref" href="#ref_guide_meta_repository" title="2.&nbsp;Metadata Repository">Section&nbsp;2, &#8220;Metadata Repository&#8221;</a> for details.
</td></tr></tbody></table>
</div></div><br class="table-break">
</div>
<div class="chapter" id="ref_guide_instrumentation"><div class="titlepage"><div><div><h2 class="title">Chapter&nbsp;16.&nbsp;
Instrumentation
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#ref_guide_instrumentation_config">1.
Configuration
</a></span></dt><dd><dl><dt><span class="section"><a href="#ref_guide_instrumentation_config_jmx">1.1.
JMX Platform MBean Enablement
</a></span></dt></dl></dd><dt><span class="section"><a href="#ref_guide_instrumentation_custom">2.
Custom Providers and Instruments
</a></span></dt></dl></div>
<a class="indexterm" name="d5e17569"></a>
<p>
OpenJPA provides the ability to instrument various aspects of runtime
operation. Instrumentation involves an instrumentation provider for base instrumentation
capabilities and instruments for instrumenting various aspects of OpenJPA. OpenJPA
includes a default instrumentation provider for JMX Platform MBeans. MBean-based instruments
are provided for the data cache, query cache, and query SQL cache. When enabled,
JMX-based remote monitoring tools such as
<a class="ulink" href="http://download.oracle.com/javase/6/docs/technotes/tools/share/jconsole.html" target="_top">
<code class="classname">JConsole</code></a> can be used to monitor various
metrics tracked by OpenJPA's caches by accessing MBeans registered under domain
<code class="classname">org.apache.openjpa</code>. Additionally, custom applications can gather metrics by using the
JMX API to query OpenJPA's MBeans. The <code class="classname">openjpa-integration-jmx</code>
integration module contains an example of how to access the cache MBeans within program code.
</p>
<div class="section" id="ref_guide_instrumentation_config"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Configuration
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#ref_guide_instrumentation_config_jmx">1.1.
JMX Platform MBean Enablement
</a></span></dt></dl></div>
<a class="indexterm" name="d5e17578"></a>
<p>
Instrumentation is enabled using the <a class="link" href="#openjpa.Instrumentation" title="5.40.&nbsp; openjpa.Instrumentation"><code class="literal">openjpa.Instrumentation</code> </a>
configuration property. The base value is the instrumentation provider. The
alias "jmx" enables the JMX Platform MBean provider. Instruments are specified
on the <code class="literal">Instrument</code> attribute of the provider. Multiple instruments can be specified
by enclosing the value in single quotes and specifying each instrument or instrument
alias as a comma separated list. For example:
</p>
<pre class="programlisting">
&lt;!-- Enable caches and cache statistics --&gt;
&lt;property name="openjpa.DataCache" value="true(EnableStatistics=true)"/&gt;
&lt;property name="openjpa.QueryCache" value="true(EnableStatistics=true)"/&gt;
&lt;property name="openjpa.jdbc.QuerySQLCache" value="true(EnableStatistics=true)"/&gt;
&lt;!-- Enable jmx provider and instruments for Data, Query, and QuerySQL caches --&gt;
&lt;property name="openjpa.Instrumentation" value="jmx(Instrument='DataCache,QueryCache,QuerySQLCache')"/&gt;
</pre>
<div class="section" id="ref_guide_instrumentation_config_jmx"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
JMX Platform MBean Enablement
</h3></div></div></div>
<a class="indexterm" name="d5e17587"></a>
<p>
The built-in JMX Platform MBean provider can be used to monitor OpenJPA
runtime information out-of-band. This provider is based upon the Platform MBean support included
in the JDK. The JDK provides options for enabling secure connectivity and authentication.
These options require additional configuration options and may require encryption
keys to be installed on the local and remote systems. To enable simple, non-secure, non-authenticated
monitoring of your application, specify the -Dcom.sun.management.jmxremote.authenticate=false and
-Dcom.sun.management.jmxremote.ssl=false directives on the java command line invocation. To enable
remote instrumentation on a specific port, specify which port to use on the directive
-Dcom.sun.management.jmxremote.port=&lt;port&gt;.
For example:
</p><pre class="programlisting">
java -cp openjpa-all-2.2.0.jar:myApplication.jar -Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=8888 com.my.app.Main
</pre><p>
</p>
<p>
Additional information regarding the use and configuration of JMX Platform MBeans
can be found in the
<a class="ulink" href="http://download.oracle.com/javase/6/docs/technotes/guides/jmx/overview/JMXoverviewTOC.html" target="_top">
<code class="literal">Java Management Extensions (JMX) Technology Overview</code></a>.
</p>
</div>
</div>
<div class="section" id="ref_guide_instrumentation_custom"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Custom Providers and Instruments
</h2></div></div></div>
<a class="indexterm" name="d5e17597"></a>
<p>
OpenJPA includes built-in support for a JMX Platform MBean provider, but a custom instrumentation
providers can be created by implementing the
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/instrumentation/InstrumentationProvider.html" target="_top">
<code class="classname">InstrumentationProvider</code></a> interface or more simply by extending
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/instrumentation/AbstractInstrumentationProvider.html" target="_top">
<code class="classname">AbstractInstrumentationProvider</code></a>. To use the custom instrumentation provider,
include the class in your classpath and specify the class name as the base value on the
<a class="link" href="#openjpa.Instrumentation" title="5.40.&nbsp; openjpa.Instrumentation"><code class="literal">openjpa.Instrumentation</code></a> configuration property.
</p>
<p>
OpenJPA includes instruments for various caches, but you can also create your own instruments. To
create a custom instrument you need to implement the
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/instrumentation/Instrument.html" target="_top">
<code class="classname">Instrument</code></a> interface or more simply extend
<a class="ulink" href="../../apidocs/org/apache/openjpa/lib/instrumentation/AbstractInstrument.html" target="_top">
<code class="classname">AbstractInstrument</code></a>. If you are building a Platform MBean JMX-based
instrument this effort can be simplified by extending
<a class="ulink" href="../../apidocs/org/apache/openjpa/instrumentation/jmx/JMXInstrument.html" target="_top">
<code class="classname">JMXInstrument</code></a>. If you create your own custom
provider, class name aliases can be registered within the provider to simplify configuration. For example,
the instrument <code class="classname">com.my.app.MySQLInstrument</code> could be aliased as
<code class="classname">MySQLInstrument</code> within custom provider
<code class="classname">com.my.app.InstrumentationProvider</code>.
</p>
<p>
OpenJPA provides the ability to plug in custom instruments and gives instruments direct access to the
configuration, but it is up to the creator of the instrument to add the internal monitoring. This often
requires modifying or extending base OpenJPA classes (such as the Broker) or using a byte-code weaving
tool such as AspectJ to produce aspect-based instruments.
</p>
<p>
Here is an example of how a custom instrumentation provider could be enabled with an instrument class
aliased by the provider as <code class="classname">MySQLInstrument</code>.
</p>
<pre class="programlisting">
&lt;!-- Enable custom provider and instrument --&gt;
&lt;property name="openjpa.Instrumentation" value="com.my.app.InstrumentationProvider(Instrument='MySQLInstrument')"/&gt;
</pre>
</div>
</div>
</div>
<div class="part" id="appendices"><div class="titlepage"><div><div><h1 class="title">Part&nbsp;4.&nbsp;Appendices</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="appendix"><a href="#jpa_resources">1.
JPA Resources
</a></span></dt><dt><span class="appendix"><a href="#supported_databases">2.
Supported Databases
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbappendix">1.
Overview
</a></span></dt><dt><span class="section"><a href="#dbsupport">2.
Verified Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbcompatible">3.
Compatible Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbunverified">4.
Unverified Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbsupport_derby">5.
Apache Derby
</a></span></dt><dt><span class="section"><a href="#dbsupport_interbase">6.
Borland Interbase
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_interbase_issues">6.1.
Known issues with Interbase
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_jdatastore">7.
JDataStore
</a></span></dt><dt><span class="section"><a href="#dbsupport_db2">8.
IBM DB2
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_db2_issues">8.1.
Known issues with DB2
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_empress">9.
Empress
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_empress_issues">9.1.
Known issues with Empress
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_h2">10.
H2 Database Engine
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_h2_issues">10.1.
Known issues with H2 Database Engine
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_hypersonic">11.
Hypersonic
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_hypersonic_issues">11.1.
Known issues with Hypersonic
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_firebird">12.
Firebird
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_firebird_issues">12.1.
Known issues with Firebird
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_informix">13.
Informix
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_informix_issues">13.1.
Known issues with Informix
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_ingres">14.
Ingres Database
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_ingres_issues">14.1.
Known issues with Ingres
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_intersystems_cache">15.
InterSystems Cache
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_intersystems_cache_issues">15.1.
Known issues with InterSystems Cache
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_access">16.
Microsoft Access
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_access_issues">16.1.
Known issues with Microsoft Access
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_sqlserver">17.
Microsoft SQL Server
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_sqlserver_issues">17.1.
Known issues with SQL Server
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_foxpro">18.
Microsoft FoxPro
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_foxpro_issues">18.1.
Known issues with Microsoft FoxPro
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_mysql">19.
MySQL
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_mysql_query_hints">19.1.
Using Query Hints with MySQL
</a></span></dt><dt><span class="section"><a href="#dbsupport_mysql_issues">19.2.
Known issues with MySQL
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_mariadb">20.
MariaDB
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_mariadb_issues">20.1.
Known issues with MariaDB
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_oracle">21.
Oracle
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_oracle_query_hints">21.1.
Using Query Hints with Oracle
</a></span></dt><dt><span class="section"><a href="#dbsupport_oracle_issues">21.2.
Known issues with Oracle
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_pointbase">22.
Pointbase
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_pointbase_issues">22.1.
Known issues with Pointbase
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_postgresql">23.
PostgreSQL
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_postgresql_issues">23.1.
Known issues with PostgreSQL
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_soliddb">24.
IBM solidDB
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_soliddb_table_types">24.1.
M-type tables vs. D-type tables
</a></span></dt><dt><span class="section"><a href="#dbsupport_soliddb_concurrency_control">24.2.
Concurrency control mechanism
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_sybase">25.
Sybase Adaptive Server
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_sybase_issues">25.1.
Known issues with Sybase
</a></span></dt></dl></dd></dl></dd><dt><span class="appendix"><a href="#migration_considerations">3.
Migration Considerations
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.0">1.
OpenJPA 2.0.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.0_incompatibilities">1.1.
Incompatibilities
</a></span></dt><dd><dl><dt><span class="section"><a href="#getProperties">1.1.1.
getProperties()
</a></span></dt><dt><span class="section"><a href="#migration_detach_behavior">1.1.2.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#private_persistent_properties">1.1.3.
Use of private persistent properties
</a></span></dt><dt><span class="section"><a href="#setParameter">1.1.4.
Query.setParameter()
</a></span></dt><dt><span class="section"><a href="#serialization">1.1.5.
Serialization of Entities
</a></span></dt><dt><span class="section"><a href="#QuerySQLCache">1.1.6.
openjpa.jdbc.QuerySQLCache
</a></span></dt></dl></dd><dt><span class="section"><a href="#Disabling AutoOff Collection Tracking">1.2.
Disabling AutoOff Collection Tracking
</a></span></dt><dt><span class="section"><a href="#internal_differences">1.3.
Internal Behavioral Differences
</a></span></dt><dd><dl><dt><span class="section"><a href="#prePostUpdate">1.3.1.
PreUpdate/PostUpdate Life Cycle Callbacks
</a></span></dt><dt><span class="section"><a href="#createemf">1.3.2.
createEntityManagerFactory Exceptions
</a></span></dt><dt><span class="section"><a href="#querycache">1.3.3.
openjpa.QueryCache default
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_2.2">2.
OpenJPA 2.2.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.2_incompatibilities">2.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.2_allocationSize">2.1.1.
allocationSize Property of Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_metamodelArrays">2.1.2.
MetaModel Attributes for Arrays
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_SupportsSetClob">2.1.3.
supportsSetClob Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_UseNativeSequenceCache">2.1.4.
useNativeSequenceCache Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_cascadePersist">2.1.5.
Cascade persist behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_LifecycleEventManager">2.1.6.
Life Cycle Event Manager Callback Behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_sharedCacheMode">2.1.7.
shared-cache-mode Property
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_2.3">3.
OpenJPA 2.3.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.3_incompatibilities">3.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.3_MappingTool">3.1.1.
MappingTool Behavior for DB2 and Derby
</a></span></dt><dt><span class="section"><a href="#jpa_2.3_RequiresSearchStringEscapeForLike">3.1.2.
RequiresSearchStringEscapeForLike DBDictionary Property
</a></span></dt><dt><span class="section"><a href="#ReturnNullOnEmptyAggregateResult">3.1.3.
Return value of aggregate functions in SELECT clause
</a></span></dt></dl></dd></dl></dd></dl></dd></dl></div>
<div class="appendix" id="jpa_resources"><div class="titlepage"><div><div><h2 class="title">Appendix&nbsp;1.&nbsp;
JPA Resources
</h2></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
<a class="ulink" href="http://www.jcp.org/en/jsr/detail?id=317" target="_top">
Java Persistence 2.0 page</a>
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="http://jcp.org/en/jsr/detail?id=318" target="_top">Enterprise JavaBeans 3.1 page</a>
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="http://download.oracle.com/javaee/6/api/index.html" target="_top">
javax.persistence Javadoc</a>
</p>
</li><li class="listitem">
<p>
<a class="ulink" href="../../apidocs/index.html" target="_top">OpenJPA Javadoc</a>
</p>
</li></ul></div>
</div>
<div class="appendix" id="supported_databases"><div class="titlepage"><div><div><h2 class="title">Appendix&nbsp;2.&nbsp;
Supported Databases
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#dbappendix">1.
Overview
</a></span></dt><dt><span class="section"><a href="#dbsupport">2.
Verified Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbcompatible">3.
Compatible Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbunverified">4.
Unverified Database Matrix
</a></span></dt><dt><span class="section"><a href="#dbsupport_derby">5.
Apache Derby
</a></span></dt><dt><span class="section"><a href="#dbsupport_interbase">6.
Borland Interbase
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_interbase_issues">6.1.
Known issues with Interbase
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_jdatastore">7.
JDataStore
</a></span></dt><dt><span class="section"><a href="#dbsupport_db2">8.
IBM DB2
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_db2_issues">8.1.
Known issues with DB2
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_empress">9.
Empress
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_empress_issues">9.1.
Known issues with Empress
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_h2">10.
H2 Database Engine
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_h2_issues">10.1.
Known issues with H2 Database Engine
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_hypersonic">11.
Hypersonic
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_hypersonic_issues">11.1.
Known issues with Hypersonic
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_firebird">12.
Firebird
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_firebird_issues">12.1.
Known issues with Firebird
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_informix">13.
Informix
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_informix_issues">13.1.
Known issues with Informix
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_ingres">14.
Ingres Database
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_ingres_issues">14.1.
Known issues with Ingres
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_intersystems_cache">15.
InterSystems Cache
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_intersystems_cache_issues">15.1.
Known issues with InterSystems Cache
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_access">16.
Microsoft Access
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_access_issues">16.1.
Known issues with Microsoft Access
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_sqlserver">17.
Microsoft SQL Server
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_sqlserver_issues">17.1.
Known issues with SQL Server
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_foxpro">18.
Microsoft FoxPro
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_foxpro_issues">18.1.
Known issues with Microsoft FoxPro
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_mysql">19.
MySQL
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_mysql_query_hints">19.1.
Using Query Hints with MySQL
</a></span></dt><dt><span class="section"><a href="#dbsupport_mysql_issues">19.2.
Known issues with MySQL
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_mariadb">20.
MariaDB
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_mariadb_issues">20.1.
Known issues with MariaDB
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_oracle">21.
Oracle
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_oracle_query_hints">21.1.
Using Query Hints with Oracle
</a></span></dt><dt><span class="section"><a href="#dbsupport_oracle_issues">21.2.
Known issues with Oracle
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_pointbase">22.
Pointbase
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_pointbase_issues">22.1.
Known issues with Pointbase
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_postgresql">23.
PostgreSQL
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_postgresql_issues">23.1.
Known issues with PostgreSQL
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_soliddb">24.
IBM solidDB
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_soliddb_table_types">24.1.
M-type tables vs. D-type tables
</a></span></dt><dt><span class="section"><a href="#dbsupport_soliddb_concurrency_control">24.2.
Concurrency control mechanism
</a></span></dt></dl></dd><dt><span class="section"><a href="#dbsupport_sybase">25.
Sybase Adaptive Server
</a></span></dt><dd><dl><dt><span class="section"><a href="#dbsupport_sybase_issues">25.1.
Known issues with Sybase
</a></span></dt></dl></dd></dl></div>
<div class="section" id="dbappendix"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
Overview
</h2></div></div></div>
<p>
The following appendix covers the database and JDBC driver versions that are
known to work with OpenJPA, along with any database specific configuration
parameters, known issues or limitations.
The <a class="link" href="#dbsupport" title="2.&nbsp; Verified Database Matrix">Verified Database Matrix</a>, contains the
list of databases and drivers that were tested extensively against this
release of OpenJPA, while the <a class="link" href="#dbcompatible" title="3.&nbsp; Compatible Database Matrix">Compatible Database
Matrix</a> contains the list of databases and drivers that were tested
against prior releases or by OpenJPA users and may not support every feature
of this release.
The Unverified Database Matrix contains a
list of databases which have been reported to work, but have not been tested by
the development team.
</p>
</div>
<div class="section" id="dbsupport"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
Verified Database Matrix
</h2></div></div></div>
<p>
Following is a table of the supported database and JDBC driver versions that
have been verified against this version of OpenJPA. For the list of other
databases and drivers that were tested in prior releases or by other OpenJPA
users, but may not support every feature of this release, please refer to the
<a class="link" href="#dbcompatible" title="3.&nbsp; Compatible Database Matrix">Compatible Database Matrix</a> section.
</p>
<div class="table" id="d5e17649"><p class="title"><b>Table&nbsp;2.1.&nbsp;
Supported Databases and JDBC Drivers
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Supported Databases and JDBC Drivers&#xA; " border="1"><colgroup><col align="left" class="dbname"><col align="left" class="dbversion"><col align="left" class="drivname"><col align="left" class="drivversion"></colgroup><thead><tr><th align="left">
Database Name
</th><th align="left">
Database Version
</th><th align="left">
JDBC Driver Name
</th><th align="left">
JDBC Driver Version
</th></tr></thead><tbody><tr><td align="left">
<a class="link" href="#dbsupport_derby" title="5.&nbsp; Apache Derby">Apache Derby</a>
</td><td align="left">
10.2.2.0, 10.3.3.0, 10.4.2.0, 10.5.3.0, 10.8.2.2, 10.14.2.0
</td><td align="left">
Apache Derby Embedded JDBC Driver
</td><td align="left">
Same as Database Version
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_db2" title="8.&nbsp; IBM DB2">IBM DB2</a>
</td><td align="left">
8.1, 8.2, 9.1, 9.5, 9.7
</td><td align="left">
IBM DB2 JDBC Universal Driver
</td><td align="left">
3.50.152
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_informix" title="13.&nbsp; Informix">IBM Informix Dynamic Server</a>
</td><td align="left">
10.00xC6, 11.10xC1, 11.5xC1
</td><td align="left">
Informix JDBC driver
</td><td align="left">
3.00 JC3, 3.10 JC1, 3.50 JC1
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_sqlserver" title="17.&nbsp; Microsoft SQL Server">Microsoft SQL Server</a>
</td><td align="left">
2005 (9.00), 2008 (10.00), 2017
</td><td align="left">
Microsoft SQL Server JDBC Driver
</td><td align="left">
1.2 or 2.0
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_mysql" title="19.&nbsp; MySQL">MySQL</a>
</td><td align="left">
5.0.26, 5.1.6, 5.7
</td><td align="left">
MySQL Driver
</td><td align="left">
5.1.6, 5.1.47
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_oracle" title="21.&nbsp; Oracle">Oracle</a>
</td><td align="left">
10g (10.1, 10.2), 11g (11.1, 11.2), 12c, 18c
</td><td align="left">
Oracle JDBC driver
</td><td align="left">
11.2.0.1, 11.2.0.4
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_postgresql" title="23.&nbsp; PostgreSQL">PostgreSQL</a>
</td><td align="left">
8.3.5, 8.4, 9, 11
</td><td align="left">
PostgreSQL Native Driver
</td><td align="left">
8.3 JDBC3 (build 603), 8.4 JDBC3 (build 701), 42.2.5
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_soliddb" title="24.&nbsp; IBM solidDB">IBM solidDB</a>
</td><td align="left">
6.5.0.0
</td><td align="left">
solidDB JDBC Driver
</td><td align="left">
2.0
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_sybase" title="25.&nbsp; Sybase Adaptive Server">Sybase Adaptive Server Enterprise</a>
</td><td align="left">
12.5, 15.0
</td><td align="left">
jConnect
</td><td align="left">
5.5, 6.0
</td></tr></tbody></table>
</div></div><br class="table-break">
</div>
<div class="section" id="dbcompatible"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
Compatible Database Matrix
</h2></div></div></div>
<p>
Following is a table of the database and JDBC driver versions that are
compatible with OpenJPA. Some of these databases have been tested against this
version of OpenJPA, while others were added or tested in prior releases and
may not support all of the new features of this release. For the list of
databases that have been fully tested against this release, please refer to the
<a class="link" href="#dbsupport" title="2.&nbsp; Verified Database Matrix">Verified Database Matrix</a> section.
</p>
<div class="table" id="d5e17721"><p class="title"><b>Table&nbsp;2.2.&nbsp;
Compatible Databases and JDBC Drivers
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Compatible Databases and JDBC Drivers&#xA; " border="1"><colgroup><col align="left" class="dbname"><col align="left" class="dbversion"><col align="left" class="drivname"><col align="left" class="drivversion"></colgroup><thead><tr><th align="left">
Database Name
</th><th align="left">
Database Version
</th><th align="left">
JDBC Driver Name
</th><th align="left">
JDBC Driver Version
</th></tr></thead><tbody><tr><td align="left">
<a class="link" href="#dbsupport_derby" title="5.&nbsp; Apache Derby">Apache Derby</a>
</td><td align="left">
10.1.2.1
</td><td align="left">
Apache Derby Embedded JDBC Driver
</td><td align="left">
10.1.2.1
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_interbase" title="6.&nbsp; Borland Interbase">Borland Interbase</a>
</td><td align="left">
7.1.0.202
</td><td align="left">
Interclient
</td><td align="left">
4.5.1
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_jdatastore" title="7.&nbsp; JDataStore">Borland JDataStore</a>
</td><td align="left">
6.0
</td><td align="left">
Borland JDataStore
</td><td align="left">
6.0
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_db2" title="8.&nbsp; IBM DB2">DB2</a>
</td><td align="left">
8.1
</td><td align="left">
IBM DB2 JDBC Universal Driver
</td><td align="left">
1.0.581, 2.10.72
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_empress" title="9.&nbsp; Empress">Empress</a>
</td><td align="left">
8.62
</td><td align="left">
Empress Category 2 JDBC Driver
</td><td align="left">
8.62
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_firebird" title="12.&nbsp; Firebird">Firebird</a>
</td><td align="left">
1.5, 2.0, 2.1
</td><td align="left">
JayBird JCA/JDBC driver
</td><td align="left">
2.1.6
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_h2" title="10.&nbsp; H2 Database Engine">H2 Database Engine</a>
</td><td align="left">
1.1.118
</td><td align="left">
H2
</td><td align="left">
Same as Database Version
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_hypersonic" title="11.&nbsp; Hypersonic">Hypersonic Database Engine</a>
</td><td align="left">
1.8.0, 2.0.1 RC2
</td><td align="left">
Hypersonic
</td><td align="left">
Same as Database Version
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_informix" title="13.&nbsp; Informix">Informix Dynamic Server</a>
</td><td align="left">
9.30.UC10, 9.4xC7
</td><td align="left">
Informix JDBC driver
</td><td align="left">
2.21.JC2, 3.00 JC3, 3.10 JC1
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_ingres" title="14.&nbsp; Ingres Database">Ingres Database</a>
</td><td align="left">
9.2
</td><td align="left">
Ingres JDBC Driver
</td><td align="left">
9.2-3.4.8
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_intersystems_cache" title="15.&nbsp; InterSystems Cache">InterSystems Cache</a>
</td><td align="left">
5.0
</td><td align="left">
Cache JDBC Driver
</td><td align="left">
5.0
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_access" title="16.&nbsp; Microsoft Access">Microsoft Access</a>
</td><td align="left">
9.0 (a.k.a. "2000")
</td><td align="left">
DataDirect SequeLink
</td><td align="left">
5.4.0038
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_sqlserver" title="17.&nbsp; Microsoft SQL Server">Microsoft SQL Server</a>
</td><td align="left">
2000 (8.00)
</td><td align="left">
Microsoft SQL Server JDBC Driver
</td><td align="left">
1.2
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_foxpro" title="18.&nbsp; Microsoft FoxPro">Microsoft Visual FoxPro</a>
</td><td align="left">
7.0
</td><td align="left">
DataDirect SequeLink
</td><td align="left">
5.4.0038
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_mysql" title="19.&nbsp; MySQL">MySQL</a>
</td><td align="left">
3.23.43-log
</td><td align="left">
MySQL Driver
</td><td align="left">
3.0.14
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_oracle" title="21.&nbsp; Oracle">Oracle</a>
</td><td align="left">
8.1, 9.2
</td><td align="left">
Oracle JDBC driver
</td><td align="left">
10.2.0.1
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_pointbase" title="22.&nbsp; Pointbase">Pointbase</a>
</td><td align="left">
4.4
</td><td align="left">
Pointbase JDBC driver
</td><td align="left">
4.4 (4.4)
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_postgresql" title="23.&nbsp; PostgreSQL">PostgreSQL</a>
</td><td align="left">
7.2.1, 8.1.5
</td><td align="left">
PostgreSQL Native Driver
</td><td align="left">
8.1
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_soliddb" title="24.&nbsp; IBM solidDB">IBM solidDB</a>
</td><td align="left">
6.5.0.0
</td><td align="left">
solidDB JDBC Driver
</td><td align="left">
2.0
</td></tr><tr><td align="left">
<a class="link" href="#dbsupport_sybase" title="25.&nbsp; Sybase Adaptive Server">Sybase Adaptive Server Enterprise</a>
</td><td align="left">
12.5
</td><td align="left">
jConnect
</td><td align="left">
5.5 (5.5)
</td></tr></tbody></table>
</div></div><br class="table-break">
</div>
<div class="section" id="dbunverified"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.&nbsp;
Unverified Database Matrix
</h2></div></div></div>
<p>
Following is a table of the database and JDBC driver versions that have been reported
to work with OpenJPA by the community but have not been verified by the development
team. In some cases this is a question of availability since the developers may not
be able to obtain a license to test, or have experience configuring these databases.
For the list of databases that have been fully tested against this release, please
refer to the <a class="link" href="#dbsupport" title="2.&nbsp; Verified Database Matrix">Verified Database Matrix</a> section.
</p>
<div class="table" id="d5e17859"><p class="title"><b>Table&nbsp;2.3.&nbsp;
Unverified Databases and JDBC Drivers
</b></p><div class="table-contents">
<table class="table" summary="&#xA; Unverified Databases and JDBC Drivers&#xA; " border="1"><colgroup><col align="left" class="dbname"><col align="left" class="dbversion"><col align="left" class="drivname"><col align="left" class="drivversion"></colgroup><thead><tr><th align="left">
Database Name
</th><th align="left">
Database Version
</th><th align="left">
JDBC Driver Name
</th><th align="left">
JDBC Driver Version
</th></tr></thead><tbody><tr><td align="left">
SAP MaxDB
</td><td align="left">
</td><td align="left">
</td><td align="left">
</td></tr></tbody></table>
</div></div><br class="table-break">
</div>
<div class="section" id="dbsupport_derby"><div class="titlepage"><div><div><h2 class="title" style="clear: both">5.&nbsp;
Apache Derby
</h2></div></div></div>
<div class="example" id="example_props_derby"><p class="title"><b>Example&nbsp;2.1.&nbsp;
Example properties for Derby
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: org.apache.derby.jdbc.EmbeddedDriver
openjpa.ConnectionURL: jdbc:derby:DB_NAME;create=true
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="dbsupport_interbase"><div class="titlepage"><div><div><h2 class="title" style="clear: both">6.&nbsp;
Borland Interbase
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_interbase_issues">6.1.
Known issues with Interbase
</a></span></dt></dl></div>
<div class="example" id="example_props_interbase"><p class="title"><b>Example&nbsp;2.2.&nbsp;
Example properties for Interbase
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: interbase.interclient.Driver
openjpa.ConnectionURL: jdbc:interbase://SERVER_NAME:SERVER_PORT/DB_PATH
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_interbase_issues"><div class="titlepage"><div><div><h3 class="title">6.1.&nbsp;
Known issues with Interbase
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Interbase does not support record locking, so
datastore transactions cannot use the pessimistic lock manager.
</p>
</li><li class="listitem">
<p>
Interbase does not support the <code class="literal">LOWER</code>,
<code class="literal">SUBSTRING</code>, or <code class="literal">INSTR</code> SQL functions.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_jdatastore"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.&nbsp;
JDataStore
</h2></div></div></div>
<div class="example" id="example_props_jdatastore"><p class="title"><b>Example&nbsp;2.3.&nbsp;
Example properties for JDataStore
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.borland.datastore.jdbc.DataStoreDriver
openjpa.ConnectionURL: jdbc:borland:dslocal:db-jdatastore.jds;create=true
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="dbsupport_db2"><div class="titlepage"><div><div><h2 class="title" style="clear: both">8.&nbsp;
IBM DB2
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_db2_issues">8.1.
Known issues with DB2
</a></span></dt></dl></div>
<div class="example" id="example_props_db2"><p class="title"><b>Example&nbsp;2.4.&nbsp;
Example properties for IBM DB2
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.ibm.db2.jcc.DB2Driver
openjpa.ConnectionURL: jdbc:db2://SERVER_NAME:SERVER_PORT/DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_db2_issues"><div class="titlepage"><div><div><h3 class="title">8.1.&nbsp;
Known issues with DB2
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Floats and doubles may lose precision when stored.
</p>
</li><li class="listitem">
<p>
Empty char values are stored as NULL.
</p>
</li><li class="listitem">
<p>
Fields of type BLOB and CLOB are limited to 1M. This number can be increased by
extending <code class="classname">DB2Dictionary</code>.
</p>
</li><li class="listitem">
<p>
Explicit creation of indexes specified by the OpenJPA @Index annotation will
fail on DB2 for iSeries if the default schema used by the JDBC driver does not
exist. If a default schema is not specified on the connection, the iSeries
will default to the user profile name. If a schema of that name does not
exist, DB2 on iSeries will not create the schema, resulting in a failure when
creating the index. The failure message will look similar to: "[SQL0204]
USERNAME in QSYS type *LIB not found." To work around this issue, specify a
default schema on the JDBC URL or data source property and make sure that
schema exists or create a schema which matches the user profile of the
connection.
</p>
</li><li class="listitem">
<p>
Use of DB2 on z/OS with the IBM JCC driver requires the DESCSTAT subsystem
parameter value to be set to 'YES'. If this parameter is set to 'NO', the
mapping tool will fail with a persistence exception containing this text:
"Invalid parameter: Unknown column name TABLE_SCHEM". After changing the value
of DESCSTAT, DB2 metadata tables must be recreated by running the DSNTIJMS job.
See DB2 for z/OS documentation for additional information.
</p>
</li><li class="listitem">
<p>
When using LOBs with persistent attributes of a streaming data type (e.g.
<code class="literal">java.io.InputStream</code>) in the case of very large LOB, DB2 JCC
driver will automatically use progressive streaming to retrieve the LOB data.
With progressiveStreaming, the inputStream retrieved must be fully materialized
before the next iteration of call to rs.next(). By default
this will result in a LobClosedException when OpenJPA processes the InputStream.
</p>
<p>
To work around this condition you may force fullyMaterializedLobData to true in
the connection URL as shown below :
</p><pre class="programlisting">
openjpa.ConnectionURL: jdbc:db2://localhost:50000/demodb:fullyMaterializeLobData=true;progressiveStreaming=NO
</pre><p>
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_empress"><div class="titlepage"><div><div><h2 class="title" style="clear: both">9.&nbsp;
Empress
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_empress_issues">9.1.
Known issues with Empress
</a></span></dt></dl></div>
<div class="example" id="example_props_empress"><p class="title"><b>Example&nbsp;2.5.&nbsp;
Example properties for Empress
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: empress.jdbc.empressDriver
openjpa.ConnectionURL: jdbc:empress://SERVER=yourserver;PORT=6322;DATABASE=yourdb
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_empress_issues"><div class="titlepage"><div><div><h3 class="title">9.1.&nbsp;
Known issues with Empress
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Empress enforces pessimistic semantics (lock on
read) when not using <code class="literal">AllowConcurrentRead</code> property (which
bypasses row locking) for <code class="classname">EmpressDictionary</code>.
</p>
</li><li class="listitem">
<p>
Only the category 2 non-local driver is supported.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_h2"><div class="titlepage"><div><div><h2 class="title" style="clear: both">10.&nbsp;
H2 Database Engine
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_h2_issues">10.1.
Known issues with H2 Database Engine
</a></span></dt></dl></div>
<div class="example" id="example_props_h2"><p class="title"><b>Example&nbsp;2.6.&nbsp;
Example properties for H2 Database Engine
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: org.h2.Driver
openjpa.ConnectionURL: jdbc:h2:DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_h2_issues"><div class="titlepage"><div><div><h3 class="title">10.1.&nbsp;
Known issues with H2 Database Engine
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
None
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_hypersonic"><div class="titlepage"><div><div><h2 class="title" style="clear: both">11.&nbsp;
Hypersonic
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_hypersonic_issues">11.1.
Known issues with Hypersonic
</a></span></dt></dl></div>
<div class="example" id="example_props_hypersonic"><p class="title"><b>Example&nbsp;2.7.&nbsp;
Example properties for Hypersonic
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: org.hsqldb.jdbcDriver
openjpa.ConnectionURL: jdbc:hsqldb:DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_hypersonic_issues"><div class="titlepage"><div><div><h3 class="title">11.1.&nbsp;
Known issues with Hypersonic
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Hypersonic does not support pessimistic locking, so non-optimistic transactions
will fail unless the <code class="literal">SimulateLocking</code> property is set for the
<a class="link" href="#openjpa.jdbc.DBDictionary" title="6.2.&nbsp; openjpa.jdbc.DBDictionary"> openjpa.jdbc.DBDictionary</a>
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_firebird"><div class="titlepage"><div><div><h2 class="title" style="clear: both">12.&nbsp;
Firebird
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_firebird_issues">12.1.
Known issues with Firebird
</a></span></dt></dl></div>
<div class="example" id="example_props_firebird"><p class="title"><b>Example&nbsp;2.8.&nbsp;
Example properties for Firebird
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: org.firebirdsql.jdbc.FBDriver
openjpa.ConnectionURL: jdbc:firebirdsql:SERVER_NAME/3050:DB_PATH_OR_ALIAS
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_firebird_issues"><div class="titlepage"><div><div><h3 class="title">12.1.&nbsp;
Known issues with Firebird
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Firebird does not support auto-increment columns.
</p>
</li><li class="listitem">
<p>
In order to use many of JPQL functions with Firebird 1.5, Interbase UDFs
have to be available in the database.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_informix"><div class="titlepage"><div><div><h2 class="title" style="clear: both">13.&nbsp;
Informix
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_informix_issues">13.1.
Known issues with Informix
</a></span></dt></dl></div>
<div class="example" id="example_props_informix"><p class="title"><b>Example&nbsp;2.9.&nbsp;
Example properties for Informix Dynamic Server
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.informix.jdbc.IfxDriver
openjpa.ConnectionURL: \
jdbc:informix-sqli://SERVER_NAME:SERVER_PORT/DB_NAME:INFORMIXSERVER=SERVER_ID
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_informix_issues"><div class="titlepage"><div><div><h3 class="title">13.1.&nbsp;
Known issues with Informix
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
None
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_ingres"><div class="titlepage"><div><div><h2 class="title" style="clear: both">14.&nbsp;
Ingres Database
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_ingres_issues">14.1.
Known issues with Ingres
</a></span></dt></dl></div>
<div class="example" id="example_props_ingres"><p class="title"><b>Example&nbsp;2.10.&nbsp;
Example properties for Ingres
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.ingres.jdbc.IngresDriver
openjpa.ConnectionURL: \
jdbc:ingres://SERVER_NAME:DAS_SERVER_PORT/DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_ingres_issues"><div class="titlepage"><div><div><h3 class="title">14.1.&nbsp;
Known issues with Ingres
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Databases must be created with the -n flag for Unicode compatibility in
order to use LOBs.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_intersystems_cache"><div class="titlepage"><div><div><h2 class="title" style="clear: both">15.&nbsp;
InterSystems Cache
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_intersystems_cache_issues">15.1.
Known issues with InterSystems Cache
</a></span></dt></dl></div>
<div class="example" id="example_props_intersystems_cache"><p class="title"><b>Example&nbsp;2.11.&nbsp;
Example properties for InterSystems Cache
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.intersys.jdbc.CacheDriver
openjpa.ConnectionURL: jdbc:Cache://SERVER_NAME:SERVER_PORT/DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_intersystems_cache_issues"><div class="titlepage"><div><div><h3 class="title">15.1.&nbsp;
Known issues with InterSystems Cache
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Support for Cache is done via SQL access over JDBC, not through their object
database APIs.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_access"><div class="titlepage"><div><div><h2 class="title" style="clear: both">16.&nbsp;
Microsoft Access
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_access_issues">16.1.
Known issues with Microsoft Access
</a></span></dt></dl></div>
<div class="example" id="example_props_access"><p class="title"><b>Example&nbsp;2.12.&nbsp;
Example properties for Microsoft Access
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.ddtek.jdbc.sequelink.SequeLinkDriver
openjpa.ConnectionURL: jdbc:sequelink://SERVER_NAME:SERVER_PORT
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_access_issues"><div class="titlepage"><div><div><h3 class="title">16.1.&nbsp;
Known issues with Microsoft Access
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Using the Sun JDBC-ODBC bridge to connect is not supported.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_sqlserver"><div class="titlepage"><div><div><h2 class="title" style="clear: both">17.&nbsp;
Microsoft SQL Server
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_sqlserver_issues">17.1.
Known issues with SQL Server
</a></span></dt></dl></div>
<div class="example" id="example_props_sqlserver"><p class="title"><b>Example&nbsp;2.13.&nbsp;
Example properties for Microsoft SQL Server
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.microsoft.sqlserver.jdbc.SQLServerDriver
openjpa.ConnectionURL: \
jdbc:sqlserver://SERVER_NAME:1433;DatabaseName=DB_NAME;selectMethod=cursor;sendStringParametersAsUnicode=false
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_sqlserver_issues"><div class="titlepage"><div><div><h3 class="title">17.1.&nbsp;
Known issues with SQL Server
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
When using a Microsoft SQL Server JDBC Driver v1.2 or earlier, the
ConnectionURL must always contain the <code class="literal">selectMethod=cursor
</code> string, which is necessary for the driver to properly
support large result sets.
</p>
</li><li class="listitem">
<p>
When using a Microsoft SQL Server JDBC Driver v1.2 or earlier, the
JDBC driver has bugs that manifest themselves when prepared statements
are pooled. Please disable prepared statement pooling by including the
<code class="literal">MaxCachedStatements=0</code> configuration property
in your org.apache.openjpa.ConnectionFactoryProperties.
</p>
</li><li class="listitem">
<p>
SQL Server date fields are accurate only to the nearest 3 milliseconds,
possibly resulting in precision loss in stored dates.
</p>
</li><li class="listitem">
<p>
Adding <code class="literal">sendStringParametersAsUnicode=false</code> to the
ConnectionURL may significantly increase performance.
</p>
</li><li class="listitem">
<p>
The Microsoft SQL Server driver only emulates batch updates. The DataDirect JDBC
driver has true support for batch updates, and may result in a significant
performance gain.
</p>
</li><li class="listitem">
<p>
Floats and doubles may lose precision when stored.
</p>
</li><li class="listitem">
<p>
<code class="literal">TEXT</code> columns cannot be used in queries.
</p>
</li><li class="listitem">
<p>
When using a SQL Server instance that has been configured to be case-sensitive
in schema names, you need to set the "schemaCase=preserve" parameter in the
<a class="link" href="#openjpa.jdbc.DBDictionary" title="6.2.&nbsp; openjpa.jdbc.DBDictionary">openjpa.jdbc.DBDictionary</a>
property.
</p>
</li><li class="listitem">
<p>
SQL Server 2005 does not support native sequences. If you would like to use
generated values with SQL Server you should use GenerationType.IDENTITY,
GenerationType.TABLE, or GenerationType.AUTO.
</p>
</li><li class="listitem">
<p>
The use of <a class="link" href="#ref_guide_streamsupport" title="7.11.&nbsp; LOB Streaming">LOB streaming</a> is limited.
When reading LOB data from the database, the Microsoft SQL Server driver will
actually load all the data into memory at the same time.
</p>
</li><li class="listitem">
<p>
The SQL Server 2008 DATETIME2 data type supports 7 digits sub-second precision.
When DataDirect JDBC driver is used with SQL Server 2008, setTimestamp method call with
a java.sql.Timestamp argument of more than 3 digits precision in a prepared statement
will result in truncation. This may cause loss of data precision or
optimistic lock exception if an entity uses Timestamp type as version field.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_foxpro"><div class="titlepage"><div><div><h2 class="title" style="clear: both">18.&nbsp;
Microsoft FoxPro
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_foxpro_issues">18.1.
Known issues with Microsoft FoxPro
</a></span></dt></dl></div>
<div class="example" id="example_props_foxpro"><p class="title"><b>Example&nbsp;2.14.&nbsp;
Example properties for Microsoft FoxPro
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.ddtek.jdbc.sequelink.SequeLinkDriver
openjpa.ConnectionURL: jdbc:sequelink://SERVER_NAME:SERVER_PORT
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_foxpro_issues"><div class="titlepage"><div><div><h3 class="title">18.1.&nbsp;
Known issues with Microsoft FoxPro
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Using the Sun JDBC-ODBC bridge to connect is not supported.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_mysql"><div class="titlepage"><div><div><h2 class="title" style="clear: both">19.&nbsp;
MySQL
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_mysql_query_hints">19.1.
Using Query Hints with MySQL
</a></span></dt><dt><span class="section"><a href="#dbsupport_mysql_issues">19.2.
Known issues with MySQL
</a></span></dt></dl></div>
<div class="example" id="example_props_mysql"><p class="title"><b>Example&nbsp;2.15.&nbsp;
Example properties for MySQL
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.mysql.jdbc.Driver
openjpa.ConnectionURL: jdbc:mysql://SERVER_NAME/DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_mysql_query_hints"><div class="titlepage"><div><div><h3 class="title">19.1.&nbsp;
Using Query Hints with MySQL
</h3></div></div></div>
<p>
MySQL has support for "query hints", which are keywords embedded in
SQL that provide some hint for how the query should be executed. These hints are
usually designed to provide suggestions to the MySQL query optimizer for how to
efficiently perform a certain query, and aren't typically needed for any but
the most intensive queries.
OpenJPA supports hints to be placed between SELECT keyword and column list.
</p>
<div class="example" id="dbsupport_mysql_query_hints_ex"><p class="title"><b>Example&nbsp;2.16.&nbsp;
Using MySQL Hints
</b></p><div class="example-contents">
<pre class="programlisting">
Query query = em.createQuery(...);
query.setHint("openjpa.hint.MySQLSelectHint", "SQL_NO_CACHE");
List results = query.getResultList();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="dbsupport_mysql_issues"><div class="titlepage"><div><div><h3 class="title">19.2.&nbsp;
Known issues with MySQL
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The default table types that MySQL uses do not support transactions, which will
prevent OpenJPA from being able to roll back transactions. Use the
<code class="literal">InnoDB</code> table type for any tables that OpenJPA will access.
</p>
</li><li class="listitem">
<p>
MySQL does not support sub-selects in versions prior to 4.1, so
some operations (such as the <code class="function">isEmpty()</code> method in a
query) will fail due to this.
</p>
</li><li class="listitem">
<p>
Rollback due to database error or optimistic lock violation is not supported
unless the table type is one of the MySQL transactional types. Explicit calls to
<code class="function">rollback()</code> before a transaction has been committed,
however, are always supported.
</p>
</li><li class="listitem">
<p>
Floats and doubles may lose precision when stored in some datastores.
</p>
</li><li class="listitem">
<p>
When storing a field of type <code class="classname">java.math.BigDecimal</code>, some
datastores will add extraneous trailing 0 characters, causing an equality
mismatch between the field that is stored and the field that is retrieved.
</p>
</li><li class="listitem">
<p>
When using large result sets with MySQL there are a number of documented limitations.
Please read the section titled "ResultSet" in the "MySQL JDBC API Implementation Notes".
The net effect of these limitations is that you will have to read all of the rows of a
result set (or close the connection) before you can issue any other queries on
the connection, or an exception will be thrown. Setting openjpa.FetchBatchSize
to any value greater than zero will enable streaming result sets.
</p>
</li><li class="listitem">
<p>
The use of <a class="link" href="#ref_guide_streamsupport" title="7.11.&nbsp; LOB Streaming">LOB streaming</a> is limited.
When reading LOB data from the database, the MySQL JDBC driver will actually
load all the data into memory at the same time.
</p>
</li><li class="listitem">
<p>
As of MySQL 5.7 the <code class="code">DATETIME</code> data type supports sub-second fractions.
The default of MySQL is to use no fractions.
The number of fractions can be explicitly set via scale:
<code class="code">@Column(scale=3)</code> will lead to a <code class="code">DATETIME(3)</code> column.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_mariadb"><div class="titlepage"><div><div><h2 class="title" style="clear: both">20.&nbsp;
MariaDB
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_mariadb_issues">20.1.
Known issues with MariaDB
</a></span></dt></dl></div>
<div class="example" id="example_props_mariadb"><p class="title"><b>Example&nbsp;2.17.&nbsp;
Example properties for MariaDB
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: org.mariadb.jdbc.Driver
openjpa.ConnectionURL: jdbc:mariadb://SERVER_NAME/DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_mariadb_issues"><div class="titlepage"><div><div><h3 class="title">20.1.&nbsp;
Known issues with MariaDB
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
As of MariaDB 10.2 the <code class="code">DATETIME</code> data type supports sub-second fractions.
The default of MariaDB internally is to use no fractions.
The number of fractions can be explicitly set via scale:
<code class="code">@Column(scale=6)</code> will lead to a <code class="code">DATETIME(6)</code> column and able to store microseconds.
A value of <code class="code">@Column(scale=-1)</code> will explicitly turn off all fractions.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_oracle"><div class="titlepage"><div><div><h2 class="title" style="clear: both">21.&nbsp;
Oracle
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_oracle_query_hints">21.1.
Using Query Hints with Oracle
</a></span></dt><dt><span class="section"><a href="#dbsupport_oracle_issues">21.2.
Known issues with Oracle
</a></span></dt></dl></div>
<div class="example" id="example_props_oracle"><p class="title"><b>Example&nbsp;2.18.&nbsp;
Example properties for Oracle
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: oracle.jdbc.driver.OracleDriver
openjpa.ConnectionURL: jdbc:oracle:thin:@SERVER_NAME:1521:DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_oracle_query_hints"><div class="titlepage"><div><div><h3 class="title">21.1.&nbsp;
Using Query Hints with Oracle
</h3></div></div></div>
<p>
Oracle has support for "query hints", which are formatted comments embedded in
SQL that provide some hint for how the query should be executed. These hints are
usually designed to provide suggestions to the Oracle query optimizer for how to
efficiently perform a certain query, and aren't typically needed for any but
the most intensive queries.
</p>
<div class="example" id="dbsupport_oracle_query_hints_ex"><p class="title"><b>Example&nbsp;2.19.&nbsp;
Using Oracle Hints
</b></p><div class="example-contents">
<pre class="programlisting">
Query query = em.createQuery(...);
query.setHint("openjpa.hint.OracleSelectHint", "/*+ first_rows(100) */");
List results = query.getResultList();
</pre>
</div></div><br class="example-break">
</div>
<div class="section" id="dbsupport_oracle_issues"><div class="titlepage"><div><div><h3 class="title">21.2.&nbsp;
Known issues with Oracle
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The Oracle JDBC driver has significant differences between different versions.
It is important to use the officially supported version of the drivers
(10.2.0.1.0/11.2.0.x.0), which is backward compatible with previous versions of the Oracle
server. It can be downloaded from
<a class="ulink" href="http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html" target="_top">
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html</a>.
</p>
</li><li class="listitem">
<p>
Empty string/char values are stored as NULL.
</p>
</li><li class="listitem">
<p>
Oracle corp's JDBC driver for Oracle has only limited support for batch updates.
The result for OpenJPA is that batching of some statements may fail and in some cases,
the exact object that failed an optimistic lock check cannot be determined. OpenJPA will
throw an <code class="classname">OptimisticException</code> with more failed objects than actually
failed. This situation may be resolved by disabling statement batching by setting the
batchLimit value to zero or by using a more recent Oracle JDBC Driver (11.2.0.1) with
batch support improvements. Attempting to resolve the issue with a more current driver
is recommended since disabling statement batching can result in a decrease in performance.
</p><div class="example" id="dbsupport_oracle_disable_batch_updates"><p class="title"><b>Example&nbsp;2.20.&nbsp;
Property to disable statement batching for Oracle
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.jdbc.DBDictionary: oracle(batchLimit=0)
</pre>
</div></div><p><br class="example-break">
</p>
</li><li class="listitem">
<p>
Oracle cannot store numbers with more than 38 digits in numeric columns.
</p>
</li><li class="listitem">
<p>
Floats and doubles may lose precision when stored.
</p>
</li><li class="listitem">
<p>
CLOB columns cannot be used in queries.
</p>
</li><li class="listitem">
<p>
The use of LOBs with persistent attributes of a streaming data type (ex.
<code class="literal">java.io.InputStream</code> or <code class="literal">java.io.Reader</code>) may
require the same connection to be used over the life of the transaction or
entity manager. If the same connection is not used for persistent operations
a <code class="literal">java.io.IOException</code> with message <code class="literal">Closed Connection
</code> may result. The OpenJPA property <code class="literal">openjpa.ConnectionRetainMode</code>
can be used to control how OpenJPA uses datastore connections. See
<a class="xref" href="#ref_guide_dbsetup_retain" title="8.&nbsp; Configuring the Use of JDBC Connections">Section&nbsp;8, &#8220;
Configuring the Use of JDBC Connections
&#8221;</a> for details.
</p><div class="example" id="dbsupport_oracle_retain_connection"><p class="title"><b>Example&nbsp;2.21.&nbsp;
Property to retain connection over the lifetime of the entity manager
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionRetainMode: always
</pre>
</div></div><p><br class="example-break">
</p>
</li><li class="listitem">
<p>
Mapping persistent attributes to <a class="link" href="#ref_guide_xmlmapping" title="7.10.&nbsp; XML Column Mapping">XML columns</a> requires
a JDBC 4 compliant driver if XML strings are longer than 4000 bytes, as counted in database.
Otherwise an <code class="literal">ORA-01461: can bind a LONG value only for insert into a LONG column</code>
error may result.
</p>
</li><li class="listitem">
<p>
If Oracle dictionary property <code class="literal">MaxEmbeddedBlobSize</code> or
<code class="literal">MaxEmbeddedClobSize</code> is set to some limit (i.e. not -1) and embedded collection
with BLOB/CLOB attribute is used, a
<code class="literal">"org.apache.openjpa.persistence.ArgumentException:
"x.y.z.EmbedOwner.embedCollection&lt;element:class x.y.z.EmbedValue&gt;"
is mapped as embedded, but embedded field
"x.y.z.EmbedOwner.embedCollection.x.y.z.EmbedValue.blob" is not embeddable.
Embedded element/key/value types are limited to simple fields and direct relations to other
persistent types"</code> error may result. To overcome this limitation, either use JDBC driver
11.2.0.x.0 (or later version) or set both <code class="literal">MaxEmbeddedBlobSize</code> and
<code class="literal">MaxEmbeddedClobSize</code> properties to -1.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_pointbase"><div class="titlepage"><div><div><h2 class="title" style="clear: both">22.&nbsp;
Pointbase
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_pointbase_issues">22.1.
Known issues with Pointbase
</a></span></dt></dl></div>
<div class="example" id="example_props_pointbase"><p class="title"><b>Example&nbsp;2.22.&nbsp;
Example properties for Pointbase
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.pointbase.jdbc.jdbcUniversalDriver
openjpa.ConnectionURL: \
jdbc:pointbase:DB_NAME,database.home=pointbasedb,create=true,cache.size=10000,database.pagesize=30720
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_pointbase_issues"><div class="titlepage"><div><div><h3 class="title">22.1.&nbsp;
Known issues with Pointbase
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Fields of type BLOB and CLOB are limited to 1M. Set the <code class="literal">BlobTypeName
</code> and/or <code class="literal">ClobTypeName</code> properties of the
<code class="literal">openjpa.jdbc.DBDictionary</code> setting to override.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_postgresql"><div class="titlepage"><div><div><h2 class="title" style="clear: both">23.&nbsp;
PostgreSQL
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_postgresql_issues">23.1.
Known issues with PostgreSQL
</a></span></dt></dl></div>
<div class="example" id="example_props_postgresql"><p class="title"><b>Example&nbsp;2.23.&nbsp;
Example properties for PostgreSQL
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: org.postgresql.Driver
openjpa.ConnectionURL: jdbc:postgresql://SERVER_NAME:5432/DB_NAME
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_postgresql_issues"><div class="titlepage"><div><div><h3 class="title">23.1.&nbsp;
Known issues with PostgreSQL
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Floats and doubles may lose precision when stored.
</p>
</li><li class="listitem">
<p>
PostgreSQL cannot store very low and very high dates.
</p>
</li><li class="listitem">
<p>
Empty string/char values are stored as NULL.
</p>
</li><li class="listitem">
<p>
Persistent fields of type <code class="classname">java.io.Reader</code> are not
supported when using
<a class="link" href="#ref_guide_streamsupport" title="7.11.&nbsp; LOB Streaming">LOB streaming</a>.
</p>
</li></ul></div>
</div>
</div>
<div class="section" id="dbsupport_soliddb"><div class="titlepage"><div><div><h2 class="title" style="clear: both">24.&nbsp;
IBM solidDB
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_soliddb_table_types">24.1.
M-type tables vs. D-type tables
</a></span></dt><dt><span class="section"><a href="#dbsupport_soliddb_concurrency_control">24.2.
Concurrency control mechanism
</a></span></dt></dl></div>
<div class="example" id="example_props_soliddb"><p class="title"><b>Example&nbsp;2.24.&nbsp;
Example properties for IBM solidDB
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: solid.jdbc.SolidDriver
openjpa.ConnectionURL: jdbc:solid://localhost:2315/dba/dba
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_soliddb_table_types"><div class="titlepage"><div><div><h3 class="title">24.1.&nbsp;
M-type tables vs. D-type tables
</h3></div></div></div>
<p>
IBM solidDB supports two types of tables: in-memory tables (M-tables) and
on-disk tables (D-tables). Since cursor hold over commit can not apply to M-tables
(which will cause SOLID Table Error 13187: The cursor cannot continue
accessing M-tables after the transaction has committed or aborted.
The statement must be re-executed), the default OpenJPA tables are D-tables.
One can set the whole server to disk-based mode by adding
[General]
DefaultStoreIsMemory=no
in solid.ini. The table types can also be determined by setting OpenJPA property
"openjpa.jdbc.DBDictionary" with value "storeIsMemory=true" or "storeIsMemory=false"
in the persistence.xml. The "STORE MEMORY" and "STORE DISK" will be appended to
the create table DDL, respectively.
</p>
</div>
<div class="section" id="dbsupport_soliddb_concurrency_control"><div class="titlepage"><div><div><h3 class="title">24.2.&nbsp;
Concurrency control mechanism
</h3></div></div></div>
<p>
The default concurrency control mechanism depends on the table type:
Disk-based tables (D-tables) are by default optimistic.
Main-memory tables (M-tables) are always pessimistic.
Since OpenJPA applications expects lock waits as usually is done with
normal pessimistic databases, the server should be set to the pessimistic mode.
The optimistic mode is about not waiting for the locks at all. That increases
concurrency but requires more programming. The pessimistic mode with the
READ COMMITTED isolation level (default) should get as much concurrency as one
might need. The pessimistic locking mode can be set in solid.ini:
[General]
Pessimistic=yes
One can override the locking mode on the per table base by setting OpenJPA property
"openjpa.jdbc.DBDictionary" to value "lockingMode=PESSIMISTIC" in the persistence.xml.
An extra SQL will be generated along with CREATE TABLE DDL:
ALTER TABLE EX_POBJECT SET PESSIMISTIC.
The possible values for lockingMode is OPTIMISTIC/PESSIMISTIC.
</p>
</div>
</div>
<div class="section" id="dbsupport_sybase"><div class="titlepage"><div><div><h2 class="title" style="clear: both">25.&nbsp;
Sybase Adaptive Server
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#dbsupport_sybase_issues">25.1.
Known issues with Sybase
</a></span></dt></dl></div>
<div class="example" id="example_props_sybase"><p class="title"><b>Example&nbsp;2.25.&nbsp;
Example properties for Sybase
</b></p><div class="example-contents">
<pre class="programlisting">
openjpa.ConnectionDriverName: com.sybase.jdbc2.jdbc.SybDriver
openjpa.ConnectionURL: \
jdbc:sybase:Tds:SERVER_NAME:4100/DB_NAME?ServiceName=DB_NAME&amp;BE_AS_JDBC_COMPLIANT_AS_POSSIBLE=true
</pre>
</div></div><br class="example-break">
<div class="section" id="dbsupport_sybase_issues"><div class="titlepage"><div><div><h3 class="title">25.1.&nbsp;
Known issues with Sybase
</h3></div></div></div>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
The "<code class="literal">DYNAMIC_PREPARE</code>" parameter of the Sybase JDBC driver
cannot be used with OpenJPA.
</p>
</li><li class="listitem">
<p>
Datastore locking cannot be used when manipulating many-to-many relations using
the default OpenJPA schema created by the schematool, unless an auto-increment
primary key field is manually added to the table.
</p>
</li><li class="listitem">
<p>
Persisting a zero-length string results in a string with a single space
character being returned from Sybase, Inc.'s JDBC driver.
</p>
</li><li class="listitem">
<p>
The <code class="literal">BE_AS_JDBC_COMPLIANT_AS_POSSIBLE</code> is required in order to
use datastore (pessimistic) locking. Failure to set this property may lead to
obscure errors like " <code class="literal">FOR UPDATE can not be used in a SELECT which is
not part of the declaration of a cursor or which is not inside a stored
procedure.</code> ".
</p>
</li><li class="listitem">
<p>
Applications performing update/insert data of the BigDecimal Java type may fail
with OptimisticException if the data exceeds the scale or precision of the
column on Sybase. To avoid this problem, applications can specify the precision
and scale for the numeric type by setting numericTypeName='NUMERIC(p,s)' for
the column type mapped by the BigDecimal Java type. See
<a class="link" href="#openjpa.jdbc.DBDictionary" title="6.2.&nbsp; openjpa.jdbc.DBDictionary">openjpa.jdbc.DBDictionary</a> for
more detail. Alternatively, application can set the precision and scale using
the standard <code class="classname">Column</code> annotation, described in
<a class="xref" href="#jpa_overview_mapping_column" title="3.&nbsp; Column">Section&nbsp;3, &#8220;
Column
&#8221;</a>.
</p>
</li></ul></div>
</div>
</div>
</div>
<div class="appendix" id="migration_considerations"><div class="titlepage"><div><div><h2 class="title">Appendix&nbsp;3.&nbsp;
Migration Considerations
</h2></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#jpa_2.0">1.
OpenJPA 2.0.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.0_incompatibilities">1.1.
Incompatibilities
</a></span></dt><dd><dl><dt><span class="section"><a href="#getProperties">1.1.1.
getProperties()
</a></span></dt><dt><span class="section"><a href="#migration_detach_behavior">1.1.2.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#private_persistent_properties">1.1.3.
Use of private persistent properties
</a></span></dt><dt><span class="section"><a href="#setParameter">1.1.4.
Query.setParameter()
</a></span></dt><dt><span class="section"><a href="#serialization">1.1.5.
Serialization of Entities
</a></span></dt><dt><span class="section"><a href="#QuerySQLCache">1.1.6.
openjpa.jdbc.QuerySQLCache
</a></span></dt></dl></dd><dt><span class="section"><a href="#Disabling AutoOff Collection Tracking">1.2.
Disabling AutoOff Collection Tracking
</a></span></dt><dt><span class="section"><a href="#internal_differences">1.3.
Internal Behavioral Differences
</a></span></dt><dd><dl><dt><span class="section"><a href="#prePostUpdate">1.3.1.
PreUpdate/PostUpdate Life Cycle Callbacks
</a></span></dt><dt><span class="section"><a href="#createemf">1.3.2.
createEntityManagerFactory Exceptions
</a></span></dt><dt><span class="section"><a href="#querycache">1.3.3.
openjpa.QueryCache default
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_2.2">2.
OpenJPA 2.2.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.2_incompatibilities">2.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.2_allocationSize">2.1.1.
allocationSize Property of Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_metamodelArrays">2.1.2.
MetaModel Attributes for Arrays
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_SupportsSetClob">2.1.3.
supportsSetClob Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_UseNativeSequenceCache">2.1.4.
useNativeSequenceCache Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_cascadePersist">2.1.5.
Cascade persist behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_LifecycleEventManager">2.1.6.
Life Cycle Event Manager Callback Behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_sharedCacheMode">2.1.7.
shared-cache-mode Property
</a></span></dt></dl></dd></dl></dd><dt><span class="section"><a href="#jpa_2.3">3.
OpenJPA 2.3.0
</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.3_incompatibilities">3.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.3_MappingTool">3.1.1.
MappingTool Behavior for DB2 and Derby
</a></span></dt><dt><span class="section"><a href="#jpa_2.3_RequiresSearchStringEscapeForLike">3.1.2.
RequiresSearchStringEscapeForLike DBDictionary Property
</a></span></dt><dt><span class="section"><a href="#ReturnNullOnEmptyAggregateResult">3.1.3.
Return value of aggregate functions in SELECT clause
</a></span></dt></dl></dd></dl></dd></dl></div>
<div class="section" id="jpa_2.0"><div class="titlepage"><div><div><h2 class="title" style="clear: both">1.&nbsp;
OpenJPA 2.0.0
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_2.0_incompatibilities">1.1.
Incompatibilities
</a></span></dt><dd><dl><dt><span class="section"><a href="#getProperties">1.1.1.
getProperties()
</a></span></dt><dt><span class="section"><a href="#migration_detach_behavior">1.1.2.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#private_persistent_properties">1.1.3.
Use of private persistent properties
</a></span></dt><dt><span class="section"><a href="#setParameter">1.1.4.
Query.setParameter()
</a></span></dt><dt><span class="section"><a href="#serialization">1.1.5.
Serialization of Entities
</a></span></dt><dt><span class="section"><a href="#QuerySQLCache">1.1.6.
openjpa.jdbc.QuerySQLCache
</a></span></dt></dl></dd><dt><span class="section"><a href="#Disabling AutoOff Collection Tracking">1.2.
Disabling AutoOff Collection Tracking
</a></span></dt><dt><span class="section"><a href="#internal_differences">1.3.
Internal Behavioral Differences
</a></span></dt><dd><dl><dt><span class="section"><a href="#prePostUpdate">1.3.1.
PreUpdate/PostUpdate Life Cycle Callbacks
</a></span></dt><dt><span class="section"><a href="#createemf">1.3.2.
createEntityManagerFactory Exceptions
</a></span></dt><dt><span class="section"><a href="#querycache">1.3.3.
openjpa.QueryCache default
</a></span></dt></dl></dd></dl></div>
<div class="section" id="jpa_2.0_incompatibilities"><div class="titlepage"><div><div><h3 class="title">1.1.&nbsp;
Incompatibilities
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#getProperties">1.1.1.
getProperties()
</a></span></dt><dt><span class="section"><a href="#migration_detach_behavior">1.1.2.
Detach Behavior
</a></span></dt><dt><span class="section"><a href="#private_persistent_properties">1.1.3.
Use of private persistent properties
</a></span></dt><dt><span class="section"><a href="#setParameter">1.1.4.
Query.setParameter()
</a></span></dt><dt><span class="section"><a href="#serialization">1.1.5.
Serialization of Entities
</a></span></dt><dt><span class="section"><a href="#QuerySQLCache">1.1.6.
openjpa.jdbc.QuerySQLCache
</a></span></dt></dl></div>
<p>
The following sections indicate changes that are incompatible
between OpenJPA 1.x.x releases and the 2.0 release. Some may
require application changes. Others can be remedied through the
use of compatibility options. If your application uses a
version 1.0 persistence.xml, compatibility options will be set
appropriately to maintain backward compatibility. OpenJPA 2.0
applications using a version 2.0 persistence.xml and requiring
OpenJPA 1.x.x compatibility may need to configure the
appropriate compatibility options to get the desired behavior.
</p>
<div class="section" id="getProperties"><div class="titlepage"><div><div><h4 class="title">1.1.1.&nbsp;
getProperties()
</h4></div></div></div>
<p>
The OpenJPAEntityManagerFactory interface getProperties()
method was changed to return a Map instead of a
Properties object. This change was made in order to
support the getProperties() method defined in the
JPA 2.0 specification.
</p>
</div>
<div class="section" id="migration_detach_behavior"><div class="titlepage"><div><div><h4 class="title">1.1.2.&nbsp;
Detach Behavior
</h4></div></div></div>
<p>
The detach behavior has changed in several ways:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
In the 1.x.x release, managed entities
were flushed to the database as part of the
detach operation. This is no longer done in
2.0.
</p>
</li><li class="listitem">
<p>
In the 1.x.x release, entities were copied
and returned. In 2.0, for those methods
that have return values, the original
entities are returned.
</p>
</li><li class="listitem">
<p>
In the 1.x.x release, managed entities still
exist in the persistent context. In 2.0,
they are removed.
</p>
</li><li class="listitem">
<p>
In the 1.x.x release, the detach operation
is recursively cascaded to all referenced
entities. In 2.0, the detach operation is
only cascaded to those entities for which
Cascade=detach has been specified.
</p>
</li></ul></div><p>
</p>
<p>
Applications that use a 1.0 persistence.xml will
automatically maintain OpenJPA 1.x.x behavior. It is
possible for a version 2.0 application to revert back to
the 1.x.x behavior for some of these items by setting the
openjpa.Compatibility property as follows:
</p><table border="0" summary="Simple list" class="simplelist"><tr><td>CopyOnDetach=true</td></tr><tr><td>FlushBeforeDetach=true</td></tr><tr><td>CascadeWithDetach=true</td></tr></table><p>
</p>
<p>
In addition, a new method has been provided on the
<a class="ulink" href="../../apidocs/org/apache/openjpa/persistence/OpenJPAEntityManager.html" target="_top">
<code class="classname">OpenJPAEntityManager</code></a>
interface to return a copy of the entity:
</p><pre class="programlisting">
public &lt;T&gt; T detachCopy(T pc):
</pre><p>
</p>
</div>
<div class="section" id="private_persistent_properties"><div class="titlepage"><div><div><h4 class="title">1.1.3.&nbsp;
Use of private persistent properties
</h4></div></div></div>
<p>
In 1.x.x releases of OpenJPA, if property access was used,
private properties were considered persistent. This is
contrary to the JPA specification, which states that
persistent properties must be public or protected. In
OpenJPA 2.0 and later, private properties will not be
persistent by default.
</p>
<p>
Applications that use a 1.0 persistence.xml will
automatically maintain OpenJPA 1.x.x behavior. It is
possible for a version 2.0 application to revert back to
the 1.x.x behavior by setting the value of the
<code class="literal">openjpa.Compatibility</code>
property <code class="literal">PrivatePersistentProperties</code> to
<code class="literal">true</code>. If compile time enhancement is
used, this property must be specified at the time of
enhancement and at runtime.
</p>
</div>
<div class="section" id="setParameter"><div class="titlepage"><div><div><h4 class="title">1.1.4.&nbsp;
Query.setParameter()
</h4></div></div></div>
<p>
The Query interface setParameter() method behavior has
changed to throw an IllegalArgumentException (as required
by the JPA specification) if more parameter substitutions
are supplied than defined in the createQuery(),
createNamedQuery(), or createNativeQuery() invocation.
OpenJPA 1.2.x and prior versions silently ignored these
extraneous parameter substitutions and allowed the Query
to be processed.
</p>
</div>
<div class="section" id="serialization"><div class="titlepage"><div><div><h4 class="title">1.1.5.&nbsp;
Serialization of Entities
</h4></div></div></div>
<p>
In 1.x.x releases of OpenJPA, when an entity was serialized
after calling EntityManager.find(), detach() or detachAll()
then all <a class="xref" href="#ref_guide_pc_scos_proxy" title="6.4.&nbsp; Proxies">Section&nbsp;6.4, &#8220;
Proxies
&#8221;</a>
references were removed as expected, but when the same
entity instance was serialized after calling
EntityManager.clear() the proxy classes were not removed.
</p>
<p>
This has two side-effects:
when entities are remoted across JVM boundaries (RPC)
or deserialized the OpenJPA runtime must be available
on the classpath (both client and server containers);
when entities are deserialized the OpenJPA runtime must
be the exact same revision as used to serialize the
entities due to the proxy classes using dynamically
generated serialVersionUID values.
</p>
<p>
Starting with OpenJPA 2.0, this behavior has been
modified, so that by default all proxies will be removed
during serialization. See
<a class="xref" href="#ref_guide_pc_scos_proxy_serial" title="6.4.4.&nbsp; Serialization">Section&nbsp;6.4.4, &#8220;
Serialization
&#8221;</a>
on how the behavior changes based on the
<code class="literal">DetachedStateField</code> setting along with
<a class="xref" href="#ref_guide_detach_state" title="1.3.1.&nbsp; Detached State">Section&nbsp;1.3.1, &#8220;
Detached State
&#8221;</a>
for more details on how to override the default
<code class="literal">DetachedStateField</code> setting.
</p>
<p>
Applications that use a 1.0 persistence.xml will
automatically maintain the old behavior. It is
possible for a version 2.0 application to revert back to
the prior 1.x.x behavior by setting the following
openjpa.Compatibility property as follows:
</p><table border="0" summary="Simple list" class="simplelist"><tr><td>IgnoreDetachedStateFieldForProxySerialization=true</td></tr></table><p>
</p>
</div>
<div class="section" id="QuerySQLCache"><div class="titlepage"><div><div><h4 class="title">1.1.6.&nbsp;
openjpa.jdbc.QuerySQLCache
</h4></div></div></div>
<p>
In prior 1.x.x releases, the openjpa.jdbc.QuerySQLCache
configuration property for Prepared SQL Cache accepted
value <code class="literal">all</code> to never drop items from the
cache, but this option is no longer supported and will cause
a PersistenceException with a root cause of a ParseException
to be thrown. See
<a class="xref" href="#ref_guide_cache_querysql" title="3.&nbsp;Prepared SQL Cache">Section&nbsp;3, &#8220;Prepared SQL Cache&#8221;</a>
for details on the available configuration values.
</p>
</div>
</div>
<div class="section" id="Disabling AutoOff Collection Tracking"><div class="titlepage"><div><div><h3 class="title">1.2.&nbsp;
Disabling AutoOff Collection Tracking
</h3></div></div></div>
<p>
The default behavior of OpenJPA in tracking collections is that
if the number of modifications to the collection exceeds the
current number of elements in collection then OpenJPA will
disable tracking the collections. OpenJPA 2.0 added a compatibility
property to disable turning off the collection tracking.
</p>
<p>
The behavior of Auto disabling of collection tracking can be
avoided by setting the value of the
<code class="literal">openjpa.Compatibility</code> property
<code class="literal">autoOff</code> to <code class="literal">false</code>.
The default behavior of auto disabling the collection tracking
is not changed. But when the above property is set then the
collection tracking will not be disabled automatically.
</p>
</div>
<div class="section" id="internal_differences"><div class="titlepage"><div><div><h3 class="title">1.3.&nbsp;
Internal Behavioral Differences
</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#prePostUpdate">1.3.1.
PreUpdate/PostUpdate Life Cycle Callbacks
</a></span></dt><dt><span class="section"><a href="#createemf">1.3.2.
createEntityManagerFactory Exceptions
</a></span></dt><dt><span class="section"><a href="#querycache">1.3.3.
openjpa.QueryCache default
</a></span></dt></dl></div>
<p>
The following sections indicate internal changes between
OpenJPA 1.x.x releases and the 2.0 release. As these are
internal implementation specific behaviors not covered by
the JPA specification, no changes should be required for
applications that did not use or depend upon OpenJPA specific
APIs or behavior.
</p>
<div class="section" id="prePostUpdate"><div class="titlepage"><div><div><h4 class="title">1.3.1.&nbsp;
PreUpdate/PostUpdate Life Cycle Callbacks
</h4></div></div></div>
<p>
If an entity was updated between the persist()
and commit() operations in OpenJPA 1.x, then
any PreUpdate and PostUpdate life cycle callback
methods would be executed. Starting in OpenJPA
1.3 and 2.0, these callbacks will not get executed.
</p>
<p>
The JPA 2.0 specification section on "Semantics
of the Life Cycle Callback Methods for Entities"
has been updated to include a Note that the
callback behavior for updating an entity after
the persist operation is implementation specific
and should not be relied upon.
</p>
</div>
<div class="section" id="createemf"><div class="titlepage"><div><div><h4 class="title">1.3.2.&nbsp;
createEntityManagerFactory Exceptions
</h4></div></div></div>
<p>
The JPA 2.0 specification section on
"Bootstrapping in Java SE Environments" states
that persistence providers must return null
if they are not a qualified provider for the
given persistence unit.
</p>
<p>
However, OpenJPA may throw a RuntimeException
if an error occurs while trying to create a
qualified persistence unit, like for invalid
openjpa.* specific configuration settings or
for schema validation failures.
</p>
<p>
If the Apache Geronimo JPA 2.0 Spec APIs are
used, then any exceptions returned by a
persistence provider will be wrapped within
a PersistenceException. When the JPA 2.0 API
reference implementation is used, any
RuntimeExceptions will be returned to the
calling application without being wrapped.
Other JPA 2.0 API and implementation providers
or versions may behave differently.
</p>
</div>
<div class="section" id="querycache"><div class="titlepage"><div><div><h4 class="title">1.3.3.&nbsp;
openjpa.QueryCache default
</h4></div></div></div>
<p>
In previous releases, the default value for the
openjpa.QueryCache property was <code class="literal">true</code>
when the openjpa.DataCache was enabled. Depending on
application characteristics, this default QueryCache
enablement actually could negate much of the potential
gains achieved by using the DataCache. Thus, the default
value for the openjpa.QueryCache property is now
<span class="emphasis"><em><code class="literal">false</code></em></span>.
</p>
<p>
To re-enable the default QueryCache behavior, you need to
include the following property in your persistence.xml
configuration.
</p><pre class="programlisting">
&lt;property name="openjpa.QueryCache" value="true"/&gt;
</pre><p>
</p>
<p>
If your configuration had previously enabled the QueryCache
explicitly, then you might have to include the
<code class="literal">true</code> value into your configuration
(if you relied on the previous default). Otherwise, your
current QueryCache enablement will continue to work.
</p><pre class="programlisting">
&lt;property name="openjpa.QueryCache" value="true(CacheSize=1000, SoftReferenceSize=100)"/&gt;
</pre><p>
</p>
</div>
</div>
</div>
<div class="section" id="jpa_2.2"><div class="titlepage"><div><div><h2 class="title" style="clear: both">2.&nbsp;
OpenJPA 2.2.0
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_2.2_incompatibilities">2.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.2_allocationSize">2.1.1.
allocationSize Property of Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_metamodelArrays">2.1.2.
MetaModel Attributes for Arrays
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_SupportsSetClob">2.1.3.
supportsSetClob Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_UseNativeSequenceCache">2.1.4.
useNativeSequenceCache Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_cascadePersist">2.1.5.
Cascade persist behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_LifecycleEventManager">2.1.6.
Life Cycle Event Manager Callback Behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_sharedCacheMode">2.1.7.
shared-cache-mode Property
</a></span></dt></dl></dd></dl></div>
<div class="section" id="jpa_2.2_incompatibilities"><div class="titlepage"><div><div><h3 class="title">2.1.&nbsp;Incompatibilities</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_2.2_allocationSize">2.1.1.
allocationSize Property of Sequence Generator
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_metamodelArrays">2.1.2.
MetaModel Attributes for Arrays
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_SupportsSetClob">2.1.3.
supportsSetClob Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_UseNativeSequenceCache">2.1.4.
useNativeSequenceCache Property.
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_cascadePersist">2.1.5.
Cascade persist behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_LifecycleEventManager">2.1.6.
Life Cycle Event Manager Callback Behavior
</a></span></dt><dt><span class="section"><a href="#jpa_2.2_sharedCacheMode">2.1.7.
shared-cache-mode Property
</a></span></dt></dl></div>
<p>
The following sections indicate changes that are incompatible
between OpenJPA 2.1.x releases and the 2.2.0 release.
</p>
<div class="section" id="jpa_2.2_allocationSize"><div class="titlepage"><div><div><h4 class="title">2.1.1.&nbsp;
allocationSize Property of Sequence Generator
</h4></div></div></div>
<p>
In previous releases, specifying the <code class="literal">allocationSize</code> property of
<a class="link" href="#jpa_overview_mapping_sequence_seqgen" title="5.1.&nbsp; Sequence Generator">sequence generator</a>
affected only sequence definition in the database. During
schema creation, the <code class="literal">INCREMENT BY</code> clause of
<code class="literal">CREATE SEQUENCE</code> statement always
had a value of 1 and on DB2, Oracle and PostgreSQL databases a <code class="literal">CACHE</code> clause
was added with the value of <code class="literal">allocationSize</code> property. Such a statement caused
sequence values being cached in the database. Starting with OpenJPA 2.2.0,
sequence values are cached in the jvm memory and the <code class="literal">allocationSize</code>
property determines size of that cache. The <code class="literal">CACHE</code> clause is no longer used,
instead the <code class="literal">INCREMENT BY</code> clause gets its value equal to the
<code class="literal">allocationSize</code> property. Such a strategy reduces the number of database roundtrips
required for retrieving sequence values considerably.
</p>
<p>
In order for the existing applications to work with OpenJPA
2.2.0, you have to manually recreate or redefine sequences, specifying
the correct <code class="literal">INCREMENT BY</code> value and, possibly, correct initial sequence value.
Note that the default value of the <code class="literal">allocationSize</code> property is 50 and that
value is used if the property is not specified.
</p>
<p>
The requirement for sequence modification applies to all databases that support sequences, regardless of
the <code class="literal">CACHE</code> clause being supported. The only exception is Firebird database -
since with this database the increment step is determined during sequence
value fetch, no migration activity is needed.
</p>
<p>
To maintain the old behavior of sequence generator in OpenJPA 2.2.0, you can:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p>
Set the <code class="literal">allocationSize</code> property value to 1.
</p>
</li><li class="listitem">
<p>
Additionally, if the <code class="literal">CACHE</code> clause has to be emitted in sequence definition,
this can be accomplished by overriding the
<a class="ulink" href="../../apidocs/org/apache/openjpa/jdbc/sql/DBDictionary.html#getCreateSequenceSQL(org.apache.openjpa.jdbc.schema.Sequence)" target="_top">
<code class="methodname">DBDictionary.getCreateSequenceSQL</code></a> method.
</p>
</li></ul></div><p>
</p>
</div>
<div class="section" id="jpa_2.2_metamodelArrays"><div class="titlepage"><div><div><h4 class="title">2.1.2.&nbsp;
MetaModel Attributes for Arrays
</h4></div></div></div>
<p>
In previous releases OpenJPA's MetaModel implementation generated a ListAttribute for every array. This behavior is correct if the array
is annotated as a PersistentCollection, but not correct for un-annotated arrays (e.g. byte[], char[]). In OpenJPA 2.2.0 this behavior was corrected
so that arrays which are not stored as PersistentCollections will use a SingularAttribute instead of a ListAttribute.
</p>
<p>
If your application uses the MetaModel API and your entities contain arrays of any of the following types: byte[], Byte[], char[], Character[] and
do not use the @PersistentCollection annotation with those fields you will need to update your application to use OpenJPA 2.2.0.
</p>
<p> In order for the existing applications to work with OpenJPA you may:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
<p> Regenerate the canonical metamodel classes</p>
</li><li class="listitem">
<p> Set the Compatibility property <code class="literal">UseListAttributeForArrays</code> to <code class="literal">true</code> in persistence.xml
</p><pre class="programlisting"> &lt;property name="openjpa.Compatibility" value="UseListAttributeForArrays=true"/&gt;</pre><p>
</p>
</li></ul></div><p>
</p>
</div>
<div class="section" id="jpa_2.2_SupportsSetClob"><div class="titlepage"><div><div><h4 class="title">2.1.3.&nbsp;
supportsSetClob Property.
</h4></div></div></div>
<p>
In OpenJPA 2.2.0, code was added to allow the setting of CLOB or XML data larger than 4000 bytes. This functionality
was eventually back ported to previous releases, and enabled by the <code class="literal">supportsSetClob</code> property on the OracleDictionary. Setting this property
has no effect in 2.2.0 and later releases and any occurrence of it should be removed.
</p>
</div>
<div class="section" id="jpa_2.2_UseNativeSequenceCache"><div class="titlepage"><div><div><h4 class="title">2.1.4.&nbsp;
useNativeSequenceCache Property.
</h4></div></div></div>
<p>
In OpenJPA 2.2.0, code was added which changed the way sequences were generated, please see
<a class="xref" href="#jpa_2.2_allocationSize" title="2.1.1.&nbsp; allocationSize Property of Sequence Generator">Section&nbsp;2.1.1, &#8220;
allocationSize Property of Sequence Generator
&#8221;</a> for details. This functionality was eventually back ported
to previous releases, and enabled by the <code class="literal">useNativeSequenceCache</code> property on the DBDictionary. Setting this property
has no effect in 2.2.0 and later releases and any occurrence of it should be removed. If previous behavior is
desired (i.e. <code class="literal">useNativeSequenceCache=true</code>), please see the details described in section
<a class="xref" href="#jpa_2.2_allocationSize" title="2.1.1.&nbsp; allocationSize Property of Sequence Generator">Section&nbsp;2.1.1, &#8220;
allocationSize Property of Sequence Generator
&#8221;</a>.
</p>
</div>
<div class="section" id="jpa_2.2_cascadePersist"><div class="titlepage"><div><div><h4 class="title">2.1.5.&nbsp;
Cascade persist behavior
</h4></div></div></div>
<p>
In previous releases, OpenJPA would check the database for the
existence of the related Entity before persisting the relationship to
that Entity. This resulted in an extra Select being sent to the
database. In 2.2.0, code was added so that when cascading a persist to
a related Entity without persistence state, the persist (insert) will
happen without first checking the database. This may result in an
EntityExistsException if the related Entity already exists in the
database. To revert this behavior to the previous release, set the
value of the <code class="literal">openjpa.Compatibility</code>
property <code class="literal">CheckDatabaseForCascadePersistToDetachedEntity</code>
to <code class="literal">true</code>.
</p>
</div>
<div class="section" id="jpa_2.2_LifecycleEventManager"><div class="titlepage"><div><div><h4 class="title">2.1.6.&nbsp;
Life Cycle Event Manager Callback Behavior
</h4></div></div></div>
<p>
Life cycle event manager is used to manage entity's life cycle event callback.
In previous releases, Life cycle event manager is scoped to EntityManagerFactory.
This means listeners registered to an individual EntityManager may get life cycle
event callbacks for entity that it does not manage.
</p>
<p>
From 2.2.1 release, the default callback behavior of the life cycle event manager
is changed to scope to each EntityManager.
To revert this behavior to the previous release, set the
value of the <code class="literal">openjpa.Compatibility</code>
property <code class="literal">SingletonLifecycleEventManager</code>
to <code class="literal">true</code>.
</p>
</div>
<div class="section" id="jpa_2.2_sharedCacheMode"><div class="titlepage"><div><div><h4 class="title">2.1.7.&nbsp;
shared-cache-mode Property
</h4></div></div></div>
<p>
In the previous release, when the shared-cache-mode is enabled and the DataCache property is not set
or set to false, there will be no data caching.
</p>
<p>
From 2.2.2 release, the caching will be turned on if the shared-cache-mode is enabled. Please see the
details described in section <a class="xref" href="#ref_guide_shared_cache_mode_integration" title="1.1.2.&nbsp; Integration with JPA standard shared cache mode">Section&nbsp;1.1.2, &#8220;
Integration with JPA standard shared cache mode
&#8221;</a>.
</p>
</div>
</div>
</div>
<div class="section" id="jpa_2.3"><div class="titlepage"><div><div><h2 class="title" style="clear: both">3.&nbsp;
OpenJPA 2.3.0
</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_2.3_incompatibilities">3.1. Incompatibilities</a></span></dt><dd><dl><dt><span class="section"><a href="#jpa_2.3_MappingTool">3.1.1.
MappingTool Behavior for DB2 and Derby
</a></span></dt><dt><span class="section"><a href="#jpa_2.3_RequiresSearchStringEscapeForLike">3.1.2.
RequiresSearchStringEscapeForLike DBDictionary Property
</a></span></dt><dt><span class="section"><a href="#ReturnNullOnEmptyAggregateResult">3.1.3.
Return value of aggregate functions in SELECT clause
</a></span></dt></dl></dd></dl></div>
<div class="section" id="jpa_2.3_incompatibilities"><div class="titlepage"><div><div><h3 class="title">3.1.&nbsp;Incompatibilities</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#jpa_2.3_MappingTool">3.1.1.
MappingTool Behavior for DB2 and Derby
</a></span></dt><dt><span class="section"><a href="#jpa_2.3_RequiresSearchStringEscapeForLike">3.1.2.
RequiresSearchStringEscapeForLike DBDictionary Property
</a></span></dt><dt><span class="section"><a href="#ReturnNullOnEmptyAggregateResult">3.1.3.
Return value of aggregate functions in SELECT clause
</a></span></dt></dl></div>
<p>
The following sections indicate changes that are incompatible
between OpenJPA 2.2.x releases and the 2.3.0 release.
</p>
<div class="section" id="jpa_2.3_MappingTool"><div class="titlepage"><div><div><h4 class="title">3.1.1.&nbsp;
MappingTool Behavior for DB2 and Derby
</h4></div></div></div>
<p>
In previous releases, the MappingTool mapped <code class="literal">java.math.BigDecimal</code> fields to the database type
DOUBLE, and as such, ignored <code class="literal">column</code> and <code class="literal">precision</code> values that might have been specified via the
<code class="literal">javax.persistence.Column</code> annotation.
</p>
<p>
From the 2.3.0 release, <code class="literal">java.math.BigDecimal</code> fields are now mapped to the database type DECIMAL
and it is very likely that you will need to specify <code class="literal">column</code> and <code class="literal">precision</code> via
the <code class="literal">javax.persistence.Column</code> annotation.
</p>
</div>
<div class="section" id="jpa_2.3_RequiresSearchStringEscapeForLike"><div class="titlepage"><div><div><h4 class="title">3.1.2.&nbsp;
RequiresSearchStringEscapeForLike DBDictionary Property
</h4></div></div></div>
<p>
In previous releases, the default value for the property RequiresSearchStringEscapeForLike is true and caused the
unexpected escape clause appended to the SQL statement.
For example, user created a named query like this:
</p><pre class="programlisting"> SELECT o.computerName FROM CompUser o WHERE o.name LIKE ?</pre><p>
At run time the following query is generated:
</p><pre class="programlisting"> SELECT t0.computerName FROM CompUser t0 WHERE (t0.name LIKE ? ESCAPE '\')</pre><p>
ESCAPE '\' shouldn't be appended to the query.
</p>
<p>
From the 2.3.0 release, RequiresSearchStringEscapeForLike property is set to false by default. You can configure
RequiresSearchStringEscapeForLike property to be true if the old behavior is desired.
</p>
</div>
<div class="section" id="ReturnNullOnEmptyAggregateResult"><div class="titlepage"><div><div><h4 class="title">3.1.3.&nbsp;
Return value of aggregate functions in SELECT clause
</h4></div></div></div>
<p>
The JPA specification states "If SUM, AVG, MAX, or MIN is used, and there are no values to which the aggregate function can be
applied, the result of the aggregate function is NULL." Prior to this update, OpenJPA incorrectly returned 0 for SUM, AVG, MIN,
and MAX when a state field being aggregated is numeric. This behavior affects both JPQL and Criteria queries. With this update,
OpenJPA will return a null result value for these aggregate functions when a query returns no result.
</p>
<p>
To re-enable the prior behavior, you need to set the following persistence property in your persistence.xml or when
creating an EntityManagerFactory.
</p><pre class="programlisting">
&lt;property name="openjpa.Compatibility" value="ReturnNullOnAggregateResult=false"/&gt;
</pre><p>
</p>
</div>
</div>
</div>
</div>
</div>
</div></body></html>