You are on page 1of 302

Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
er denDriven
Building Database
b t
s to Swith
Applications
e tu JPA
n
z (er Guide
Student e this
an
de to us
e rn nse SL-370-EE6 Rev A
n a l H lice
B er able
e s to sfer
E rn -tran
s non
C arlo

D65187GC11
Edition 1.1
August 2010
D68596
Copyright 2010, Oracle and/or its affiliates. All rights reserved.

Disclaimer

This document contains proprietary information, is provided under a license agreement containing restrictions on use and
disclosure, and is protected by copyright and other intellectual property laws. You may copy and print this document solely for
your own use in an Oracle training course. The document may not be modified or altered in any way. Except as expressly
permitted in your license agreement or allowed by law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

authorization of Oracle.

The information contained in this document is subject to change without notice. If you find any problems in the document,
please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.

Sun Microsystems, Inc. Disclaimer

This training manual may include references to materials, offerings, or products that were previously offered by Sun
Microsystems, Inc. Certain materials, offerings, services, or products may no longer be offered or provided. Oracle and its
affiliates cannot be held responsible for any such references should they appear in the text provided.
s a
Restricted Rights Notice
) h a
m x
Government, the following notice is applicable:
t ob
If this documentation is delivered to the U.S. Government or anyone using the documentation on behalf of the U.S.
g
s a de
U.S. GOVERNMENT RIGHTS
a l@ Gui
The U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these training materials are
n
b er dent
restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

Trademark Notice
e s to Stu
( e rn this
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
This page intentionallybeleft r blank.
e n t
e s to Stud
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
This page intentionallybeleft r blank.
e n t
e s to Stud
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Table of Contents
s a
About This Course .............................................................Preface-xiii h a
m x)
Course Goals........................................................................... Preface-xiii
g
Topics Not Covered .................................................................
t ob Preface-xiv
s a dePreface-xv
How Prepared Are You?...........................................................

n a l@ Gui Preface-xvi
Introductions ............................................................................
e r ent
How to Use Course Materials .................................................
b Preface-xvii

to Stud
Conventions ........................................................................... Preface-xviii
e s
Typographical(e
rn th............................................
Conventions
is
Icons.............................................................................. Preface-xviii
Preface-xix
e
d to u
Additional
z
Conventions s e ................................................... Preface-xx
a n

Overviewe rnof thenJava
se Persistence API............................................1-1
H
al Objectives e
r n l e lic ............................................................................................ 1-1
B e ab Additional Resources ............................................................................ 1-2

e s to sfer Java Persistence API ............................................................................. 1-3


E rn -tran Object Relational Mapping Software ................................................... 1-4

r l o s non Entity Classes........................................................................................ 1-7


Ca Declaring the Entity Class ........................................................... 1-7
Verifying and Overriding the Default Mapping ......................... 1-9
Persistent Fields Compared With Persistent Properties............ 1-11
Persistent Fields ......................................................................... 1-11
Persistence Data Types .............................................................. 1-12
The Concept of a Primary Key ................................................. 1-13
Life Cycle and Operational Characteristics of Entity Components.... 1-14
Persistence Units....................................................................... 1-15
persistence.xml File ........................................................... 1-15
Persistence Context.................................................................... 1-15
Entity Manager ......................................................................... 1-16
Entity Instance Management ..................................................... 1-16
Entity States and Entity Manager Methods ............................... 1-17
Entity Manager Methods .......................................................... 1-20
Deploying Entity Classes.................................................................... 1-21
A Persistence Unit in a Java EE Application............................ 1-23
Examining a Persistence Unit Using Non-Default Settings ............... 1-24

v
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Java Persistence API in Java SE Applications ................ 1-25
Introducing the Auction Application.............................................. 2-1
Objectives ............................................................................................ 2-1
Additional Resources ............................................................................ 2-2
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Auction Application Use Cases ............................................................ 2-3


Analyzing the Auction System ............................................................. 2-5
Auction Application Domain Objects.......................................... 2-5
Auction Domain Object............................................................ 2-7
AuctionUser Domain Object................................................... 2-9
Bid Domain Object .................................................................. 2-10
Item Domain Object ................................................................ 2-11
BookItem Domain Object ....................................................... 2-12
s a
Examining the Implementation Model ............................................... 2-13
) h a
m x
Middle-Tier Subsystems ............................................................ 2-13
Java Persistence API Entities.........................................................
t g ob 3-1
s a de 3-1
Objectives ............................................................................................
a l@ Gui
Additional Resources ............................................................................
n 3-2
b e r e n t
Understanding Entities.......................................................................... 3-3
Object Tier and Data Tier s o
t andSDynamic
Static d
tu Mapping Example ...
n e
(er e this
3-3
e z
Defining an Entity........................................................................
s 3-6
Persistent Fields
n a ndand Properties
t o u .......................................................... 3-10
Field-Based e
er ensAccess.................................................................... 3-10
a l H i c
Property-Based Access .............................................................. 3-11
n l
B er Attributes
a b le ............................................................................................ 3-13
s t o sfer @Transient
@Column Annotation ................................................................. 3-13
r n e ran Annotation .......................................................... 3-15
s E n-t @Temporal Annotation............................................................. 3-15
r l o n o @Access Annotation ................................................................. 3-16
Ca Primary Keys and Entity Identity ....................................................... 3-18
@Id Annotation.......................................................................... 3-19
@GeneratedValue .................................................................. 3-19
Understanding the Entity Manager ................................................ 4-1
Objectives ............................................................................................ 4-1
Additional Resources ............................................................................ 4-2
Understanding Entity Manager............................................................. 4-3
Persistence Unit .................................................................................... 4-4
description Element............................................................... 4-6
provider Element...................................................................... 4-6
properties Element ................................................................. 4-6
jta-data-source and non-jta-data-source Elements ... 4-9
class, jar-file, and mapping-file Elements.................... 4-9
Persistence Context............................................................................. 4-13
Obtaining an Entity Manager.............................................................. 4-14

vi Building Database Driven Applications with the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Obtaining a Container-Managed Entity Manager in the Java EE
Environment............................................................................ 4-14
Obtaining an Application-Managed Entity Manager................. 4-16
Examining Entity Life-Cycle States ................................................... 4-19
Using Entities to Interact With the Database...................................... 4-23
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Using an Extended Persistence Context Entity Manager .......... 4-26


Modeling Entity Relationships ........................................................5-1
Objectives ............................................................................................ 5-1
Additional Resources ............................................................................ 5-2
Examining Association Relationships in Data and Object Models ...... 5-3
Using Relationship Properties to Define Associations ......................... 5-5
Examples of Association Relationships....................................... 5-6
s a
Implementing One-to-One Unidirectional Association ...................... 5-10
) h a
Implementing One-to-One Bidirectional Association ........................ 5-12
m x
Implementing One-to-Many/Many-to-One Bidirectional Association.......
t g ob
5-14
s a de
n a l@ Gui
Implementing Many-to-Many Bidirectional Association................... 5-16

b er dent
Examining Fetch and Cascade Mode Settings.................................... 5-18
Fetch Mode Attribute................................................................. 5-18
e s to Stu
Cascade Mode Attribute ............................................................ 5-19
( e rn this
Entity Inheritance and
e
d to u z s e
Object-Relational Mapping........................6-1
Objectivesn............................................................................................ 6-1
n a
H er eResources
Additional
n seInheritance
............................................................................ 6-2

n a l Examining
l i c Entity ............................................................... 6-3

B er aExamining
b le Object/Relational Inheritance Hierarchy Mapping Strategies .
e s to sfer 6-4
r n r a n Mapping Inheritance Using the Single-Table-Per-Class Hierarchy
s E n-t Strategy .................................................................................... 6-6
ar l o n o Mapping Inheritance Using the Joined-Subclass Strategy ......... 6-7
C Mapping Inheritance Using a Table-Per-Class Strategy............. 6-8
Inheriting From an Entity Class............................................................ 6-9
Inheriting Using a Mapped Superclass ............................................... 6-11
Inheriting From a Non-Entity Class.................................................... 6-13
Using an Embeddable Class ............................................................... 6-15
Defining Entity Classes by Using an Embeddable Class .......... 6-15
Persisting Enums and Collections .................................................7-1
Objectives ............................................................................................ 7-1
Additional Resources ............................................................................ 7-2
Introduction........................................................................................... 7-3
Persisting Entities With Enums .................................................. 7-4
Persisting Entities With Lists...................................................... 7-8
Persisting Entities With Maps................................................... 7-11
Introduction to Querying .................................................................8-1
Objectives ............................................................................................ 8-1

vii
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources ............................................................................ 8-2
Introduction to Querying Entities ......................................................... 8-3
Querying Using the Entity Manager ..................................................... 8-4
Examining Query Objects..................................................................... 8-6
Setting Query Object Metadata............................................................. 8-8
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Setting the Flush Mode ................................................................ 8-8


Setting the Lock Mode................................................................. 8-8
Setting Hints ................................................................................ 8-9
Introducing the Java Persistence Query Language ............................. 8-11
Introducing Native Queries Using SQL.............................................. 8-12
Introducing the Criteria API ............................................................... 8-13
Using Named Queries ......................................................................... 8-15
Declaring and Using Named Parameters ................................... 8-16 s a
Declaring and Using Positional Parameters............................... 8-17 ) h a
m x
Using the Java Persistence Query Language ...............................
t g ob 9-1
s a e
Objectives ............................................................................................ 9-1

n a l@ G uid
Additional Resources ............................................................................ 9-2
Introducing the Java Persistence Query Language
b e r ent ............................... 9-3
Declaring Query Strings: The SELECT
s t o tud Statement................................ 9-4
Examining the FROM Clause
r n e is S ....................................................... 9-5
Examining the WHERE
z (e Clause e th.....................................................9-12
9-8
Examining the
a
Examiningn
dthee GROUP
SELECT
t o uBYs and HAVING Clauses ....................... 9-12
Clause.................................................

e rn nthe
Examining seORDER BY Clause.............................................. 9-14
l H
aDeclaring e
ic Strings: The UPDATE Statement.............................. 9-15
r n l e lQuery
B e Declaring
a b Query Strings: The DELETE Statement.............................. 9-16
o
st nUsing r
fe the Criteria API .................................................................... 10-1
n e s
s Er n-tra Objectives .......................................................................................... 10-1
r l o n o Additional Resources .......................................................................... 10-2
Ca Introduction to the Criteria API .......................................................... 10-3
Criteria Query API Usage................................................................... 10-4
sConstructing Criteria Queries............................................................ 10-5
Understanding the Metamodel API .................................................... 10-7
Using a String-Based Metamodel ............................................. 10-9
Parameter Expressions ...................................................................... 10-10
Named Parameters ................................................................... 10-10
Joins .................................................................................................. 10-12
Chaining Joins.......................................................................... 10-13
Outer Joins ............................................................................... 10-13
Query Modification........................................................................... 10-15
Ordering the Query Results .............................................................. 10-16
Using the Java Persistence API in a Container .......................... 11-1
Objectives .......................................................................................... 11-1
Additional Resources .......................................................................... 11-2

viii Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction to Using the Java Persistence API in a Container .......... 11-3
Java Servlets ....................................................................................... 11-4
Simple Java Servlet............................................................................. 11-5
Adding a Container-Managed Entity Manager to a Servlet ............... 11-7
Using Transactions in a Servlet ........................................................ 11-10
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Understanding EJB Components ...................................................... 11-11


What Is a Session Bean?.......................................................... 11-11
Types of Session Beans ........................................................... 11-11
Session Bean Annotation Types .............................................. 11-12
Characteristics of a Session Bean ............................................ 11-12
Session Bean Clients................................................................ 11-12
Creating Session Beans: Essential Tasks.......................................... 11-14
No-Interface Implementation................................................... 11-14 s a
Adding a Container-Managed Entity Manager to a Stateless Session Bean ) h a
11-15 m x
t g ob
Injecting a Stateless Session Bean into a Servlet.................... 11-16
s a de
n a l@ Gui
Implementing Transactions and Locking.....................................12-1

b e r ent
Objectives .......................................................................................... 12-1
t o tud
Additional Resources .......................................................................... 12-2

r n es is S
What Is a Transaction? ....................................................................... 12-3
e e th....................................................... 12-5
Container-Managed(Transactions
z
Bean-ManagedeTransactions s (BMT) .................................................. 12-6
n
d o u
e rna Context
Introducing
Persistence
the Javat Transaction API ................................................ 12-7
n se Lifetime .............................................................. 12-8
H
al Controllinge
r n l e lic Java Persistence API Transactions ................................ 12-10
B e ab Java Transaction API Entity Managers ................................... 12-10
e s t o s f er Resource-Local Entity Managers............................................. 12-11
r n t r a n EntityTransaction Interface............................................. 12-11
E -
rlos non
Container-Managed Persistence Contexts ........................................ 12-13
C a Container-Managed Transaction-Scoped Persistence Context 12-13
Container-Managed Extended Persistence Context................. 12-14
Optimistic Locking ........................................................................... 12-16
Version Attribute ..................................................................... 12-16
Pessimistic Locking .......................................................................... 12-18
Lock Modes ...................................................................................... 12-20
OPTIMISTIC and OPTIMISTIC_FORCE_INCREMENT Modes .......
12-20
PESSIMISTIC_READ, PESSIMISTIC_WRITE, and
PESSIMISTIC_FORCE_INCREMENT Modes ....................... 12-21
Advanced Java Persistence API Concepts..................................13-1
Objectives .......................................................................................... 13-1
Additional Resources .......................................................................... 13-2
Composite Primary Keys .................................................................... 13-3
Defining a Composite Primary Key With the @EmbeddedId Annotation
13-5

ix
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Finding Entities With an Embedded ID Using an Entity Manager ...
13-7
Defining a Composite Primary Key With the @IdClass Annotation13-9
Finding Entities With an ID Class Using an Entity Manager.. 13-11
Overriding Mappings With the @AttributeOverride Annotation .......
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

13-12
Overriding Multiple Mappings With the @AttributeOverrides
Annotation ............................................................................ 13-13
Overriding the Default Mapping of Collections ............................... 13-14
Overriding Mappings for Entity Relationships With the
@AssociationOverride Annotation ........................................ 13-15
Entity Listeners and Callback Methods ............................................ 13-17
Life-Cycle Callback Methods ........................................................... 13-18 s a
Creating an Entity Listener Class ..................................................... 13-21 ) h a
m x
t g ob A-2
Java DB.............................................................................................A-1
a de A-3
Additional Resources ...........................................................................
s
n a l@ Gui
What Is Java DB? ................................................................................

b e r ent
Installing Java DB....................................................................... A-3
t o tud
Java DB Configurations.............................................................. A-4
Introduction to the JavaTM rPlatform, n es isEnterprise S Edition 6 .........B-1
Additional Resources (
z use e t h
............................................................................B-2
n d e
Introducing the
n a JavaTM
t oPlatform, Enterprise Edition (Java EE) .........B-3

H er theeJava
Examining
n seEE Application Architecture ................................B-6

n a l Examining
l i c the Component-Container Architecture ....................B-6

B er abExamining
le the Java EE Implementation of the

s t o sfer Examining Java EE Container


Container-Component Architecture..........................................B-7
r n e ran Services.......................................B-9
s E n-t Examine the EJB Application Creation Process.................................B-14
r l o n o Comparing Java EE Application Development With Traditional
Ca Enterprise Application Development...............................................B-18

x Building Database Driven Applications with the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Preface
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

About This Course

Course Goals a
h a s
x )
Upon completion of this course, you should be able to: m
t g ob
Describe the basics of Object Relational Mapping (ORM)
s a de
a
Define the key concepts of the Java Persistence
n
@ (entity,
lAPI G uientity manager,
and persistence unit)
b er dent
s to SAPI
Identify and use common JavaePersistence tu annotations, such as
n
@Entity, @Id, @Table,
z e this
r @Column
(eand
n
delifetcycle
Describe the entity
a o us
e rn nproperties
Use relationship se to define associations such as one-to-one, one-
l H e
r n ato-many,
l e licmany-to-many
and
Be Understand
r ab object/relational inheritance hierarchy mapping strategies
t o f e
r n es ran s Persist entities that contain enums with @Enumerated
s E n-t Persist entities that contain lists with @ElementCollection
ar l o no
C Understand basic Java Persistence API query language queries
Understand native SQL queries
Understand basic Criteria API queries
Use the Java Persistence API from a servlet
Use the Java Persistence API from a stateless session bean
Apply transactions to the Java Persistence API
Understand entity listeners and callback methods

Preface-xiii
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Topics Not Covered

Topics Not Covered


This course does not cover the following topics. Many of these topics are covered
in other courses offered by Sun Educational Services.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Object-oriented concepts Covered in OO-226: Object-Oriented Analysis


and Design for Java Technology (UML)
Distributed programming concepts and support technologies, such as remote
procedure call (RPC), Remote Method Invocation (RMI), Internet Inter-
ORB Protocol (IIOP), Common Object Request Broker Architecture
(CORBA), Lightweight Directory Access Protocol (LDAP), Java Naming
and Directory Interface API (JNDIAPI) s a
) h a
m x
Refer to the Sun Educational Services catalog for specific information and
registration.
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Preface-xiv Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
How Prepared Are You?

How Prepared Are You?


If you are prepared to take this course, you should be able to answer yes to the
following questions:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Can you write a Java technology class?


Can you implement composition, association, and inheritance relationships?
Can you handle events and exceptions generated in Java technology
classes?
Can you describe the issues associated with transaction management?
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

About This Course Preface-xv


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introductions

Introductions
Now that you have been introduced to the course, introduce yourself to the other
students and the instructor, including the following information:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Name
Company affiliation
Title, function, and job responsibility
Experience related to topics presented in this course
Reasons for enrolling in this course
s a
Expectations for this course
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Preface-xvi Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
How to Use Course Materials

How to Use Course Materials


To enable you to succeed in this course, these course materials contain a learning
module that is composed of the following components:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Goals You should be able to accomplish the goals after finishing this
course and meeting all of its objectives.
Objectives You should be able to accomplish the objectives after
completing a portion of instructional content. Objectives support goals and
can support other higher-level objectives.
Lecture The instructor presents information specific to the objective of the
s a
module. This information helps you learn the knowledge and skills
) h a
m x necessary to succeed with the activities.
Activities The activities take various forms, such as an g
t ob self-
exercise,
check, discussion, and demonstration. Activities help s ayou facilitate
d e the
mastery of an objective. al@ t Gu i
r n
e dvisual n aids to convey a
Visual aids The instructor might use
o bseveral
t form. e
concept, such as a process, ine asvisual S tuVisual aids commonly contain
n
( r e this
graphics, animation, andevideo.
z
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C

About This Course Preface-xvii


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Conventions

Conventions
The following conventions are used in this course to represent various training
elements and alternative learning resources.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Icons

Additional resources Indicates other references that provide additional


information on the topics described in the module.
s a
) h a
m x
t
Discussion Indicates that a small-group or class discussion onathe
ob topic
gcurrent
s d e
! is recommended at this time.
al@ t Gu i
? r n
e den
o b
n e st S tu
z (er that
Note Indicates additional information e thcanishelp students but is not crucial to
n
e being
thedconcept us described. Students should be able to
a
their understanding of
rn orncomplete t o
understand the e
H concept
e se the task without this information. Examples
r n al information
of notational
e lic include keyword shortcuts and minor system
e ab
adjustments.
B l
e s t o s f er
E rn -tran
s non
C arlo

Preface-xviii Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Conventions

Typographical Conventions
Courier is used for the names of commands, files, directories, programming
code, and on-screen computer output; for example:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Use ls -al to list all files.


system% You have mail.

Courier is also used to indicate programming constructs, such as class names,


methods, and keywords; for example:
The getServletInfo method is used to get author information.
The java.awt.Dialog class contains Dialog constructor. s a
) h a
m x
ob
Courier bold is used for characters and numbers that you type, for example:
To list the files in this directory, type: t
a de g
s
# ls
n a l@ Gui
b er dent
Courier bold is also used for each line
e s toof programming
S tu code that is referenced

( e rn this
in a textual description, for example:
1 import java.io.*;
d e z use
2 import a
n n to
javax.servlet.*;
r ns e
e javax.servlet.http.*;
3 import
l H c e
rnaNotice thelijavax.servlet interface is imported to allow access to its life-
e
e
B ecycle l
abmethods (Line 2).
t o f r
r n es rans
s E n-t Courier italics is used for variables and command-line placeholders that are
ar l o no replaced with a real name or value, for example:
C To delete a file, use the rm filename command.

Courier italic bold is used to represent variables whose values are to be


typed by the student as part of an activity, for example:
Type chmod a+rwx filename to grant read, write, and execute rights for
filename to world, group, and users.

Palatino italics is used for book titles, new words or terms, or emphasized words,
for example:
Read Chapter 6 in the Users Guide.
These are called class options.

About This Course Preface-xix


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Conventions

Additional Conventions
Java programming language examples use the following additional conventions:
Method names are not followed with parentheses unless a formal or actual
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

parameter list is shown, for example:


The doIt method... refers to any method called doIt.
The doIt() method... refers to a method called doIt that takes no
arguments.
Line breaks occur only where there are separations (commas), conjunctions
(operators), or white space in the code. Broken code is indented four spaces
s a
under the starting code.
) h a
m x
If a command used in the Solaris Operating System (Solaris OS) is
t g ob
different from a command used in the Microsoft Windows platform, both
s a de
commands are shown, for example:
n a l@ Gui
In the Solaris OS:
b er dent
$CD SERVER_ROOT/BIN
e s to Stu
In Microsoft Windows:
( e rn this
d e z use
C:\>CD SERVER_ROOT\BIN
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Preface-xx Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 1
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Overview of the Java Persistence API

Objectives a
h a s
x )
Upon completion of this module, you should be able to: m
t g ob
Describe the basics of Object Relational Mapping (ORM)
s a de
a
Define the key concepts of the Java Persistence
n
@ (entity,
lAPI G uientity manager,
and persistence unit)
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

1-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Eric Jendrock, Debbie Carson, Ian Evans, Devika Gollapudi, Kim Haase,
Chinmayee Srivathsa. The Java EE 6 Tutorial,
[http://java.sun.com/javaee/6/docs/tutorial/doc/],
accessed September 15, 2009.
JSR 317: Java Persistence, Version 2.0, Java Persistence API,
[http://jcp.org/en/jsr/detail?id=317], accessed September
15, 2009. s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

1-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Java Persistence API

Java Persistence API


Databases are a key feature of nearly every enterprise application. Without a data
persistence mechanism, applications would not be able to preserve the data that
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

would otherwise be lost when the application shuts down or the server
unexpectedly loses power.

Historically, JDBC was used by Java developers to store data in the database.
While this continues to be an effective way to interact with a database using the
Java language and SQL statements, it presents a problem: the developer must
create and maintain Java code that maps the JavaBean component to the database
table. s a
) h a
m x
The Java Persistence API - available to both Java SE and Java EE applications -
g ob
goes beyond simple JDBC to offer a full object / relational mapping solution.
t
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Overview of the Java Persistence API 1-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Object Relational Mapping Software

Object Relational Mapping Software


The persistence mechanism used in most enterprise applications is a relational
database. However, object-oriented (OO) program design and relational database
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

table structure might not organize data in the same structure. A Java business
domain object can encompass partial data from a single database table or include
data from multiple tables depending on the normalization of the relational
database.

s a
Customer ) h a
m x Entity

t g ob Component

s a de
n a l@ Gui
Customer
b er dent
e s to Stu
Figure 1-1 e rn tOriented
Business Concept-to-Object
( his Domain Object and
z
de to us
Relational Database e
Mapping
a n

Writing codeH toe rn nfrom
translate sean object-oriented domain scheme to a relational
e
l canlicbe time consuming. Object relational mapping (ORM)
ascheme
database
r n
e attempts leto provide this mapping to OO software developers while
B
software
a b
r or no coding. Often just configuration information in the form of
e s torequiring
s f elittle
E an annotations or XML configuration files are supplied to ORM software.
rn -trcode
arlos non Examples of existing ORM software are EclipseLink and Hibernate.
C
Note EclipseLink is the continuation of Oracles open-source version of
Toplink. Oracle donated the source code for Toplink, a Java Persistence API 1.0
provider, to the Eclipse Foundation. EclipseLink is the reference implementation
for the Java Persistence API 2.0 specification. For more information, see
http://www.eclipse.org/eclipselink/.

1-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Object Relational Mapping Software

The most basic ORM software supports a simple mapping of Java objects to
database tables, as shown in Figure 1-2.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Customer
Customer

Account
Account
s a
) h a
m x
t g ob
s a de
Address
n a l@Address
G ui
b er dent
e s to Stu
n his
Figure 1-2 (er eof tJava
One-to-OnezMapping Objects to Relational Tables
e
nd to u s
n a e the ability to map Java objects to database table
Modern ORM
H ersoftware
e n shas
r n al thate dolicnot have a simple one-to-one mapping, as shown in Figure 1-3.
structures
B e abl
e s to sfer
E rn -tran
s non
arlo
Customer
C
Customer
Entity
Component Account

Address

Figure 1-3 One-to-Many Mapping of a Java Object to Relational Tables

Overview of the Java Persistence API 1-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Object Relational Mapping Software

The Java Persistence API specification is a specification for an API and life-cycle
behavior. It is not usable ORM software. In order to use the Java Persistence API,
you must obtain a Java Persistence API provider implementation. Two examples
of Java Persistence API providers are EclipseLink and Hibernate.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

1-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Classes

Entity Classes
An entity is a lightweight persistent domain object. An entity class may make use
of auxiliary classes that serve as helper classes or that are used to represent the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

state of the entity.

This section provides an overview of the tasks required to define a Java


Persistence API entity class. To define an entity class, you are required to
perform the following tasks:
Declare the entity class.
Verify, and optionally override, the default mapping. s a
) h a
The following subsections describe these tasks in more detail. m x
t g ob
s a de
Declaring the Entity Class n a l@ Gui
b er dent
The following steps outline a processe s to can Susetuto declare an entity class.
you
n his
1. Collect information z (er toedeclare
required t the entity class.
e
nd to u s
n a e
H er involves
This step
e n sidentifying the application domain object, identified in

n a l
the
l i c
object-oriented analysis and design phase of application development,

B er thatabyou
lewant to persist.
e s to sfer Use the domain object name as the class name.
E rn -tran Use the domain object field names and data types as the field names
s non
C arlo and types of entity classes.
2. Declare a public Java technology class.

The class must not be final, and no methods of the entity class can be final.
The class can be concrete or abstract. The class can not be an inner class.
3. If an entity instance is to be passed by value as a detached object through a
remote interface, then ensure that the entity class implements the
Serializable interface.
4. Annotate the class with the javax.persistence.Entity annotation.
5. Declare the attributes of the entity class.

Attributes of an entity can be defined either as instance variables,


properties, or a combination of the two.

Attributes defined as instance variables must not have public visibility.

Overview of the Java Persistence API 1-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Classes

They can have private, protected, or package visibility. Clients must not
attempt to access an entity classs instance variables directly.

Attributes specified as properties are defined using a set of public getter and
setter methods for every attribute declared.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

6. Annotate the primary key field or the getter method that corresponds to the
primary key column with the Id annotation.

Note Primary key fields can be either a single field or a collection of fields. For
more information on multi-field primary keys, see Advanced Java Persistence
API Concepts.
s a
) h a
7.
m x
Declare a public or protected no-arg constructor that takes no parameters.

t g ob
The container uses this constructor to create instances of the entity class.
a de
The class can have additional constructors.
s
n a l@ Gui
Code 1-1 Entity Class Code Example
b er dent
1 import javax.persistence.*; e s to Stu
2 ( e rn this
3 @Entity
d e z use
4 public class Item{
r n an e to
5
H e ens
6 @Id
n l
a e lic
7 private Bintr
e itemId; b l
to String
f a
erdescription;
8 s
private
e s
9 rn -tran
10s E public
n int getItemId() { return itemId; }
r l
a 11 o n o
public void setItemId(int itemId){
C 12 this.itemId = itemId;
13 }
14 public String getDescription() { return description; }
15 public void setDescription(String description) {
16 this.description = description;
17 }
18 }

1-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Classes

Verifying and Overriding the Default Mapping


The following table lists the default standard relationship between entity classes
and relational databases.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Table 1-1 Mapping Object Tier Elements to Database Tier Elements

Object Tier Element Database Tier Element

Entity class Database table


Attribute of entity class Database table column
s a
Entity instance Database table record
) h a
m x
The default database table name can be overridden using the Table
t g obannotation.
s
The Java Persistence API assigns the name of the entity class a as theddefault
e name
to the database table. For example: al@ t Gu i
r n
e den
@Entity o b
@Table(name = Cust) //Cust is the name
n e stof theStdatabase
u table
public class Client { r
(e e th i s
//... z
de to us
a n

}
e rn nse
a
ThenJava
lH l i c e API assigns the name of the entity class property or field
r as the
ename
Persistence
b ledefault name to the database table column. Use the Column
B a
er to override the default setting. For example:
to annotation
e s s f
E rn -tran
s non = Cust)
@Entity

C arlo @Table(name public class Client {


@Column(name = cname)
private String clientName;
//...
}

Several options are available for generating the values of primary keys. The
simplest option is to use the auto generation feature of the container. For
example:
@Entity
@Table(name = Cust)
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int clientReference;

Overview of the Java Persistence API 1-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Classes

//...
}

When using @GeneratedValue(strategy = GenerationType.AUTO)


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

EclipseLink creates a sequence table in the relational database. Other Java


Persistence API providers can use different techniques to create unique IDs.

Note This discussion examined the optional task of overriding the default
settings. For the vast majority of situations, using the defaults should be sufficient
if no previous database tables exist.
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

1-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Classes

Persistent Fields Compared With Persistent Properties


Entity classes have their state synchronized with a database. The state of an entity
class is obtained from either its variables (fields) or its accessor methods
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

(properties). Field-based or property-based access is determined by the placement


of annotations. A single persistence annotation on one field (variable) means that
the entire persistence state is determined by the entity objects variables. Java
Persistence API 1.0 entities cannot have both field-based and property-based
access.

Note The Java Persistence API 2.0 allows the mixing of field-based and
s a
property-based access with the introduction of the
) h a
javax.persistence.Access annotation.
m x
t g ob
s a de
Persistent Fields n a l@ Gui
b er dent
e s to provider
When using persistent fields, the persistence S tu retrieves an objects state
n
by reading its variables.
z (er e this
n
e be upublic.
dcannot s

a
Persistent fields
rnfieldsnshouldt o
H e
Persistent
e se not be read by clients directly.
al annotated
ern Unlessle lic with @Transient or modified with the transient
t o f ab all fields are persisted regardless of whether they have a @Column
B ekeyword,
r
r n es rans annotation.
s E n-t
ar l o no Code 1-2 Persistent Fields
C
@Id @Column(name = "ID") private int id;
@Column(name = "MSG") private String message;

public int getId() { return id; }


public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }

Persistent Properties

When using persistent properties, the persistence provider retrieves an objects


state by calling its accessor methods.
Methods must be public or protected.
Methods follow the JavaBeans naming convention.

Overview of the Java Persistence API 1-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Classes

Persistence annotations can only be made on getter methods.

Code 1-3 Persistent Properties


private int id;
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

private String message;

@Id @Column(name = "ID") public int getId() { return id; }


public void setId(int id) { this.id = id; }

@Column(name = "MSG")
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
s a
) h a
m x
Persistence Data Types
t g ob
s a de
Regardless of the use of field-based or property-based a
n access, ui rules
l@ theGsame
er dtoeSQL
apply governing the Java data types that can bebmapped
nt data types. Data
types that can be mapped include:
e s to Stu
Java primitive types ( e rn this
d e z use

r n an e to
Java wrappers, such as java.lang.Integer
H e ens
java.lang.String
l lic
rna band
ebyte[] l e Byte[]
t o B char[]
e ra and Character[]
s
s f
E rne -tran Any serializable types including but not limited to:
s non
C arlo java.util.Date
java.sql.Date
java.sql.Time
java.sql.TimeStamp

1-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Classes

The Concept of a Primary Key


An entity component distinguishes itself and the data it represents from other
entities using a unique ID value known as a primary key. Primary keys have the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

following features:
Give an entity instance its persistent identity. An entity identity is a concept
used by the entity manager, which is discussed later.
Typically are a string or an integer but can also be custom classes that
correspond to several database table columns. The most common table
design is to have an INT column with a UNIQUE constraint.
s a
Are required in every Entity class. On the database side, the primary key
) h a
m x columns might be required to be INDEX columns.
Can have values that are generated automatically
t g ob
s a de
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
n a l@ Gui
private int id;
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens <<customer>>
Database

n l
a e lic Primary Key 102
r
e abl
B
to sfer
Customer Table

e s
rn -tran
102
<<customer>>
E .

rlos non
Primary Key 105 .
.

C a 105
.
<<customer>> .
.
Primary Key 976
976

Figure 1-4 Relationship Between Entity Instances and Table Rows

Overview of the Java Persistence API 1-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life Cycle and Operational Characteristics of Entity Components

Life Cycle and Operational Characteristics of Entity


Components
Besides entity classes, several key concepts must be understood before you can
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

begin leveraging the Java Persistence API. They are:


Persistence Unit
Configuration information in the form of an XML file and a bundle of
classes that are controlled by the Java Persistence API provider.
Entity manager
s a
An entity manager is the service object that manages the lifecycle of the
) h a
m x
entity. This object is the core object that a Java developer uses to create,
retrieve, update, and delete data from a database.
t g ob
Persistence context
s a de
Every entity manager is associated with a persistence
n a l@ G
context. uAi persistence
context is the active set of entities that theb
er dehas
application nt retrieved from the
s to Stu
database or has just created and is manipulating.
e
Persistent identity ( e rn this
d e z use
n a n atunique
The persistent identity is
o value used by the container to map the
entity instance e
er tonotethenbescorresponding record in the database. Persistent
a l
identityHshould
i c confused with Java object identity.
n l
B er able
e s to sfer
E rn -tran
s non
C arlo

1-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life Cycle and Operational Characteristics of Entity Components

Persistence Units
A persistence unit is a collection of entity classes stored in a EJB-JAR, WAR, or
JAR archive along with a persistence.xml file. A persistence unit defines
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

which entity classes are controlled by an entity manager. A persistence unit is


limited to a single data source.

persistence.xml File
Configuration of a persistent unit is controlled by a XML configuration file
named persistence.xml. The persistence.xml file: s a
) h a
m x Configures which classes make up a persistence unit
Defines the base of a persistence unit by its location
t g ob
s a de
Specifies the data source used
n a l@ Gui
<?xml version="1.0" encoding="UTF-8"?>
b e r ent
<persistence version="2.0"
to Stud
e s
e rn this
xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="Auction" (transaction-type="JTA">
d e z use
<jta-data-source>AuctionDS</jta-data-source>
r n an e to
<jar-file>AuctionLibrary.jar</jar-file>
H e ens
<properties/>
n l
a e lic
r
</persistence-unit>
e abl
B
to sfer
</persistence>
e s
E rn -tran
arlos nonPersistence Context
C
A persistence context can be thought of as a working, in-memory copy of a
persistence unit. Several persistence contexts using the same persistence entity
can be active at the same time. A persistence context:
Limits entity instances to a single instance per persistent identity
Has a management API known as the entity manager

Overview of the Java Persistence API 1-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life Cycle and Operational Characteristics of Entity Components

Entity Manager
An entity manager provides methods to control events of a persistence context
and the life cycle of entity instances in a persistence context. An entity manager
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

provides operations such as persist(), find(), and remove() to control a


persistence context

In a Java EE application, an entity manager can be obtained using dependency


injection in managed classes.
@PersistenceContext
private EntityManager em;
s a
) h a
m x Note For more information on using an entity manager in a Java EE
t g ob application, see Using the Java Persistence API in a Container.
s a de
n a l@ Gui
b er dent
e s to Stu
Entity Instance Management rn this
(
z usee
d e
When a reference to an
r n anentitye toand outhasofbeen
manager obtained, you use its methods to
H e ens
marshall entity instance data into the database.
n l
a e lic
r
e abl
B er exceptions that can be thrown by the EntityManager methods are
toNote s fMany
e s
E rn -trnotanrequire
indirect subclasses of java.lang.RuntimeException. IDEs and compilers do

r l o s non try catch blocks around lines of code that cause a


Ca RuntimeException subclass, such as
javax.persistence.EntityExistsException, to be thrown.

Code 1-4 EntityManager Example


1 import javax.persistence.*;
2 import javax.ejb.*;
3
4 @Remote
5 @Stateless
6 public class BrokerModelImpl implements BrokerModel {
7 @PersistenceContext
8 private EntityManager em;
9
10 public Stock getStock(String symbol) {
11 return em.find(Stock.class, symbol);

1-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life Cycle and Operational Characteristics of Entity Components

12 }
13
14 public void addStock(Stock stock) throws BrokerException {
15 try {
16 em.persist(stock);
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

17 }catch(EntityExistsException exe) {
18 throw new BrokerException("Duplicate Stock : " +
19 stock.getSymbol());
20 }
21 }
22
23 public void updateStock(Stock stock) {
24 em.merge(stock); s a
25 } ) h a
26 public void deleteStock(Stock stock) { m x
27 em.remove(stock2);
t g ob
28 } s a de
29 }
n a l@ Gui
b er dent
e s to Stu
Entity States and Entity Manager rn this Methods
(
z use e
d e
n entitiestohave a transitional life cycle. An entity can exist in
a
Java Persistence API
n
one of four e
H
r
e n secontrolled primarily by the entity manager.
states that are

r n al e lic
B e abl
e s to sfer
E rn -tran
s non
C arlo

Overview of the Java Persistence API 1-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life Cycle and Operational Characteristics of Entity Components

Figure 1-5 shows the possible states of an entity instance. The persist, merge,
and remove methods are part of the entity manager API.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
Figure n1-5
l
a Entity licInstance States and the Entity Manager Methods That
r l e
e abControl Them
t o B er
e s s f
E an 1-2 provides a summary of the significance of each entity state shown in
rn -trTable
s non Figure 1-5.
C arlo
Table 1-2 Entity Life-Cycle States

Entity State Significance

New A new instance of the entity created using the new keyword. No corresponding
database record in the persistence tier is associated with the entitys primary key
and the entity instance is not connected to a persistence context.
Managed A corresponding database record is kept synchronized by the persistence
provider with the data in the entity. The entity instance is connected to a
persistence context and has a unique entity identity. Only one managed instance
of an identity can exist in a persistence context.
Detached A corresponding database record exists but data in the record and data in the
entity are not synchronized and the entity instance is not connected to a
persistence context.

1-18 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life Cycle and Operational Characteristics of Entity Components

Table 1-2 Entity Life-Cycle States

Entity State Significance

Removed This state represents a pending removal of the corresponding data record in the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

database.

Table 1-3 shows the entity manager methods or events required to change an
entitys life-cycle state.

Table 1-3 Changing Entity Life-Cycle States

Old Entity New Entity s a


State
Required Operation
State ) h a
m x
Does not exist Use the new operator to create a new instance.
t ob
New
g
New Use the entity managers persist operation. s a Managed
d e
al@ t GuRemovedi
Managed Use the entity managers remove operation.ern n
o b d e
Managed st ending.
The consequence of the persistenceecontext
n S tu Detached
e
Instances generated by serialization
( h is of managed
r or tcloning
z
de to us
instances are always detached. e
Removed Use the entityrn a n

managersepersist operation. Managed
e
Hreference n s
e to the removed instance.
Removed
n a
Delete l the l i c Nonexistent
r
e ab l e
t o B er
e s s f
E rn -tran
s non
C arlo

Overview of the Java Persistence API 1-19


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life Cycle and Operational Characteristics of Entity Components

Entity Manager Methods


Table 1-4 shows several useful entity manager methods.

Table 1-4
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Changing Entity Life-Cycle States

Entity
Manager Comment
Method

flush Forces the synchronization of the database with entities in the persistence
context.
s a
refresh Refreshes the entity instances in the persistence context from the database.
) h a
m x
find
t g ob
Finds an entity instance by executing a query by primary key on the database.
contains a signifies
Returns true if the entity instance is in the persistence context.sThis
d e that
the entity instance is managed. al@ t Gu i
r n
e persistence
n context.
merge b
Merge the state of the given entity into the current
o d e
n e st S tu
(er e this
remove Remove the entity instance.
persist Make an entity instance d z
e and
managed u spersistent.
n
o
e rna nse t
n a l H lice
B er able
e s to sfer
E rn -tran
s non
C arlo

1-20 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Deploying Entity Classes

Deploying Entity Classes


This section examines the issues and tasks associated with deploying entity
classes. Note the following information.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

To deploy entity classes, you are required to create a persistence unit.


A persistence unit is a logical grouping of all the elements required by the
container to support the persistence management of an application.

Table 1-5 shows the list of required components of a persistence unit.

Table 1-5 Components of the Persistent Unit s a


) h a
Persistence Unit Component m x
Comment

t g ob
Entity classes with object a
Defines what is persisted
s and themapping
e database
/relational mapping metadata l @ classes
between the managed
a u idand
tables. rn
e n t G
t b de unit.
o thetupersistence
A persistence.xml file sDefines
ne his S
( e r t
e z
d to u
For deployment to a Java EE s e
application server, the components of the
a n

rnmustnbesplaced
persistence unit
e e in one of the following locations:
l HIn anliEAR
a c e file
n
er abInlean EJB-JAR file
B
to sfer
e s
E rn -tran In a WAR file
s non
arlo
In an application client JAR file
C The following table lists the locations where the components of the
persistence unit should be placed.

Table 1-6 Default Locations for Persistence Unit Components

Persistence Unit
Default Location
Component

All Managed (entity) classes In directories that map the package structure of the managed
classes. The directory path root is the root of the JAR file.
Object relational mapping
metadata Included as annotations in the entity classes. An alternative to
annotations is an XML object-relational mapping file usually
named orm.xml.
persistence.xml file In the META-INF directory off the root of the JAR file.

Overview of the Java Persistence API 1-21


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Deploying Entity Classes

A Persistence Unit in a Java EE Application


Figure 1-6 shows an example of persistence unit components in default settings
within an EJB-JAR file. It also shows other components of an EJB-JAR archive.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

(/ ) Root
META-INF
ejb-jar.xml
persistence.xml MANIFEST.MF
auctionsystem
ejbs
entity
AuctionManagerBean.class
s a
AuctionManagerRemote.class ) h a
Auction.class
m x
ob
AuctionManagerLocal.class
AuctionUser.class
t
a de g dtos
Bid.class s
BidStatusMessage.class

n a l@ Gui
PlaceBidMessage.class
Item.class
b er dent
Persistence Components e s to Stu
( e rn this
Figure 1-6
e z usUnit
Example of Persistence
d e Components in Default Settings
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

1-22 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining a Persistence Unit Using Non-Default Settings

Examining a Persistence Unit Using Non-Default Settings

Note This section describes the optional task of using non-default settings to
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

create a persistence unit. For the vast majority of situations, using the defaults
should be sufficient. The Java Persistence API 2.0 provides new APIs to control
cache behavior.

Code 1-5 persistence.xml File With Non-Default Settings


1 <?xml version="1.0" encoding="UTF-8" ?>
2 <persistence version="2.0" s a
xmlns="http://java.sun.com/xml/ns/persistence" ) h a
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" m x
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
t g ob
s a de
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
3
n a l@ Gui
4 er dent
<persistence-unit name="BrokerTool-ejb" transaction-type="JTA">
b
5 to Stu
<jta-data-source>StockMarket</jta-data-source>
e s
6
rn this
<jar-file>BrokerLibrary.jar</jar-file>
( e
7
z use
<mapping-file>mapping.xml</mapping-file>
d e
an e to
8 <properties>
9 r n
<property name="eclipselink.cache.type.default" value="NONE"/>
e ens
10 l H </properties>
a e lic
r n
11
e abl </persistence-unit>
B
to sfer
12 </persistence>
e s
E rn -tran The JAR files off the root directory
s non
arlo
The JAR files off the root directory are optional. They are an alternative
C method for the developer to provide the managed set of entity classes.
Every JAR file provided requires a corresponding jar-file element in the
persistence.xml file. The presence of the jar-file elements in the
persistence.xml file prompts the application server to load the classes
archived in the JAR file.
The mapping XML files off the root directory
The mapping XML files off the root directory are an alternative location for
the object/relational mapping information. These mapping files require a
corresponding mapping-file element in the persistence.xml file.
The mapping XML files are optional. All mapping information can be
supplied through the appropriate annotations in the entity class.
<properties> are used to pass configuration information to the
persistence provider.

Overview of the Java Persistence API 1-23


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining a Persistence Unit Using Non-Default Settings

Using Java Persistence API in Java SE Applications


The examples so far in this module assume that the Java Persistence API is being
used in a Java EE application that uses EJBs. Using the Java Persistence API in
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

this context has the following benefits:


Transactions are taken care of automatically.
Less configuration is necessary because the persistence unit is using a
preconfigured DataSource for database access.
Dependency injection is used to obtain an EntityManager or an
EntityManagerFactory reference.
s a
) h a
m x The Java Persistence API can also be used in non-EJB Java EE applications

t g ob composed of servlets or web services. In addition, the Java Persistence API can
be used in Java SE applications.
s a de
n a l@ G ui
b er dent
To use the Java Persistence API in Java SE applications, you must:

s
Set the transaction-type to RESOURCE_LOCAL
e to Sintuyour persistence unit
definition in persistence.xml.
( e rn this
e z provider
Explicitly set the persistence
d u s e in persistence.xml.
r n anclassese intopersistence.xml.
List all the entity
l
Addaproperties
ns
He icforeconfiguring

r n l e l the JDBC data source in
B epersistence.xml.
ab
t o f e r
r n es ransManually control transactions in your application code.
s E n-t
ar l o no Code 1-6 API Example persistence.xml File for a Java SE Java Persistence
C Application
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
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">

<persistence-unit name="StockPU" transaction-type="RESOURCE_LOCAL">

<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>trader.Stock</class>
<class>trader.Customer</class>
<class>trader.CustomerShare</class>
<properties>

1-24 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining a Persistence Unit Using Non-Default Settings

<!-- useful log levels include OFF,FINE,SEVERE -->


<!-- useful ddl-generation values include
create-tables and drop-and-create-tables -->
<property name="javax.persistence.jdbc.user" value="public"/>
<property name="javax.persistence.jdbc.password"
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

value="public"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:MyDB;create=true"/>
<property name="javax.persistence.jdbc.driver"
value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="eclipselink.ddl-generation"
value="drop-and-create-tables"/>
<property name="eclipselink.logging.level" s a
value="SEVERE"/> ) h a
</properties> m x
</persistence-unit>
t g ob
</persistence> s a de
n a l@ Gui
b er dent
Note This persistence.xml file uses
e s to the S tu the Derby
embedded database driver

e r n his
which automatically starts a database instance within same JVM as the
application. z ( e t
e
nd to u s
n a
r nse Obtaining an EntityManager and Manually
Code 1-7He Programmatically
a l Controlling
l i c e Transactions
n
er abemf le
t B
o sfer
EntityManagerFactory =
s
E rne -tranem = emf.createEntityManager();
Persistence.createEntityManagerFactory("StockPU");
EntityManager
s non
C arlo EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
// ...
entityTransaction.commit();

Note For more information on using transactions with Java Persistence API, see
Implementing Transactions and Locking.

In order to use Java Persistence API in a Java SE application, several JAR files
must be added to a project. In the CLASSPATH, the application will require the
following files:
The library JAR files that contain the persistence provider. Both Hibernate
and EclipseLink can be freely downloaded.

Overview of the Java Persistence API 1-25


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining a Persistence Unit Using Non-Default Settings

The library JAR files to satisfy any required dependencies of the persistence
provider. Multiple dependencies might need to be met. Hibernate requires
several additional library JAR files.
A running database and its JDBC driver. Derby, also known as the Java DB,
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

is a popular choice for small databases because of its portability and


embedded option.

Note For more information on Java DB, see Appendix A.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

1-26 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 2
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Introducing the Auction Application

Objectives a
h a s
x )
Upon completion of this module, you should be able to: m
t g ob
Describe the auction application
s a de
a l@ Gui
Define the domain objects of the auction application
n
b ether auction
e n t
to Stud
Describe the implementation model for system
e s
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

2-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
None.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

2-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Auction Application Use Cases

Auction Application Use Cases


The auction system provides a problem domain that is easily understandable,
allows for end-to-end development during labs, and still has enough complexity
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

to illustrate complex activities associated with creating a Java EE application.


The auction application is similar to many existing online auction systems.

The auction system views users as one of the following user types (actors):
Seller
Bidder
s a
Administrator
) h a
m x
Figure 2-1 shows the actors and the use cases associated with each
t g obactor.
s a de
n a l@ Gui
er dent
Creates

b
to Stu
Auction

Seller
e s
( e rn this
d e z use
r n an e to Closes

H e ens Auction

n l
a e lic
r
e abl
Administrator

B
to sfer
e s
E rn -tran Bids on
s non
arlo
Auction

C Bidder

Figure 2-1 Auction Application Use Cases

The auction application must implement the following use cases:


Create-auction use case The create-auction use case is executed by the
seller. The seller creates an auction by placing an item for sale. The seller
specifies the start amount. In addition, each auction has a start time, close
time, and bid increment.

Introducing the Auction Application 2-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Auction Application Use Cases

Close-auction use case The close-auction use case is executed by the


seller and administrator. The administrator can withdraw any auction.
Sellers can withdraw only auctions they create.
Bid-on-auction use case The bid-on-auction use case is executed by the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

bidder. For a bid to be accepted, it must be greater than the sum of the
current highest bid by at least the bid increment amount.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

2-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

Analyzing the Auction System


This section analyzes the auction system and describes the domain objects in the
simplified auction system used in the lab exercises. It also describes the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

relationships among the domain objects.

Auction Application Domain Objects


Figure 2-2 illustrates the domain objects of the auction application and the
relationships among the domain objects.
s a
) h a
Item
item
Auction
auction
m x
1 1 1
*tg
ob
bids
*
auctions s a de
n a l@ GBid ui
seller
b er dent *
1
e s t1o Stu bids
r n i s
BookItem
(e e thbidder
AuctionUser
z
Figure 2-2 a n

Auction
deApplications
t o us Data Relationship Model
e rn nse
n a l H system
l i c ehas many design decisions made with the idea of extensibility
B einrmind.aFor
The auction
b leexample, the Auction object and the Item object have a one-to-one
e s s er and they could feasibly be combined. In a more robust auction
to relationship,
f
E rn -transystem, an unsold item could be re-auctioned. Keeping the item as a separate
s non
arlo
entity enables you to set up re-auctions more easily.
C
Note A more realistic domain model of an auction system is significantly more
complex and includes some kind of credit authorization model and corresponding
domain objects, such as credit cards or bank accounts.

Introducing the Auction Application 2-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

The auction application is modeled using the following domain objects:


The Auction domain object This object represents a single online
auction within the auction system. Each Auction object has an association
with a seller, an item, and a collection of bids.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The AuctionUser domain object This object represents either a seller or


a bidder within the auction system. Each AuctionUser object has an
association with a credit card, a shipping address, a collection of auctions,
and bids that the auction users have placed.
The Bid domain object This object represents a purchase offer on an
auction sale item. Each Bid object is associated with a bidder
(AuctionUser) and an auction.
s a
h a

x)
The Item domain object This object represents the article offered for sale
m
ob
in an auction.
t
a de g
s
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

2-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

Auction Domain Object


Figure 2-3 illustrates the Auction domain object.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Auction

auctionID : Integer
startAmount : double
item increment : double auction
Item
1 1 status : String 1
openTime : Date bids
*
closeTime : Date
Bid
s a
...
) h a
*
auctions m x
BookItem
t g ob
seller s a de
1
n a l@ Gui
AuctionUser
b er dent
e s to Stu
Figure 2-3 Auction Domain
( e rnObjectthis
d e z use
n
The Auction domain
r an object
e torepresents a single online auction within the auction
H
application.
l c e ns domain object contains the following attributes:
eThe Auction
a e li attribute A unique identity for the Auction object.
rn auctionID
B e a b l
s r
to sfestartAmount attribute The start amount specified by the seller.
n e n
s Er n-tra increment attribute The minimum bid increment.
C arlo no status attribute The auction status. Status values are OPEN, CLOSED,
CANCELLED.
openTime attribute The start time of the auction.
closeTime attribute The close time of the auction.

Introducing the Auction Application 2-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

Each Auction domain object contains relationships with other domain objects.
These relationships are represented by the following associations:
item relationship The item for sale in the auction.
seller relationship The AuctionUser object that is selling the item.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

bids relationship The collection of bids placed on the auction.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

2-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

AuctionUser Domain Object


Figure 2-4 illustrates the AuctionUser domain object.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

item auction
Item Auction
1 1 1
bids
* auctions *

seller Bid
1
AuctionUser *
bids
auctionUserID : Integer
s a
displayName : String
) h a
BookItem email : String
m x 1

... t g ob bidder

s a de
Figure 2-4 AuctionUser Domain Object
n a l@ Gui
b er dent
s
The AuctionUser domain object represents
e to eitherS tua seller or a bidder within the
e r n
auction application. The AuctionUser is
domain
h object maps to both the seller
(
z application t
e use cases. The AuctionUser domain
object contains the n d e
and bidder roles in the auction
u s
r n a following
e toattributes:
H e ensattribute A unique identity for the auction user.
auctionUserID
l
a e lic attribute The display name of the auction user.
ern displayName
l
B a b
r attribute The email address of the auction user.
e s to sfeemail
E rn -tran
s non
arlo
Each AuctionUser domain object contains relationships with other domain
C objects. These relationships are represented by the following associations.
auctions relationship The auctions in which the auction user has
participated as a seller.
bids relationship The collection of bids placed by the auction user.

Introducing the Auction Application 2-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

Bid Domain Object


Figure 2-5 illustrates the Bid domain object.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

item auction
Item Auction
1 1 1 bids
* *
auctions
Bid
bidID : Integer
amount : double
bidTime : long
s a
approval : String
) h a
m x ...
ob
seller
1
1
*
t
a de
bidsg
s
BookItem AuctionUser
bidder
n a l@ Gui
Figure 2-5 Bid Domain Object b er dent
e s to Stu
The Bid domain object represents ( e rn thoffer
a purchase
is on an auction sale item. Each
z
de twith
Bid domain object is associated
e
uasbidder (AuctionUser) and an auction.
a n
o
e rn contains
The Bid domain object
n s e the following attributes:
a
bidID
n lH l
attribute i ceA unique identity for the bid.
r le The bid amount.
Beamount a b
e s to sfer attribute

E rn -tran bidTime attribute The time the bid was made.


arlos non approval attribute The sufficient funds availability check authorization
C code associated with the bid.

Each Bid domain object contains relationships with other domain objects. These
relationships are represented by the following associations:
auction relationship The auction associated with the bid.
bidder relationship The auction user who placed the bid.

2-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

Item Domain Object


Figure 2-6 illustrates the Item domain object.

item auction
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Item
Auction
itemID : Integer 1 1 1
bids
description : String * *
image : String auctions
Bid
...
1 *
seller bids

1 s a
BookItem AuctionUser
) h a
m x bidder

Figure 2-6 Item Domain Object t g ob


s a de
n a l@ Gui
r eforntsale in an auction. The
The Item domain object represents the articleeoffered
b
Item domain object contains the following
to Stud
attributes:
e s
e rn identity
itemID attribute A unique
( thisfor the item.

z
de to The
description attribute e
us items description.
a n

rn nsThe
imageeattribute e location of an image of the item.
H
al e lic e
r n
e abl
B
to sfer
e s
E rn -tran
arlos non
C

Introducing the Auction Application 2-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Analyzing the Auction System

BookItem Domain Object


Figure 2-7 illustrates the BookItem domain object.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

item auction
Item
1 1
Auction
1 s a
*
bids
) h a

*
m xauctions

BookItem
t g ob
Bid

1
seller
s a * de
title : String
n a l@
1
G ui bids
er debidder
nt
author : String
AuctionUser
...
to Stub
e s
Figure 2-7 BookItem DomaineObject
( rn this
d e z use
The BookItem domain
r n anobjecterepresents
to the book item. It inherits from the Item
H
domain object. e
The n s
BookItem
e domain object contains the following attributes:
l c
li The title of the book.
rna attribute
etitle l e
t o B erab
e s nsauthor
f attribute The name of the author of the book.
n
Er n-tra
s
C arlo no

2-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Implementation Model

Examining the Implementation Model


Figure 2-8 illustrates the preliminary design of the auction system
implementation.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Client Tier Middle Tier EIS Tier

Business Core Persistance


Service

s a
request
) h a
m x <<session bean>>
entities
ob
AuctionManagerEJB

t
a deg
response
s
AuctionManagerHelper
n a l@ Gui
er dent
Client
b
to Stu
e s
Figure 2-8 Auction System ( e rn thisDesign
Preliminary
d e z use
r n
The auction system anis based
e o the Java EE technology and the EJB technology
ton
l H eThe middle
architecture.
c e nstier consists of a business core and persistence service.
a ecore
rnbusiness
The l li consists of EJBs and helper classes that implement the auction
e ab business logic. The persistence service consists of persistence
B applications
t o f e r
r n es ranentities.
s Persistence entities are objects that represent data stored in the Enterprise
s E n-t Information Service (EIS) tier (database).
arlo no
C
Middle-Tier Subsystems
The primary client interface object in the business core is the AuctionManager
session bean. The AuctionManager functions as a session facade. It receives
requests such as add auction or place bid from the client tier. These requests are
processed with the assistance of helper objects such as the
AuctionManagerHelper and persistence entities. The results are then returned
to the client.

Introducing the Auction Application 2-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Implementation Model

Figure 2-9 illustrates the persistence entities used by the auction application.

Business Core

<<entity>> item <<entity>> auction


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Item 1 1 Auction 1
bids
* *
auctions
<<entity>>
Bid
seller
1 *
1 bids
<<entity>> <<entity>>
BookItem AuctionUser bidder
s a
) h a
m x
Figure 2-9
t g ob
Business Core Implementation

s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

2-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 3
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Java Persistence API Entities

Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
Describe the difference between objects and entities atg
ob

s d e
al@
Describe the difference between persistent fields u i
and properties
r n t G
e APIdannotations,
n

Identify and use common Java Persistence
t o b u e such as
@Entity, @Id, @Table, and e s
@Column S t
e r n h i s
z ( e t
e
nd to u s
n a
H er ense
r n al e lic
B e abl
e s to sfer
E rn -tran
arlos non
C

3-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September
15, 2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

3-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entities

Understanding Entities
An entity is a lightweight persistent domain object.
JavaBean components are objects that live short-term in memory.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Entities are JavaBeans components that live short-term in memory, but also
are persistent so that they live beyond the application life cycle.

The Java Persistence API defines the entity class as the object tier equivalent of a
table in the database tier. An entity instance is defined as the object tier
equivalent of a row in a database table.
s a
Table 3-1 Mapping Object Tier Elements to Database Tier Elements ) h a
m x
Object Tier Element Database Tier Element
t g ob
s a de
Entity class Database table
n a l@ Gui
Attribute of entity class Database tableb
er dent
column
Entity instance e
Database s to Stu
table row
( e rn this
d e z use
r n an e to
Note An H e may
entity
e s
ncorrespond to more than one table in the database, and an
l
nainstance
entity c
li be persisted in more than one row in the table. These
may
e r l e
b be more fully explored throughout the course.
t o B concepts
e r awill
es rans f
r n
E n-t
l o s no Object Tier and Data Tier Static and Dynamic Mapping
C ar
Example
This section shows an example of the static and dynamic relationships between
elements in the object and data tiers.

Java Persistence API Entities 3-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entities

Figure 3-1 and Figure 3-2 illustrate the relationship that exists between the data
tier and the object tier. Figure 3-1 shows three tables in the database tier.
Auction Table

Auction ID Seller Item StartAmount Increment ...


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Bid Table

BidID Auction Bidder Amount BidTime Authorization

s a
) h a
m x
t g ob
s a de Item Table

n a l@ Gui ItemID Description Image

b er dent
e s to Stu
Figure 3-1 (
Static Relationship e rn is
Mappingt-hData Tier Elements
z
de to us e
an

e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C

3-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entities

Figure 3-2 shows three entity classes in the object tier that correspond to the
tables from the data tier shown in Figure 3-1. You should observe the
correspondence between the fields of the entity classes shown in Figure 3-2 and
the columns of the tables shown in Figure 3-1.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

<<entity>> <<entity>>
Auction Bid

auctionID : Integer bidID : Integer


seller : AuctionUser auction : Auction
item : Item bidder : AuctionUser s a
startAmount : double amount : double ) h a
increment : double m x
bidTime : Date
... g ob
authorization : String
t
s a de
n a l@ Gui
b er dent
<<entity>> es
to Stu
Item(er
n his
z e t
e
nd to u s
n a e
H er e:nsInteger
itemID
r n al description
e lic : String
e
B erab l
image : String
t o
s nsf
n e
s Er n-tra Figure 3-2 Static Relationship Mapping - Object Tier Elements
C arlo no

Java Persistence API Entities 3-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entities

Figure 3-3 illustrates the dynamic relationship consisting of data synchronization


between the object and data tiers. The data synchronization service is provided by
the persistence provider through one or more entity manager objects.

Container
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Item Table
:Item
ItemID Description Image
itemID : 32
description : Drum 32 Drum drum.gif
image : drum.gif

Entity
s a
) h a
m x
With entities, the data synchronization is maintained by the persistence provider.
t g ob
s a de
Figure 3-3 Dynamic Relationship - Object/Data Tier lData
a @ Gui
Synchronization
n
er dent

to Stub
e s
( e rn this
z e
Defining an Entityande to us
e rn nse
l Hmeetlictheefollowing conditions:
An entityamust
n
B eItr mustabbeleannotated with the @Entity annotation or denoted in the XML
e s to sdescriptor

f er as an entity
E rn -tran
arlos non
C Note If both annotations and XML descriptors are used in an application, the
XML descriptor takes precedence.

It must have a public or protected no-arg constructor. Other constructors are


allowed but will not be used by the Java Persistence API.
It must be a top-level class. An enum, interface, or inner class must not be
designated as an entity.
It must not be declared final. No methods or persistent instance variables of
the entity class may be final.

3-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entities

Entities Using the @Entity Annotation

Entities are most commonly identified using the @Entity annotation when
declaring the class. Code 3-1 demonstrates an entity class using annotations.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 3-1 Entity Class Using @Entity


1 import javax.persistence.*;
2
3 @Entity
4 public class Item{
5 @Id
6 private int itemId; s a
7 private String description; ) h a
m x 8
public int getItemId() { return itemId; }
t g ob 9
public void setItemId(int itemId){ s a de 10
this.itemId = itemId;
n a l@ Gui 11
}
b er dent 12
public String getDescription() { return
e s to description;
S tu { } 13
public void setDescription(String
( e rn this
description) 14
this.description = description;
d e z use 15

an e to
} 16
} r
e ensn 17
l H
Byrn a the
default, l e lic Persistence API assumes that entity names and table names
Java
B ematch. Toabmap an entity to a non-matching table name, use the @Table
t o f e r
r n es ranannotation.
s Code 3-2 demonstrates using the @Table annotation.
s E n-t
ar l o no Code 3-2 Using the @Table Annotation
C
1 import javax.persistence.*;
2
3 @Entity
4 @Table(name = AUCTION_ITEMS)
5 public class Item{
6 //...
7 }

Entities Using the XML Descriptor

Entities may also be defined in a file typically named orm.xml, although this file
can be named anything. Code 3-3 demonstrates using an XML descriptor to
describe an entity.

Java Persistence API Entities 3-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entities

Note Due to the additional work of keeping two files in sync - the entity and the
XML descriptor - many Java Persistence API developers favor using annotations.

Code 3-3 Entity Class in orm.xml


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

1 <?xml version="1.0" encoding="UTF-8" ?>


2 <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
5 http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
6 version="2.0">
7 <description>The Auction application</description> s a
8 <package>com.yourcompany</package> ) h a
9 <entity class="com.yourcompany.Item" name="Item"> m x
10 <table name="ITEM"/>
t g ob
11 <attributes> s a de
12 <id name="itemId">
n a l@ Gui
13
b er dent
<generated-value strategy="TABLE"/>

14 </id>
e s to Stu
15 rn this
<basic name="description">
( e
16
d z use
<column name="DESCRIPTION" length="100"/>
e
17
r n an e to
</basic>
18
H e ens
</attributes>
19
n l
a e lic
</entity>
r l
e the orm.xml
b
t B
o sfer
Once a file is written, it must be referenced in the
s
E rne -trpersistence.xml
an file using the mapping-file element.
s non
C arlo Note The mapping-file element is not required if the default orm.xml
filename is used and is included in the META-INF directory.

Code 3-4 Referencing orm.xml in persistence.xml


1 <?xml version="1.0" encoding="UTF-8" ?>
2 <persistence xmlns="http://java.sun.com/xml/ns/persistence"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
5 http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
6 version="2.0">
7
8 <persistence-unit name="Auction">
9 <mapping-file>com/yourcompany/orm.xml</mapping-file>
10 <class>com.yourcompany.Item</class>

3-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entities

11 </persistence-unit>
12
13 </persistence>
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note For more on persistence.xml, see Understanding the Entity


Manager.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Java Persistence API Entities 3-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistent Fields and Properties

Persistent Fields and Properties


The persistent state of an entity is accessed by the persistence provider runtime
either through JavaBeans style property accessors (property access) or through
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

instance variables (field access).

Note The persistent fields and properties of an entity class are generically
referred to as the attributes of the class.

By default, a single access type (field or property access) applies to an entity


s a
hierarchy. When annotations are used to define a default access type, the
) h a
m x placement of the mapping annotations on either the persistent fields or persistent

t g ob properties of the entity class specifies the access type as being either field-based
or property-based access respectively.
s a de
a
When field-based access is used, the object/relational
n l@mapping
G uiannotations
b er dThe
for the entity class annotate the instance variables.
e t
npersistence provider

e s to Stu
runtime accesses instance variables directly.
When property-based accesseisrn used, the s
hiobject/relational mapping
z ( e t
n
d e classuannotate
annotations for the entity s the getter property accessors. The
r n a et
persistence provider runtimeo accesses persistent state through the property
e eThe
accessor methods.
H n ssetter property must not be used for property-based
l c
e rna ble li
access.

t o B era
n e s Notens fTo exclude a field or property from being persisted, use the @Transient
a
Er n-trannotation.
rlo s no
C a

Field-Based Access
When you place annotations on the instance variables, the Java Persistence API
will use field-based access. The Java Persistence API will use the field directly
when accessing the entity, bypassing the getter method.

Note The @Id annotation is discussed in greater detail in Primary Keys and
Entity Identity.

Code 3-5 Entity Class Using Field-Based Access

3-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistent Fields and Properties

1 import javax.persistence.*;
2
3 @Entity
4 public class Item{
5
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

6 @Id
7 private int itemId;
8 private String description;
9
10 public int getItemId() { return itemId; }
11 public void setItemId(int itemId){
12 this.itemId = itemId;
13 } s a
14 public String getDescription() { return description; } ) h a
15 public void setDescription(String description) { m x
16 this.description = description;
t g ob
17 } s a de
} 18
n a l@ Gui
b er dent
e s to Stu
Property-Based Access rn
z (e e this
a n
de ton
When you place annotations o usproperty accessor methods, the Java
the
e
Persistence APIrnwill use
n seproperty-based access. The Java Persistence API will
H e
algetteremethod
use the
r n l lic when accessing the entity.
B e ab
e s t o s f er
E rn -tranon setter
Note Only getter methods may be used for property-based access. Annotations

r l o s non methods are not allowed.


C a
Code 3-6 Entity Class Using Property-Based Access
1 import javax.persistence.*;
2
3 @Entity
4 public class Item{
5
6 private int itemId;
7 private String description;
8
9 @Id
10 public int getItemId() { return itemId; }
11 public void setItemId(int itemId){
12 this.itemId = itemId;
13 }

Java Persistence API Entities 3-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistent Fields and Properties

14 public String getDescription() { return description; }


15 public void setDescription(String description) {
16 this.description = description;
17 }
18 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

3-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Attributes

Attributes
The instance variables of a class must be set for private, protected, or package
visibility regardless of whether field access or property access is used. When
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

property access is used, the property accessor methods must be public or


protected.

The persistent fields or properties of an entity may be of the following types:


Java primitive types such as boolean, double, float, and int and the
corresponding wrapper classes such as Boolean, Double, Float, and
Integer
s a
Serializable types such as java.lang.String, ) h a
m x java.math.BigDecimal, and java.math.BigInteger
t g ob
Arrays of bytes and characters such as byte[], Byte[],
s a dechar[], and
Character[]
n a l@ Gui
Temporal types such as java.util.Date,
b er java.util.Calendar,
e n t
java.sql.Date, java.sql.Time,
e s tud
to andSjava.sql.Timestamp
Enums
( e rn this
Collections d e z use
n
Other e rna nse to
entities
n a l H lice
B er able
e s to Note
s f erFor more information on persisting Enums and Collections, see Entity
E rn -tran Classes: Persisting Enumerations and Collections.

arlos non
C
@Column Annotation
By default, all attributes of an entity will be persisted to a column that matches
the attribute name. To override this setting, use the @Column annotation.

Code 3-7 Using the @Column Annotation


1 import javax.persistence.*;
2
3 @Entity
4 public class Item{
5
6 @Id
7 private int itemId;

Java Persistence API Entities 3-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Attributes

8 private String description;


9 @Column(name=IMAGE_URL)
10 private String image;
11
12 // ...
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

13 }

The @Column annotation has many elements that can be used to further refine the
attribute mapping to the underlying column.

Table 3-2 Elements of the @Column Annotation

Name Type Default Description s a


) h a
columnDefinition String Generated SQL m x
The SQL fragment used when

to create a
t g ob
generating the DLL for the
column of the
s a de column

n a l@ Gui
inferred type
insertable boolean true
Whether b ercolumn
the
d e is tincluded in
n
e s
SQLtoINSERTS tustatements
( e rn generated
t h is by the persistence
d e z usprovider
e
length int r n
255an e to The column length of string-based
H e ens columns
a l l i c
name
B ernString
a b le The property or The name of the column
e s to sfer field name
r n r a n
s E n-t
nullable boolean true Whether the column is nullable
r l o
a precision n o
C int 0 The precision for a decimal (exact
numeric) column
scale int 0 The scale for a decimal (exact
numeric) column
table String Column is in The name of the table
primary table
unique boolean false Whether the property is a unique
key
updatable boolean true Whether the column is included in
SQL UPDATE statements
generated by the persistence
provider

3-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Attributes

Note The elements of the @Column annotation are also valid attributes of the
column element in the XML descriptor.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

@Transient Annotation
By default, all attributes will be persisted unless flagged with the @Transient
annotation. Transient attributes are fully accessible for in-memory usage;
however, they will not be saved by the Java Persistence API.
s a
Code 3-8 Using the @Transient Annotation ) h a
m x
1 import javax.persistence.*;
t g ob
2
s a de
3 @Entity
n a l@ Gui
4 public class Item{
b er dent
5
6 @Id e s to Stu
7 private int itemId; ( e rn this
8 private String description; d e z use
9 private String image;
r n an e to
10 @Transient H e ens
11 n
private booleanl lic
a temporarilyOnHold;
r
e ab l e
12 B
t ... sfer
o
13
e s
//
n tran
14 r}
E
s non-
ar l o
C
@Temporal Annotation
The underlying data type for java.util.Date or java.util.Calendar attributes
must be refined using the @Temporal annotation. Data of type java.sql.Date
does not require the @Temporal annotation.

The @Temporal annotation accepts a value of TemporalType enum.

Java Persistence API Entities 3-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Attributes

Table 3-3 Acceptable Values for the @Temporal Annotation

Value Description
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

TemporalType.DATE Maps as java.sql.Date


TemporalType.TIME Maps as java.sql.Time
TemporalType.TIMESTAMP Maps as
java.sql.Timestamp

s a
Code 3-9 Using the @Temporal Annotation
) h a
1 import javax.persistence.*; m x
2
t g ob
@Entity 3 s a de
4
public class Item{
n a l@ Gui
5
b er dent
@Id 6
e s to Stu
7
private int itemId;
private String description; z (e
rn this
8
d e u s e
9
private String image;
10 r n an e to
@Temporal(TemporalType.DATE)
H e ens
11 l
a e lic
private Date manufactureDate;
n
r
12 l
@Temporal(TemporalType.TIMESTAMP)
e lastUpdated;
b
private B
to sfer
13
Date a
s
//e...
rn -tran
14
E
}
s non 15

C arlo
@Access Annotation
You can override default field-based or property-based access on a per attribute
basis using the @Access annotation. The @Access annotation accepts a value of
AccessType enum.

Table 3-4 Acceptable Values for the @Access Annotation

Value Description

AccessType.FIELD Specifies field-based access


AccessType.PROPERTY Specifies property-based access

3-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Attributes

If an entity class mixes field and property access, add a class-level @Access
annotation to define the default access type of the entity class, and additional
@Access annotations to the individual persistent fields or properties for the
exceptions to the default access type.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

When @Access(AccessType.FIELD) is applied to an entity class, you


can selectively designate individual attributes within the class for property
access. To specify a persistent property for access by the persistence
provider runtime, that property must be designated
@Access(AccessType.PROPERTY).
When @Access(AccessType.PROPERTY) is applied to an entity class,
you can selectively designate individual attributes within the class for
s a
instance variable access. To specify a persistent instance variable for access
) h a
m x
by the persistence provider runtime, that instance variable must be
designated @Access(AccessType.FIELD).
t g ob
s a de
a
Note When access types are combined within a class,
n l@the G ui
@Transient
b r emappings.
epersistent n t

annotation should be used to avoid duplicate
to Stud
e s
Code 3-10 Using the @Access ( e rnAnnotation
this
z
de to us e
1 import javax.persistence.*; a n

2 e rn nse
3 @Entity
n a l H lice
4
B er able
@Access(AccessType.FIELD) //using field-based access
5 publico
st nsfe
class r
Item{
6 rne
s7E n
@Id- tra
C arlo 8 noprivate int itemId;
9 private String description;
10 private String image;
11 @Transient //this field will be ignored
12 private Date manufactureDate;
13
14 //for this attribute, property-based access will be used
15 @Access(AccessType.PROPERTY)
16 public Date getManufactureDate(){
17 return manufactureDate;
18 }
19
20 // ...
21 }

Java Persistence API Entities 3-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Primary Keys and Entity Identity

Primary Keys and Entity Identity


Every entity must have a primary key, a way to uniquely identify the entity. A
primary key corresponds to one or more fields or properties of the entity class.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

A simple non-composite primary key must correspond to a single persistent


field or property of the entity class. The @Id annotation or <id> XML
element must be used to denote a simple primary key.
A composite primary key must correspond either to a single persistent field
or property or to a set of fields or properties. A primary key class must be
defined to represent a composite primary key. Composite primary keys
typically arise when mapping from legacy databases where the database key s a
is comprised of several columns. The @EmbeddedId or @IdClass ) h a
m
annotation is used to denote a composite primary key. x
t g ob
s a de
Note For more on composite primary keys, see Advanceda l@ Java i
uPersistence
API Concepts. n
er dent G
b
to Stu
e s
( e
The value of its primary key uniquelyrnidentifies
t hisan entity instance within a
z
e manager
persistence context and todentity u e
s operations. The application must not
n
o
e rna primary
change the value of the
s e tkey, as undefined behavior can occur.
a l H icen
rn blekey
A simple primary l of an entity should be one of the following types:
e
t o B Java e a
rprimitive
e s s f types such as long or int and the wrapper classes such as

E rn -tran primary keys. In general, floating point types should never be used in
Long or Integer.
s non
C arlo Serializable types (java.lang.String, java.math.BigInteger)
Temporal types (java.util.Date or java.sql.Date)

Note If java.util.Date is used as a primary key field or property, the


@Temporal annotation should be specified as TemporalType.DATE.

@Id Annotation
The @Id annotation specifies the primary key property or field of an entity.

3-18 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Primary Keys and Entity Identity

Note If the @GeneratedValue annotation is not applied to the @Id attribute,


the application developer must ensure that only unique values are provided for
the primary key.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 3-11 Using the @Id Annotation


1 import javax.persistence.*;
2
3 @Entity
4 public class Item{
5
6 @Id s a
7 private int itemId; ) h a
8 // ... m x
} 9
t g ob
s a de
n a l@ Gui
@GeneratedValue b er dent
e s to Stu
The @GeneratedValue annotation( e rn provides
t his for the specification of generation
z e
strategies for the valueseof primaryskeys. The @GeneratedValue annotation
d o uproperty or field of an entity in conjunction with
may be applied toaanprimary tkey
n
er eThe e of the @GeneratedValue annotation is required to
suse
the @Id annotation.
H n
al eonly
be supported
r n licfor simple primary keys.
B e ab l
s o
t The f r
e@GeneratedValue
r n e a n s annotation accepts a value of GenerationType enum
E
s non - t r for the strategy element. If either GenerationType.SEQUENCE or

arlo
GenerationType.TABLE are specified, the generator element should be used
C to identify the corresponding sequence or table name.

Table 3-5 Acceptable Values for the @GeneratedValue Annotation

Value Description

GenerationType.AUTO Indicates that the persistence


provider should pick an
appropriate strategy for the
particular database
GenerationType.IDENTITY Indicates that the persistence
provider must assign primary keys
for the entity using database
identity column

Java Persistence API Entities 3-19


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Primary Keys and Entity Identity

Table 3-5 Acceptable Values for the @GeneratedValue Annotation

Value Description

GenerationType.SEQUENCE Indicates that the persistence


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

provider must assign primary keys


for the entity using a database
sequence primary key generator to
ensure uniqueness
GenerationType.TABLE Indicates that the persistence
provider must assign primary keys
for the entity using a database
table primary key generator to s a
ensure uniqueness ) h a
m x
t g ob
s a de
a l@
Note GenerationType.AUTO is the default value for
n ui
the @GeneratedType
G
annotation.
b er dent
e s to Stu
( e rn tAnnotation
Code 3-12 Using the @GeneratedValue his
z e
deGenerationType.AUTO
us
1 //Example 1, using the default
n a n
t o value
1 @Id r
e ens e
2 @GeneratedValue al H lic id; }
3 r
e abn
public Long getId() {l e
return
t o B er
4
e s n s f
Ern n-tra
5 //Example 2
6 s @Id
arl7o @GeneratedValue(strategy
no = GenerationType.IDENTITY)
C 8 public Long getId() { return id; }
9
10 //Example 3
11 @Id
12 @GeneratedValue(strategy=GenerationType.SEQUENCE,
generator="CUST_SEQ")
13 public Long getId() { return id; }
14
15 //Example 4
16 @Id
17 @GeneratedValue(strategy=GenerationType.TABLE, generator="CUST_GEN")
18 public Long getId() { return id; }

3-20 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 4
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Understanding the Entity Manager

Objectives a
h a s
x )
b m Upon completion of this module, you should be able to:
Describe the relationship between an entity manager, a t go context,
a persistence
@ s ide
and a persistence unit
n l
a t Gu
r
e den entity manager and
Describe the difference between a container-managed
b
o
n e st
an application-managed entity manager
S tu

z er e this
Describe the entity life (cycle

a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C

4-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

4-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding Entity Manager

Understanding Entity Manager


An entity manager is used to create and remove persistent entity instances, to find
persistent entities by primary key, and to query persistent entities.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Database lifecycle events are often generically called CRUD events -- short for
Create, Retrieve, Update, and Delete. The EntityManager interface defines,
among other things, the CRUD methods that are used to interact with the
persistence context. The following table is a partial list of common
EntityManager methods as they relate to CRUD methods.

s a
) h a
m x Table 4-1 Relating CRUD events to EntityManager Methods
t g ob
CRUD EntityManager Method s a de
n a l@ Gui
Create persist(entity);
b er dent
Retrieve find(entity, s
e to Skey);
primary tu
n
Update (er happen
none - updates
z e this
an
de to ufor
automatically s managed entities.
Delete e rn remove(entity);
n se
H
al e lic e
r n
e abl
B
to sfer
e s
E rn -tran
arlos non
C

Understanding the Entity Manager 4-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

Persistence Unit
The set of entities that can be managed by a given EntityManager instance is a
persistence unit. A persistence unit also defines database connectivity information
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

and other settings.

must be colocated in their mapping to a Note All entities in the same persistence unit must be saved to a single
single database database.

A persistence.xml file defines one or more persistence units. The


s a
persistence.xml file is located in the META-INF directory of the root of the
) h a
m x persistence unit.

Code 4-1 Defining a Persistence Unit in persistence.xml tg


ob
s a de
19 <persistence version="2.0"
n a l@ Gui
20 xmlns="http://java.sun.com/xml/ns/persistence"
b er dent
21 s to Stu
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
e
22 rn this
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
( e
23 z use
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
d e
24
an e to
<persistence-unit name="JpaDemoPU"
r n
25
e ens
transaction-type="RESOURCE_LOCAL">
H
26
n l
a e lic
27 <provider> r
e abl
28 B
to sfer
org.eclipse.persistence.jpa.PersistenceProvider
29 e s
n tran
</provider>
30 Er <class>jpademo.jpa.Item</class>
r l
31o o n-
s n<properties>
Ca 32 <property name="javax.persistence.jdbc.password"
33 value="wordpass"/>
34 <property name="javax.persistence.jdbc.user" value="admin"/>
35 <property name="javax.persistence.jdbc.driver"
36 value="org.apache.derby.jdbc.ClientDriver"/>
37 <property name="javax.persistence.jdbc.url"
38 value="jdbc:derby://localhost:1527/auction"/>
39 </properties>
40 </persistence-unit>
41 </persistence>

The persistence-unit element has the following attributes:

4-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

Table 4-2 Attributes of the persistence-unit Element

Attribute Required Description


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

name yes The name attribute defines the name for the persistence
unit
transaction- no The transaction-type attribute is used to specify
type whether the entity managers provided by the entity
manager factory for the persistence unit must be JTA
entity managers or resource-local entity managers.
s a
In a Java EE environment, if this element is not specified, ) h a
m x
the default is JTA. In a Java SE environment, if this
g ob
element is not specified, the default is
t
RESOURCE_LOCAL. s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
Note For more
r n aonntransactions,
e to see Implementing Transactions and Locking.
H e ens
n l
a e lic
r
e abl
The persistence-unit element can contain the following sub-elements:
B r
to sfedescription
e s
E rn -tran provider
s non
C arlo properties
jta-data-source (or non-jta-data-source)
class, jar-file, mapping-file
exclude-unlisted-classes
shared-cache-mode
validation-mode

Note Only the name attribute on the persistence-unit element is required.


All other attributes and elements are optional.

Understanding the Entity Manager 4-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

description Element
The description element provides optional descriptive information about the
persistence unit.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 4-2 The description Element of a Persistence Unit


1 <persistence>
2 <persistence-unit name="JpaDemoPU">
3 <description>This persistence unit is
4 used for demo purposes.</description>
5 </persistence-unit>
s a
6 </persistence>
) h a
m x
provider Element t g ob
s a de
n a l@ Gui
r entprovider's
The provider element specifies the name of theepersistence
b
javax.persistence.spi.PersistenceProvider tudclass. isThedependent
toif theSapplication provider
n e s
element is optional, but it should be specified
e r
a particular persistence provider (being used.t h i s upon

d e z use
The provider classrn is a
n intothe persistence providers documentation. For
H e enproviderse class is
specified

r n al e lic
example, the EclipseLink

B e b l
org.eclipse.persistence.jpa.PersistenceProvider. The Hibernate

s t oproviderf e ra is org.hibernate.ejb.HibernatePersistence.
class

rne -trCode s
an 4-3 provider Element of a Persistence Unit
E
arl1os <persistence>
non
C 2 <persistence-unit name="JpaDemoPU">
3
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
4 </persistence-unit>
5 </persistence>

properties Element
The properties element is used to specify both standard and vendor-specific
properties and hints that apply to the persistence unit and its entity manager
factory configuration.

4-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

Note Standard properties use the javax.persistence namespace. Vendor-


specific properties use custom namespaces.

The following properties are intended for use in Java SE environments:


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

javax.persistence.jdbc.driver - Fully qualified name of the


driver class
javax.persistence.jdbc.url - Driver-specific URL
javax.persistence.jdbc.user - Username used by database
connection
s a
javax.persistence.jdbc.password - Password for database
) h a
m x connection validation

Code 4-4 properties Element of a Persistence Unit atg


ob
s d e
al@ t Gu i
1 <persistence>
r n
e den
2 <persistence-unit name="JpaDemoPU">
o b
3 <properties>
n e st S tu
4
(er e this
<property name="javax.persistence.jdbc.password"
z
de to us
5 value="wordpass"/>
6
a n

<property name="javax.persistence.jdbc.user"
n
value="admin"/>
7 r
e ens e
<property name="javax.persistence.jdbc.driver"
l H
8
r n l e lic
a name="javax.persistence.jdbc.url"
value="org.apache.derby.jdbc.ClientDriver"/>
9 e ab
<property
B
10 t o
11 nes</properties>s f er value="jdbc:derby://localhost:1527/auction"/>
E - t an
r </persistence-unit>
r
rlos13 </persistence>
non
12

C a

The following properties and hints are intended for use in both Java EE and Java
SE environments:
javax.persistence.lock.timeout - Value in milliseconds for
pessimistic lock timeout. This is a hint only.
javax.persistence.query.timeout - Value in milliseconds for query
timeout. This is a hint only.
javax.persistence.validation.group.pre-persist - Groups
that are targeted for validation upon the pre-persist event (overrides the
default behavior).

Understanding the Entity Manager 4-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

javax.persistence.validation.group.pre-update - Groups that


are targeted for validation upon the pre-update event (overrides the default
behavior).
javax.persistence.validation.group.pre-remove - Groups that
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

are targeted for validation upon the pre-remove event (overrides the default
behavior).

Vendor-specific properties can be mixed with standard properties. The


documentation of the persistence provider will list the vendor-specific properties
that can be used. s a
) h a
m x Code 4-5 Vendor-Specific Properties for EclipseLink
t g ob
1 <persistence>
s a de
2 <persistence-unit name="JpaDemoPU">
n a l@ Gui
3 <properties>
b er dent
4
5 value="DERBY"/> e s to Stu
<property name="eclipselink.target-database"

6 ( e rn this
<property name="eclipselink.ddl-generation"
7 d e z use
value="drop-and-create-tables"/>
8 </properties>
r n an e to
9 </persistence-unit> H e ens
10 </persistence> na l lic
r
e ab l e
t o B er
e s s f
E rn -tran
arlos non Code 4-6 Vendor-Specific Properties for Hibernate
C 1 <persistence>
2 <persistence-unit name="JpaDemoPU">
3 <properties>
4 <property name="hibernate.dialect"
5 value="org.hibernate.dialect.DerbyDialect"/>
6 <property name="hibernate.hbm2ddl.auto"
7 value="create-drop"/>
8 </properties>
9 </persistence-unit>
10 </persistence>

4-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

jta-data-source and non-jta-data-source


Elements
In Java EE environments, the jta-data-source and non-jta-data-source
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

elements are used to specify the global JNDI name of the JTA or non-JTA data
source to be used by the persistence provider. If neither is specified, the deployer
must specify a JTA data source at deployment or a JTA data source must be
provided by the container, and a JTA EntityManagerFactory will be created
to correspond to it.

In Java SE environments, these elements may be used or the data source


information may be specified by other means, depending upon the requirements s a
of the provider. ) h a
m x

Code 4-7 jta-data-source Element of a Persistence Unit
t g ob
s a de
1 <persistence>
n a l@ Gui
2 <persistence-unit name="JpaDemoPU">
b er dent
3 <properties>
e s to Stu
4
rn this
<jta-data-source>jdbc/MyDataSource</jta-data-source>
( e
5 </properties>
d e z use
an e to
6 </persistence-unit>
7 </persistence> r n
e ens
l H
a e lic
r n
e abl
B
to sfer
e s
E rn class,
- t r an jar-file, and mapping-file Elements
arlos non
C The set of managed persistence classes that are managed by a persistence unit is
defined by using one or more of the following:
Annotated managed persistence classes contained in the root of the
persistence unit unless the exclude-unlisted-classes element is
specified
One or more object/relational mapping XML files
One or more JAR files that will be searched for classes
An explicit list of classes

The set of entities managed by the persistence unit is the union of these sources,
with the mapping metadata annotations or annotation defaults for any given class
being overridden by the XML mapping information file if both annotations as
well as XML mappings are provided for that class.

Understanding the Entity Manager 4-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

Annotated Classes in the Root of the Persistence Unit

All classes contained in the root of the persistence unit are searched for annotated
managed persistence classes, classes with the @Entity, @Embeddable, or
@MappedSuperclass annotation. If the annotated persistence classes contained
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

in the root of the persistence unit are not intended to be included in the
persistence unit, the exclude-unlisted-classes element must be specified
as true.

Note The exclude-unlisted-classes element is not intended for use in


Java SE environments.
s a
) h a
Code 4-8 Simplest Possible Persistence Unit
m x
1 <persistence> t g ob
s a de
2
3
<persistence-unit name="JpaDemoPU" />
</persistence> n a l@ Gui
b er dent
e
Any annotated managed persistence classes s tofoundSintthe
u root of the persistence
n his classes. If a META-
er persistence
(
unit are added to the list of managed
z e t
INF/orm.xml file exists, any
n
d e classesusreferenced by it and mapping information
r n a e to
contained in it are used.
H e ens
n l
a e licMapping Files
r
Object/Relational
e abl
B er
toA object/relational
e s n s f mapping XML file typically named orm.xml may be
r n r a
E n-t specified in the META-INF directory in the root of the persistence unit or in the
l o s no META-INF directory of any JAR file referenced by the persistence.xml.
C ar Additionally, one or more mapping files may be referenced by the mapping-
file elements of the persistence-unit element. These mapping files may be
present anywhere on the class path.

Note If you name the object / relational mapping XML file something other
than orm.xml, you must include the mapping-file element in
persistence.xml.

Code 4-9 mapping-file Element of a Persistence Unit


1 <persistence>
2 <persistence-unit name="JpaDemoPU">
3 <mapping-file>customMappings.xml</mapping-file>
4 </persistence-unit>
5 </persistence>

4-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

Any annotated managed persistence classes found in the root of the persistence
unit are added to the list of managed persistence classes. The
customMappings.xml resource exists on the classpath and any classes and
mapping information contained in it are used. If a META-INF/orm.xml file
exists, any classes and mapping information contained in it are used as well.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JAR Files

One or more JAR files may be specified using the jar-file elements in
addition to the mapping files specified in the mapping-file elements. If specified,
these JAR files will be searched for managed persistence classes. Such JAR files
are specified relative to the directory or JAR file that contains the root of the
s a
persistence unit.
) h a
m x
Code 4-10 jar-file Element of a Persistence Unit
t g ob
s a de
1
2
<persistence>
<persistence-unit name="JpaDemoPU"> n a l@ Gui
3 <jar-file>AdditionalEntities.jar</mapping-file> b er dent
4 </persistence-unit>
e s to Stu
5 </persistence>
( e rn this
d e z use
r n an persistence
Any annotated managed
e to classes found in the root of the persistence
e to theenlistsof managed persistence classes. The
unit are added
H
l
a e lic
AdditionalEntities.jar
n file is searched for managed persistence classes.
r
eAny annotatedl
b managed persistence classes found in it or any classes specified in
t o B e r a
e s the
s form.xml file in the JAR file are added.
E rn -tran
arlos non
C
List of Managed Classes

A list of named managed persistence classes may be specified instead of, or in


addition to, the JAR files and mapping files. The class element is used to list a
managed persistence class.

Note A list of all named managed persistence classes must be specified in Java
SE environments. This is required for portability.

Code 4-11 class and exclude-unlisted-classes Elements of a


Persistence Unit
1 <persistence>
2 <persistence-unit name="JpaDemoPU">

Understanding the Entity Manager 4-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Unit

3 <exclude-unlisted-classes>true</exclude-unlisted-classes>
4 <class>com.acme.Order</class>
5 <class>com.acme.Customer</class>
6 <class>com.acme.Item</class>
7 </persistence-unit>
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

8 </persistence>

Any annotated managed persistence classes found in the root of the persistence
unit are not added to the list of managed persistence classes. Only Order,
Customer, and Item are added to the list of managed persistence classes.

Note If the META-INF/orm.xml file exists, classes in that file will be added to s a
the list of managed persistence classes. ) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

4-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Context

Persistence Context
A persistence context is a set of managed entity instances in which a unique
entity instance exists for any persistent entity identity (primary key). Within the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

persistence context, the entity instances and their life cycle are managed by the
entity manager.

The following items provide additional information regarding persistence


contexts and entity managers.
You do not create a persistence context directly. Instead, you use the

s
persistence context that is created when the entity manager is created. a
h a
Java EE applications typically use a container-managed entity manager.
m x)
Java SE applications typically use an application-managed entity
g o b manager.

atscopes:
A persistence context can have the following (lifetime)s i d e
Transaction scope - A transaction scopedn l@ Gucontext exists for
apersistence
the duration of the transaction. be
r e n t l

s to scoped d
tupersistence
n e
Extended scope - An extended
r i s S exists for the l
e
duration of multiple
z e t h
( transactions.
e
nd to u s
n a
H er ense
r n al e lic
B e abl
e s to sfer
E rn -tran
arlos non
C

Understanding the Entity Manager 4-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Obtaining an Entity Manager

Obtaining an Entity Manager


The entity manager for a persistence context is obtained from an entity manager
factory.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

When container-managed entity managers are used in Java EE environments, the


application does not interact with the entity manager factory. The entity managers
are obtained directly through dependency injection or from JNDI, and the
container manages interaction with the entity manager factory transparently to the
application.

When application-managed entity managers are used, the application must use the s a
entity manager factory to manage the entity manager and persistence context ) h a
m x lifecycle.
t g ob
s a de
Note An entity manager must not be shared among multiple
n a G ui
l@ concurrently
b er dcontext
executing threads, as the entity manager and persistence
e nt are not required
to be threadsafe. Entity managers must only
e s tobe accessed
S t u in a single-threaded
manner.
( e rn this
d e z use
r n an e to
H e ens
Obtaining a Container-Managed Entity Manager in the
Java EE
l
na le li c
e rEnvironment
t o B erab
e n s f
s A container-managed
E r n t r a entity manager is obtained by the application through

r l o s non- dependency injection, or direct lookup of the entity manager in the JNDI

Ca
namespace. The container manages the persistence context lifecycle and the
creation and the closing of the entity manager instance transparently to the
application.

The @PersistenceContext annotation is used for entity manager injection. All


elements of the @PersistenceContext annotation are optional.

4-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Obtaining an Entity Manager

Table 4-3 Elements of the @PersistenceContext Annotations

Name Type Default Description


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

name String The name by which the entity


manager is to be accessed in the
environment referencing context.
This name is not needed when
dependency injection is used.
properties PersistenceProperty[] Used to specify properties for the
s a
h a
container or persistence provider.
)
m x Vendor-specific properties may be

t g ob included in this set of properties.


s a de Properties that are not recognized

n a l@ Gui by a vendor are ignored.


type PersistenceContextType
TRANSACTIONb er Specifies
d e n t whether this is a
e s to Stutransaction-scoped persistence
n
z (er e this context (TRANSACTION) or an
d e u s extended persistence context

r n an e to (EXTENDED).
unitName String l He
c e ns The name of the persistence unit.
a l i
B ern able
e s to sfer
E rn -tran
s non Code 4-12 Using the @PersistenceContext Annotation to Inject an Entity
C arlo Manager Into a Class
1 public class ItemDao{
2 @PersistenceContext(unitName = JpaDemoPU)
3 private EntityManager entityManager;
4 }

Code 4-13 Using JNDI Lookup to Obtain an Entity Manager


1 @PersistenceContext(name = OrderEM)
2 public class ItemDao{
3 @Resource SessionContext sessionContext;
4 public void doSomething(){
5 EntityManager entityManager =
6 (EntityManager) sessionContext.lookup(OrderEM);

Understanding the Entity Manager 4-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Obtaining an Entity Manager

7 }
8 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Obtaining an Application-Managed Entity Manager


An application-managed entity manager is obtained by the application from an
entity manager factory.

The EntityManagerFactory used to obtain an application-managed entity


s a
manager is the same whether this API is used in Java EE or Java SE
) h a
environments.
m x
t g ob
safactory injection.
The @PersistenceUnit annotation is used for entity manager
All elements of the @PersistenceUnit annotation arel@optional. uid
e
e r na nt G
t o b tude
r n es is S
(e e th Annotations
Table 4-4 Elements of the @PersistenceUnit
z
a n
de to us
Name Type e rn nDefault
se Description
l H
a e li c e
name Stringern l The name by which the entity
B
o sfer a b
s t manager factory is to be accessed

E rne -tran in the environment referencing


context. This name is not needed
l o s o n
C ar n when dependency injection is
used.
unitName String The name of the persistence unit.

Code 4-14 Using the @PersistenceUnit Annotation on an Instance Field to


Inject an Entity Manager Factory Into a Class
1 @Stateless
2 public MyBeanImpl implements MyBean
3 @PersistenceUnit(unitName = JpaDemoPU)
4 private EntityManagerFactory emf;
5
6 public void someMethod(){
7 EntityManager entityManager = emf.createEntityManager();

4-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Obtaining an Entity Manager

8 // ...
9 }
10 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Unlike mapping annotations which must be placed on the getter methods, the
@PersistenceUnit annotation must be placed on the setter method to inject
an entity manager factory.

Code 4-15 Using the @PersistenceUnit Annotation on a Setter Method to


Inject an Entity Manager Factory Into a Class
s a
1 @Stateless ) h a
m x 2 public MyBeanImpl implements MyBean
t g ob 3 private EntityManagerFactory emf;
s a de 4
@PersistenceUnit(unitName = JpaDemoPU)
n a l@ Gui 5
public void setEmf(EntityManagerFactory f){
b er dent 6
this.emf = f;
e s to Stu 7
}
( e rn this 8

d e z use 9

an e to = emf.createEntityManager();
public void someMethod(){ 10
r n
EntityManager entityManager
e ens 11
// ... l H
a e lic 12
} r n
e abl 13
} B
to sfer 14
e s
E rn -tran
arlos non
C Obtaining an Entity Manager Factory in a Java SE Environment

Outside a Java EE container environment, the


javax.persistence.Persistence class is the bootstrap class that provides
access to an entity manager factory. The createEntityManagerFactory
method accepts the name of a persistence unit as a parameter.

Code 4-16 Obtaining an Entity Manager Factory in a Java SE Environment


1 import javax.persistence.*;
2
3 public class ItemDao {
4 private EntityManager entityManager;
5
6 public ItemDao(){

Understanding the Entity Manager 4-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Obtaining an Entity Manager

7 EntityManagerFactory emf =
8 Persistence.createEntityManagerFactory("JpaDemoPU");
9 entityManager = emf.createEntityManager();
10 }
11 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

4-18 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Entity Life-Cycle States

Examining Entity Life-Cycle States


This section examines the following topics and their relationship to entity life-
cycle state management.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Entity life-cycle states


The four life-cycle states of an entity instance are New, Managed,
Detached, and Removed. More details are provided in Table 4-5.
Persistent identity
The persistent identity is a unique value used by the persistence provider to
map the entity instance to the corresponding table row in the database.
s a
Persistent identity should not be confused with Java object identity.
) h a
m x
Table 4-5 provides a summary of the significance of each entitygstate
t ob shown in
Figure 4-1. s a de
n a l@ Gui
Table 4-5 Entity Life-Cycle States
b er dent
Entity State Significance e s to Stu
( e rn this
New A new entity instance is
d e za new instance
u s e of the entity created using the new
keyword. There a is n to
no corresponding database table row in the persistence tier
r n e
associated e
l H c e ns primary key.
with the entitys

l e li
rna is ba corresponding
Managed
B eThere database row and data in the row is kept synchronized

s t o (by f e rapersistence provider) with data in the entity


the
s
rne -tranThere is a corresponding database row but data in the row and data in the entity
Detached
E
s non
arlo
are not kept synchronized.
C Removed This state represents a pending removal of the corresponding data row in the
database.

Understanding the Entity Manager 4-19


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Entity Life-Cycle States

Figure 4-1 shows the possible states of an entity instance. The persist, merge,
and remove methods are part of the entity manager API.
Object Tier Persistence Tier
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

:EntityManager
... New
persist()
No PI
merge() No PC
remove() persist()
find() or
merge() Automatic
s a
Detached Managed data
) h a
*
m x synchronization
Has PI
No PC merge()
Has PI
Has PC t g ob
s a de
n a l@ Gui
remove()
b er dent
e s to Stu
( e rn this
d e z use
Removed

r n an e to
H e ens
n l lic Identity
aPI = Persistent
r
e PC l e
t o B
f e r ab= Persistence Context
r n es rans * = When the PC ends
s E n-t
ar l o no Figure 4-1 Entity Instance State Diagram
C

Note Under some circumstances, persistence identity might not be available for
entity instances that changed state from new to managed until the transaction
commits. This situation applies, for example, to entities that use generated
primary keys.

4-20 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Entity Life-Cycle States

Table 4-6 shows the entity manager methods or events required to change an
entitys life cycle state.

Table 4-6 Changing Entity Life Cycle States


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Old Entity New Entity


Required Operation
State State

Does not exist Use new operator to create a new instance New
New Use entity managers persist operation Managed
Managed Use entity managers remove operation Removed
s a
Managed Happens as the consequence of the persistence context Detached
) h a
ending.
m x
instances are always detached. t ob
Instances generated by serialization or cloning of managed
g
s a de
Detached Use entity managers merge operation
a l@ GuManagedi
n
r ent Managed
Removed Use entity managers persist operationbe
e s to Stud
Removed
e r n his
Delete reference to removed instance Nonexistent
z ( e t
e s
nd othertouseful
u entity manager methods.
a
Table 4-7 shows several
n
H er ense
l
Table 4-7 Other EntityaManager
n c
liMethods
r
e ab l e
Entity t o B er
e s s f
rn -tranComment
Manager
E
s non
Method
C arlo flush Forces the synchronization of the database with entities in the persistence
context.
refresh Refreshes an entity instance in the persistence context from the database.
find Finds an entity instance by executing a query by primary key on the database.
contains Returns true if the entity instance is in the persistence context. This value
signifies that the entity instance is managed.

The following tasks are relevant to managing the life cycle state of an entity
instance:
l Decide between using a transaction scoped entity manager or extended
scoped entity manager.
l Obtain or create an entity manager.

Understanding the Entity Manager 4-21


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Entity Life-Cycle States

l Write code that uses the entity manager methods to manage the entity
life cycle state to meet the requirements of the application use cases.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

4-22 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Entities to Interact With the Database

Using Entities to Interact With the Database


Figure 4-2 illustrates the database tasks you can perform using entity instances.
Actions
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Create new entry Id Description Image


Delete entry 025 Car Car.jpg
Find entry 026 Boat Boat.jpg
Update entry

Id Description Image
s a
Create new entry
) h a
Delete entry
025
m x Car Car.jpg
Find entry
t g ob026 Boat Boat.jpg
Update entry s a de 027 Bike Bike.jpg

n a l@ Gui
b er dent
e s
Id to Description
S tu Image
Create new entry rn
Delete entry z (e 025
e this Car Car.jpg
Find
a n
de to us
entry
e rn nentry
Update se 027 Bike Bike.jpg
H
al e lic e
r n l new entry
e abCreate
B
to sfer Delete entry Id Description Image
e s
E rn -tran Find entry 025 Car Car.jpg
s n
C arlo no Update entry 027 Bike Bike.jpg

Create new entry


Id Description Image
Delete entry
Find entry 025 Truck Truck.jpg
Update entry 027 Bike Bike.jpg

Figure 4-2 Database Tasks

This section shows how you can use entity instances and the EntityManager
API to perform the tasks illustrated in Figure 4-2.
Create a new entry in the database.
The createItemEntry method is an example of creating a new entry in
the database. The steps involved are:

Understanding the Entity Manager 4-23


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Entities to Interact With the Database

a. Create a new instance of an entity class that corresponds to the


database table.
b. Use the persist method of the entity manager object to create an
entry in the database table.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note The Item entity class uses the persistence providers automatic primary
key generation facility to generate primary keys.

The entity manager object is a transaction scoped entity manager. You can
assume that all methods of the AppManagerBean class run in a transaction.
s a
Locate and fetch an entry from the database.
) h a
m x The findItem method is an example of finding and returning an existing
t g ob entry in the database.
s a locatedean entry
Use the find method of the entity manager object
n a l@ Gobject.
to
ui l
in the database table. This method returns
b er dent
a managed
Update an entry in the database.
e s to Stu
The overloaded updateItemImage( e rn methods
t his are two examples of updating
z
de to us
an entry in the database. e
a n

e rn use nthesproperty
You must e method (setImage) to change the value of l

n a ltheHimage
l i c e
attribute of the entity instance.

B er You a b e either use the property method on a managed instance as


lmust l

e s to sfershown in the
E rn -tran updateItemImage(Item item, String newImage)method,
rlos non
or you must merge a detached instance after updating it as shown in
C a the updateItemImage(String newImage, Item item)
method.
Delete an existing entry in the database.
The overloaded deleteItem methods are two examples of deleting an
entry from the database.
l Use the remove method of the entity manager object.
l The entity instance passed to the remove method must be a managed
object.

4-24 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Entities to Interact With the Database

Code 4-17 Entity Instance Management Using a Transaction-Scoped Persistence


Context
1 @Stateful
2 public AppManagerBean implements AppManager {
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

3 @PersistenceContext
4 private EntityManager entityManager;
5
6 public Item createItemEntry(String description, String image) {
7 Item item = new Item(description, image);
8 entityManager.persist(item);
9 return item;
10 }
s a
11
) h a
m x 12 public Item findItem(Integer key) {

t g ob 13 Item item = entityManager.find(Item.class, key);


s a de 14 return item;

n a l@ Gui 15 }

public Item updateItemImage(Item item) {be


r ent 16

tud invocation
17
// assume item has been updated e s to toSmethod
prior 18
( e rn this
Item item1 = entityManager.merge(item); 19
return item1;
d e z use 20
}
r n an e to 21

public Item a l He icens 22


r n l e l
updateItemImage(Integer key, String newImage) { 23
e =aentityManager.find(Item.class,
ItemBitem b key); 24
t o fe r
sitem.setImage(newImage); 25
n e n s
s Er } n-tra
return item; 26

rlo no
27
C a 28
29 public Item updateItemImage(Item item, String newImage) {
30 // item is detached intance; item1 is managed instance
31 Item item1 = entityManager.merge(item);
32 item1.setImage(newImage);
33 return item1;
34 }
35
36 public Item updateItemImage(String newImage, Item item) {
37 item.setImage(newImage); // item is detatched instance
38 Item item1 = entityManager.merge(item); // item1 is managed
39 return item1;
40 }
41
42 public Item deleteItem(Integer key) {
43 Item item = findItem(key);

Understanding the Entity Manager 4-25


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Entities to Interact With the Database

44 entityManager.remove(item);
45 return item;
46 }
47
48 public Item deleteItem(Item item) {
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

49 item = entityManager.find(Item.class, item.getId);


50 entityManager.remove(item); // managed instance
51 return item;
52 }
53 }

Using an Extended Persistence Context Entity s a


) h a
x Manager
m
t g ob
a de
The main difference between using a container-managed transaction-scoped
s
entity manager and a container-managed extended-scoped
a l@ Gmanger
entity u i are as
follows: n
er dent
b
to allSmanaged
s
With a transaction-scoped entity manager,
e tu entity instances in
n is detached when the
transaction completese z (er orscope
the entity managers persistence
e thbecome
an
d to us
(commits rolls back).
rn npersistence
With an extended-scoped
e s e entity manager, all managed entity instances in

a l
the entityH ice
managers scope stay managed for the duration of the
l
rn boflethe entity manager.
B elifetime a manager is obtained using the
s t o sThe f e rentity
E rne -tran PersistenceContext(type=EXTENDED) injection. The persistence

r l o s non context type associated with entity manager is extended scope. It exists for
Ca the duration of the AppManagerBean instance.
For this example, you should assume that each method executes in its own
transaction.

Note The struck-through lines of code indicate that these lines of code that were
required when using a transaction-scoped entity manager are not required when
using an extended-scoped transaction manager.

4-26 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Entities to Interact With the Database

Code 4-18 Entity Instance Management Using an Extended Persistence Context


1 @Stateful
2 public AppManagerBean implements AppManager {
3 @PersistenceContext(type=EXTENDED)
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

4 private EntityManager entityManager;


5
6 public Item createItemEntry(String description, String image) {
7 Item item = new Item(description, image);
8 entityManager.persist(item);
9 return item;
10 }
11
s a
12 public Item findItem(Integer key) {
) h a
m x 13 Item item = entityManager.find(Item.class, key);

t g ob 14 return item;
s a de 15 }

// The following method is no longer neededrna


l@ Gui 16

b e dent 17
public Item updateItemImage(Item item)
// assume item has been updated e s to toSmethod
prior
{
tu invocation
18
19
n
(er e this
Item item1 = entityManager.merge(item);
z
20
return item1;
an
de to us 21
}
e rn nse 22

public Itemn a l H lice


updateItemImage(Integer key, String newImage) {
23
24
er =aentityManager.find(Item.class,
ItemBitem b l e key); 25
t o fe r
sitem.setImage(newImage);
n e n s 26

s Er } n-tra
return item; 27

arlo no 28
C 29
30 public Item updateItemImage(Item item, String newImage) {
31 // item is managed instance
32 Item item1 = entityManager.merge(item);
33 item.setImage(newImage);
34 return item;
35 }
36
37 // The following method is identical to the previous method
38 public Item updateItemImage(String newImage, Item item) {
39 item.setImage(newImage); // item is managed instance
40 Item item1 = entityManager.merge(item); // item1 is managed
41 return item;
42 }
43
44 public Item deleteItem(Integer key) {

Understanding the Entity Manager 4-27


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Entities to Interact With the Database

45 Item item = findItem(key);


46 entityManager.remove(item);
47 return item;
48 }
49
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

50 public Item deleteItem(Item item) {


51 item = entityManager.merge(item);
52 entityManager.remove(item); // managed instance
53 return item;
54 }
55 }

s a
Note Due to the nature of stateful session bean client access, only a stateful ) ha
session bean can use container-managed extended-scoped persistence context. m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C

4-28 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 5
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Modeling Entity Relationships

Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
t g ob
a de
Examine association relationships in the data and object
s models
a l@ Gui
Use relationship properties to define associations
n
b er dent
Implement one-to-one unidirectional associations
e s to Stu
n hassociations
r t isbidirectional associations
Implement one-to-one bidirectional
z ( e e

a n
de to us
Implement many-to-one/one-to-many
Implement
e rn nse bidirectional associations
many-to-many

n a l H limany-to-many
Implement c e unidirectional associations
r
e Examine l e
t o B
f e r ab fetch and cascade mode settings
r n es rans
s E n-t
ar l o no
C

5-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

5-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Association Relationships in Data and Object Models

Examining Association Relationships in Data and Object


Models
Most applications use relational databases to persist data. Relational databases
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

store data in tables. Tables consist of rows and columns. The columns represent
attributes and the rows store attribute values that are semantically related. You use
a primary key to uniquely identify a row of data.

In many cases, a row of data in one table can be semantically related to one or
more rows in one or more tables. In relational databases, you use foreign keys to
maintain such relationships.
s a
) h a
m x
Figure 5-1 shows some of the relationships within the data model that represents
the auction application in the EIS tier.
t g ob
Bid s a de
Table 5-2

n a l@ Gui
BidID Auction Bidder Amount
b er BidTime
e n t Authorization
e s to Stud
( e rn this
d e z use
r n an e to
H e ens
Auction
Table 5-1

n l c
a IDe liSeller
r
Auction
e ab l Item StartAmount Increment ...
B
to sfer
e s
E rn -tran
s non
C arlo
Table 5-3 Item

ItemID Description Image

Figure 5-1 Partial View of Relationships Within the Auction Systems Data
Model

Modeling Entity Relationships 5-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Association Relationships in Data and Object Models

Figure 5-2 shows the part of the object model that is used to represent the auction
application in the middle tier. It shows the object tier equivalent auction-bid
relationship and the auction-item relationship shown in Figure 5-1 on page 5-3.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

<<entity>> 1 * <<entity>>
Auction Bid

1 1 <<entity>> s a
Item ) h a
m x
t g ob
Figure 5-2 a de
Object Model Showing Object Association Relationships
s
n a l@ Gui
er inde
The first step in modelling the association relationships
b t tier is to define
thendata

e s to properties.
the relationship in terms of a set of relationship
S t u These relationship
rn thethsame
properties can then be used to implement
model using entity classes. z (e
is relationships in the object
d e u s e
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

5-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Relationship Properties to Define Associations

Using Relationship Properties to Define Associations


The following four properties are required to describe association relationships
between objects in the object model, reflecting the association between data held
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

in two related database tables:


Cardinality
Cardinality specifies the quantity relationship between two entities in a
relationship. In the Java Persistence API, cardinality is expressed using one
of the following annotations:
OneToOne
s a
ManyToOne
) h a
m x
OneToMany
t g ob
ManyToMany
s a de
Direction
n a l@ Gui
b erDirection
e n t expressed using one
of the following terms: e s to Stud
Direction implies navigation or visibility. is

rn this
Bidirectional z (e e
d e u s
r n an e trelationship,
In a bidirectional o each entity can see the other entity in

l H c e ns You can include code in either entity that navigates to


e relationship.
the
rna bthe l e li entity to obtain information or services from the other entity.
other
e
B era In the Java Persistence API, the bidirectional nature of the relationship
t o
s nsf
r n e r a is specified by the use of one of the cardinality annotations in both the
s E n-t entity classes on either side of the relationship.
ar l o n o Unidirectional
C
In a unidirectional relationship, only one of the entities can see the
other entity in the relationship.
In the Java Persistence API, the unidirectional nature of the
relationship is specified by the use of one of the cardinality
annotations in the entity class that owns the relationship.

Modeling Entity Relationships 5-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Relationship Properties to Define Associations

Ownership
Ownership specifies the owning side of the relationship. In a unidirectional
relationship, ownership is implied. The following terminology is used when
discussing ownership:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Owning side
In the Java Persistence API, the owning side determines which entity
causes updates to the relationship in the database.
Inverse side
The non-owning side or the inverse side of the relationship recieves
updates from the owning side.
s a
Cascade type (operation propagation)
) h a
m x
t ob
The javax.persistence.CascadeType property specifies the
g
propagation of the effect of an operation to associated entities. The cascade
s a de
n a l@ Gui
functionality is most typically used in parent-child (composition)
relationships. The cascade property is expressed using one of the following
terms: b er dent
e s to Stu

rn this
ALL - Cascades all operations
( e
e z persist
PERSIST - Cascades
d u s e
operations
an emerge
MERGE -nCascades
r to operations
alREMOVE e ns remove operations
He -icCascades
r n REFRESH
l e l
e
B erab - Cascades refresh operations
t o
s ns f DETACH - Cascades detach operations
n e
s Er n-tra
C arlo no
Examples of Association Relationships
Table 5-1 shows the seven possible cardinality-direction combinations of
relationships.

Table 5-1 Cardinality-Direction Combinations

Cardinality Direction

1 One-to-one Bidirectional
2 One-to-one Unidirectional
3 Many-to-One / One-to-many Bidirectional
4 Many-to-One Unidirectional
5 One-to-Many Unidirectional
6 Many-to-many Bidirectional

5-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Relationship Properties to Define Associations

Table 5-1 Cardinality-Direction Combinations

Cardinality Direction

7 Many-to-many Unidirectional
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Example of One-to-One Bidirectional Relationships

Figure 5-3 shows an example of a one-to-one bidirectional relationship. In this


example (taken from outside the auction application), a Car entity instance is
restricted to a one-to-one relationship with an Engine entity instance. The
bidirectional nature of the relationship enables either entity instance to navigate to
s a
the other entity.
) h a
m x
Car_1 Engine_1
t g ob
s a de
Figure 5-3 One-to-One Bidirectional Relationship a l@Exampleui
b e r ent G
n
Example of One-to-One Unidirectional s t o Relationship
tud
e
rn this S
( e
z of ua sone-to-one
e
n
d e
Figure 5-4 shows an example unidirectional relationship. In this

r n a et
example, an Auction entity o
instance is restricted to a one-to-one relationship
with an Item
l H c ns toThenavigate
eentityeinstance. unidirectional nature of the relationship enables

r n a e li
the Auction entity instance to the Item entity, but the Item entity
B a l
ecannot navigate
b to the Auction entity.
o
st nsAuction_1fe r
r n e r a Item_1
E - t
arlos non
C Figure 5-4 One-to-One Unidirectional Relationship Example

Modeling Entity Relationships 5-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Relationship Properties to Define Associations

Examples of Many-to-One / One-to-Many Bidirectional


Relationship

Figure 5-5 shows an example of a many-to-one/one-to-many bidirectional


relationship taken from the auction application. In this example, an Auction
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

entity instance is related to many Bid entity instances. From the Auction entity
instance, you can locate all its associated Bid classes. From any Bid entity
instance, you can locate the Auction entity instance to which it relates.

Auction_1

s a
Bid_1
) h a
m x
Figure 5-5 Many-to-One / One-to-Many Bidirectional Relationship t g obExample
s a de
n a l@ Gui
Example of Many-to-One Unidirectional Relationship
b er dent
e
Figure 5-6 shows an example of a many-to-ones to unidirectional
S tu relationship taken
e r n h i s
z (
from a banking application. In this example,
e t an AccountType entity instance is
n
e instances.
related to many Accountdentity uans Account
The unidirectional nature of the
relationship restricts a
rn instance.
navigation
e t o
from entity instance to its related
AccountType e
H icen
entity s
n a l l
e r l e
t o f e ab
B AccountType_1
r
r n es rans
s E n-t
ar l o no Account_1
C
Figure 5-6 Many-to-One Unidirectional Relationship Example

5-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Relationship Properties to Define Associations

Example of One-to-Many Unidirectional Relationship

Figure 5-7 shows an example of a one-to-many unidirectional relationship. In this


example, an Order entity instance is related to many OrderItem entity
instances. From the Order entity instance, you can locate all of its associated
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

OrderItem classes. However, the designers of the relationship have chosen to


hide the Order entity instance from the OrderItem entity instances.

Order_1

OrderItem_1 a
h a s
x )
m
Figure 5-7
ob
One-to-Many Unidirectional Relationship Example
t
a deg
s
Example of Many-to-Many Bidirectional Relationship
n a l@ Gui
b er bidirectional
d e n t
Figure 5-8 shows an example of a many-to-many
example models a relationship that e s t o thatS t u relationship. This

e r n shows h i s a company has many employees


and an employee can work for
z ( many
e t
companies. Navigation is possible in either
direction. That is, given
a n
decan t o us you
a company, can navigate to all its employees, and

works. He
rn nse
given an employee you navigate to all the companies for which the employee

a l l i c e
n
er Company_1 le
o B r a b Employee_1
t
es rans f e
r n
E n-t
r l o s no Employee_2
C a Company_2

Employee_3

Company_3
Employee_4

Figure 5-8 Many-to-Many Bidirectional Relationship Example

Modeling Entity Relationships 5-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Relationship Properties to Define Associations

Example of Many-to-Many Unidirectional Relationship

Figure 5-9 shows an example of a many-to-many unidirectional relationship. This


example models a unidirectional relationship between Order instances and
InventoryItems instances.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Order_1 InventoryItem_1

InventoryItem_2
Order_2

s a
InventoryItem_3
) h a
m x
Order_3
t g ob
InventoryItem_4 s a de
n a l@ Gui
Figure 5-9 b er deExample
Many-to-Many Unidirectional Relationship nt
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C

5-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-One Unidirectional Association

Implementing One-to-One Unidirectional Association


Figure 5-10 shows a one-to-one unidirectional association between two entities.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

<<entity>> <<entity>>
Customer Record
1 1
id : int recId : int
custRecord : Record ...

Figure 5-10 s a
One-to-One Unidirectional Association
) h a
m x
The following steps outline a process you can follow to define a o
g b
one-to-one
unidirectional association between two entity classes. t
a de
s
1. Define the two entity classes.
n a l@ Gui
2. Identify the entity class that is the o b
owner
erof thedrelationship.
e nt
n e st S tu or field to represent the
3. In the owning entity, create
(has
a is
erwithethethother
relationship property
relationship this entity
d e z u s target entity.
4. In the owning
r n anentity,eannotate
to the relationship field or property with the
H
OnetoOne
l c e ns
e annotation.
5.rna l e li relationship is a unidirectional one-to-one association, no code
e Because
B echanges
this
ab are required on the target entity.
t o f r
r n es rans
s E n-t Code 5-1 Unidirectional One-to-One Association Owning Entity Example
a l o
r @Entity no
C
public class Customer {
@Id
private int id;
@OneToOne
private Record custRecord;
//. . .
}

Code 5-2 Unidirectional One-to-one Association Inverse Entity Example


@Entity
public class Record {
@Id
private int recId;
//. . .
}

Modeling Entity Relationships 5-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-One Unidirectional Association

Figure 5-11 illustrates the table with a join column matching the corresponding
entities.

<<entity>> <<entity>>
Customer Record
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

1 1
id : int recId : int
custRecord : Record ...

s a
) h a
CUSTOMER Table
m x RECORD Table

ID ... CUSTRECORD_RECID
ob
RECID tg ...
s a de
n a l@ Gui
Figure 5-11 Join Column for One-to-One Unidirectional
b er deAssociation
nt
e s to Stu
e rn way
The previous procedure is a fairly generic
( t h isof specifying a unidirectional one-
e
to-one annotation. The following
d z notes u s e
highlight variations to the generic
procedure.
r n an e to
e ethensdefault name of the join column by following the
You canHoverride
n l lic with a JoinColumn annotation in the owning entity.
a eannotation
r
OneToOne
e ab l
t o B If ether two tables share the same primary key values for primary keys
e s s f
E rn -tran PrimaryKeyJoinColumns
involving multiple columns, you should use the

r l o s non annotation instead of the JoinColumn


C a annotation in the owning entity.
If the two tables are joined using multiple columns, you must use the
JoinColumns annotation instead of the default or a JoinColumn
annotation in the owning entity.
In a OneToOne mapping in which the primary key of the referencing entity
is used as a foreign key to the referenced entity, the
PrimaryKeyJoinColumn annotation specifies a primary key column that
is used as a foreign key to join to another table.

5-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-One Bidirectional Association

Implementing One-to-One Bidirectional Association


Figure 5-12 shows a one-to-one bidirectional association between two entities.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

<<entity>> <<entity>>
Customer Record
1 1
id : int recId : int
custRecord : Record ...

Figure 5-12 s a
One-to-One Bidirectional Association
) h a
m x
The following steps outline a process you can follow to define a o
g b
one-to-one
bidirectional association between two entity classes. t
a de
s
1. Define the two entity classes.
n a l@ Gui
b errelationship.
e n t
2. Identify the entity that is the owner of
e s to Stud
the
3. In the owning entity, create
e na relationship
rwith h is entity.
property or field to represent the
relationship this entity (
z use
has t
the other
d e
4. In the owning
r n anentity,eannotate
to the relationship field or property with the
H
OnetoOne
l c e ns
e annotations.
5.rna e li entity, create a relationship property or field to represent the
In the linverse
e ab
B erelationship
s t o f r this entity has with the owning entity.
s
rne -tran6. In the inverse entity, annotate the relationship field or property with the
E
s non OnetoOne annotation. Set the value of the mappedBy attribute of the
r l o
Ca OnetoOne annotation to the value of the relationship field or property in
the owning entity.

Code 5-3 Bidirectional One-to-One Association Owning Entity Example


@Entity
public class Customer {
@Id
private int id;
@OneToOne
private Record custRecord;
//. . .
}

Code 5-4 Bidirectional One-to-One Association Inverse Entity Example


@Entity
public class Record {
@Id

Modeling Entity Relationships 5-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-One Bidirectional Association

private int recId;


@OneToOne(mappedBy="custRecord")
private Customer customer;
//. . .
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Figure 5-13 illustrates the table with a join column matching the corresponding
entities.

<<entity>> <<entity>>
Customer Record
s a
1 1 ) h a
id : int m x recId : int
custRecord : Record
t g ob customer : Customer
s a de ...

n a l@ Gui
b er dent
e s to Stu
( e rn this
CUSTOMER Table
d e z useRECORD Table
r n an e to RECID ...
e ens
ID ... CUSTRECORD_RECID
H
n l
a e lic
r l Column for One-to-One Bidirectional Association
e 5-13abJoin
B
Figure
to sfer
e s
E rn -trTheanpreviously discussed procedure uses the Java Persistence APIs object
s non relational mapping defaults to specify a one-to-one relationship. The following
C arlo notes highlight variations to using the defaults.
You can override the default name of the join column by following the
OneToOne annotation with a JoinColumn annotation in the owning entity.
If the two tables share the same primary key values for primary keys
involving multiple columns, you should use the
PrimaryKeyJoinColumns annotation instead of the JoinColumn
annotation in the owning entity.
If the two tables are joined using multiple columns, you must use the
JoinColumns annotation instead of the default or a JoinColumn
annotation in the owning entity.
In a OneToOne mapping in which the primary key of the referencing entity
is used as a foreign key to the referenced entity, the
PrimaryKeyJoinColumn annotation specifies a primary key column that
is used as a foreign key to join to another table.

5-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association

Implementing One-to-Many/Many-to-One Bidirectional


Association
Figure 5-14 shows a one-to-many/many-to-one bidirectional association between
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

two entities.

<<entity>> <<entity>>
Customer Order
1 *
id : int orderId : int
orders : Collection<Order> customer : Customer s a
...
) h a
m x
Figure 5-14 One-to-Many/Many-to-One Bidirectional Association
t g ob
s a de
The following steps outline a process you can followa l@to define u a imany-to-
one/one-to-many bidirectional association between n
er two n G
t classes.
entity
b
to Stud e
e s
( e
Note In many-to-one/one-to-many
rn associations,
this the owning entity is always the
entity on the many n
side
z us e
deof thetorelationship.
a
rn nse
e
l H thelitwo
1. Define
n a c eentity classes.
B e2.r Identify
a b lethe entity that is the many side of the relationship.
e s to 3.sfeInr the owning entity, create a relationship property or field to represent the
E rn -tran relationship this entity has with the other entity.
arlos non 4. In the many-side entity, annotate the relationship field or property with the
C ManytoOne annotation.
5. In the one-to-many entity, create a relationship property or field to represent
the relationship this entity has with the other entity.
6. In the one-to-many entity, annotate the relationship field or property with
the OnetoMany annotation.
7. Set the value of the mappedBy attribute to the value of the relationship or
property in the owning entity. The mappedBy attribute is always set on the
inverse entity. For a many-to-one/one-to-many association, the inverse
entity is the class that contains the OnetoMany annotation.

Code 5-5 Bidirectional One-to-Many Association Example


@Entity
public class Customer {
@Id

Modeling Entity Relationships 5-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association

private int id;


@OneToMany(mappedBy=customer)
private Collection <Order> orders;
//. . .
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 5-6 Bidirectional Many-to-One Association Example


@Entity
public class Order {
@Id
private int orderId;
@ManyToOne
s a
private Customer customer;
) h a
//. . .
m x
}
t g ob
s a de
a
Figure 5-15 illustrates the table with join column matching
n G ui
l@the corresponding
entities.
b er dent
e s to Stu
<<entity>> ( e rn this <<entity>>
Customer dez u s e Order
a n
t o
e rn nse 1 *
n a l H lice
id : int
e r b l e orderId : int
orders
t B ra
o s:feCollection<Order> customer : Customer
s
E rne ...
- t r an
s non
C arlo

CUSTOMER Table ORDER Table

ID ... ORDERID CUSTOMER_ID ...

Figure 5-15 Join Column for One-to-Many/Many-to-One Bidirectional


Association

5-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association

Using the OrderBy Annotation


Use the OrderBy annotation to return the entities on the many-side of the
relationship in a specific order.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note The OrderBy annotation should be used on a java.util.List of


entities.

Applying the empty OrderBy annotation to a list returns the entities sorted in
primary key order. Omitting the OrderBy annotation, or applying an empty
s a
OrderBy annotation, to a list returns the entities sorted in primary key order.
) h a
m x
Code 5-7 OrderBy Annotation Example
t g ob
@Entity s a de
public class Customer {
n a l@ Gui
@Id
b er dent
private int id;
e s to Stu
@OneToMany(mappedBy=customer)
( e rn this
@OrderBy
d e z use
private List <Order> orders;
//. . . r n an e to
H e ens
}
n l
a e lic
r l
eYou canaspecify
b
t B
o Each e r a comma-delimited list of fields on the OrderBy annotation.
s s f
E rne -trankeyword. attribute can be sorted independently by adding the optional ASC or DESC
Fields without an explicit sort order are sorted in ascending order.
l o s o n
C ar n
Code 5-8 OrderBy Annotation Example With Attributes
@Entity
public class Customer {
@Id
private int id;
@OneToMany(mappedBy=customer)
@OrderBy(orderDate DESC, state ASC)
private List <Order> orders;
//. . .
}

Modeling Entity Relationships 5-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association

Using the OrderColumn Annotation


Use the OrderColumn annotation to maintain the sort order of entities on the
many-side of the relationship without using the entitys attributes for ordering.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The OrderColumn allows the many-side entities to be maintained in an arbitrary


order.

For example, suppose that an address book application must give the end user the
ability to arrange a list of preferred phone numbers for a given contact in an
arbitrary order.

Code 5-9 The Contact Class s a


) h a
@Entity
m x
public class Contact {
t g ob
@Id
s a de
private int id;
n a l@ Gui
@OneToMany(mappedBy=contact)
@OrderColumn b er dent
e s to Stu
private List <PhoneNumber> preferredPhoneNumbers;
//. . . ( e rn this
}
d e z use
r n an e to
Code 5-10
l H c e ns
eThe PhoneNumber Class
@Entity e rna ble li
t o BPhoneNumber
e ra {
public class
@Idne
s s f
E r - t r anid;
s non
private int

C arlo @ManyToOne private Contact contact;


//. . .
}

Placing the OrderColumn attribute on the preferredPhoneNumbers list


causes a new column named PREFERREDPHONENUMBERS_ORDER to be added to
the PHONENUMBER table. The persistence provider uses integers in the order
column to store the arbitrary sort order.

Use the name attribute on the OrderColumn annotation to specify the name of
the order column.

Code 5-11 Using The OrderColumn Annotation With The Name Attribute
@Entity
public class Contact {
@Id
private int id;
Modeling Entity Relationships 5-18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association

@OneToMany(mappedBy=contact)
@OrderColumn(name=CallOrder)
private List <PhoneNumber> preferredPhoneNumbers;
//. . .
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note You cannot use both the OrderBy and OrderColumn annotations on the
same attribute.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Modeling Entity Relationships 5-19


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association

Using the OrphanRemoval Attribute


Adding the orphanRemoval attribute to the OneToOne or OneToMany
annotation guarantees that when an entity is removed from a relationship any
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

entity that is orphaned by that operation will also be removed. For example, in the
following code all related PhoneNumber entities will be deleted when the
Contact entity is deleted.

Code 5-12 Using The OrphanRemoval Annotation With The OneToMany


Attribute
@Entity
s a
public class Contact {
) h a
@Id
m x
private int id;
@OneToMany(mappedBy=contact, orphanRemoval=true) t g ob
s a de
@OrderColumn(name=CallOrder)
n a l@ Gui
private List <PhoneNumber> preferredPhoneNumbers;
//. . . b er dent
}
e s to Stu
( e rn this
d e z use
r n an eantexample
The following code provides o of automatic orphan removal.
Contact contact = ...;l H
e ens
n a e lic
// create a phone rnumber
B e ab=l new PhoneNumber(...);
to sfenumber
PhoneNumber phoneNumber
s r
e
rn -tran
// add the new phone
E
contact.getPreferredPhoneNumbers().add(phoneNumber);
os non
arlphoneNumber.setContact(contact);
C em.persist(phoneNumber);
em.merge(contact);
// remove the phone number from the list
// phoneNumber is now orphaned
contact.getPreferredPhoneNumbers.remove(phoneNumber);
em.merge(contact);
// phoneNumber is removed automatically

5-20 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association

Using a Map For Relationship Mapping


A java.util.Map can be used to store relationships between two entities.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

For example, suppose that you decided to store PhoneNumber entities related to
a Contact entity in a Map. A descriptive string such as Home, Work, or
Mobile can be used at the map key. The PhoneNumber entity is stored as the
map value.

Code 5-13 The Contact Class


@Entity
s a
public class Contact {
) h a
@Id
m x
private int id;
t g ob
@OneToMany(mappedBy=contact)
s a de
@MapKeyColumn(name=description)
n a l@ Gui
//. . . b er dent
private Map <String, PhoneNumber> preferredPhoneNumbers;

} e s to Stu
( e rn this
The MapKeyColumn d e z uspecifies
annotation s e the name of the column that stores the
map key in the n
r an e totable.
PHONENUMBER
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Modeling Entity Relationships 5-21


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing Many-to-Many Bidirectional Association

Implementing Many-to-Many Bidirectional Association


Figure 5-16 shows a many-to-many bidirectional association between two
entities.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

<<entity>> <<entity>>
Worker Project
* *
id : int pId : int
projects : Set<Project> workers : Set<Workers>
... ...
s a
) h a
Figure 5-16 m x
ob
Many-to-Many Bidirectional Association
t g
aa many-to-many

@ Gu
The following steps outline a process you can follow to ldefine s i d e
bidirectional association between two entity classes.rna
b e dent
1. Define the two entity classes.
e s to Stu
(
2. Identify the entity that is the e rn ofththeisrelationship.
owner
d e z a relationship
u s e property or field to represent the
3. In the owning entity,
n n hastwith
create
aentity o the other entity.
relationship rthis
e ens e
4. In the l H
a e lientity,
owning c annotate the relationship field or property with the
r n
eManyToMany l
o B r a b annotations.
n e st 5. nsInfethe inverse entity, annotate the relationship field or property with the
s Er n-tra ManyToMany annotation. Set the value of the mappedBy attribute of the
C arlo no ManyToMany annotation to the value of the relationship field or property in
the owning entity.

Code 5-14 Bidirectional Many-to-Many Association Owning Entity Example


@Entity
public class Worker {
@Id
private int id;
@ManyToMany
private Set <Project> projects;
//. . .
}

Code 5-15 Bidirectional Many-to-Many Association Inverse Entity Example


@Entity

5-22 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing Many-to-Many Bidirectional Association

public class Project {


@Id
private int pId
@ManyToMany(mappedBy=projects)
private Set <Worker> workers;
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

//. . .
}

Figure 5-17 illustrates the tables involved in creating a many-to-many


relationship between the corresponding entities.

<<entity>> <<entity>>
s a
Worker Project
) h a
* m x*
id : int pId : int go
b
projects : Set<Project> workers s t
: aSet<Workers>
e
... ... l@
a t Gu i d
r n
e den
o b
n e st S tu
WORKER Table
z (er e this PROJECT Table

ID ...
an
de to us PID ...
r n
e ens e
l H
a e lic
r n
e abl
B
to sfer
n e s n WORKER_PROJECT Join Table
r
E n-t r a
l o s no
C ar WORKERS_ID PROJECTS_PID

Figure 5-17 JoinTable for One-to-Many/Many-to-One Bidirectional


Association

Modeling Entity Relationships 5-23


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing Many-to-Many Bidirectional Association

Using the JoinTable Annotation


The JoinTable annotation can be added to the owning entity to override the
default join table name and the foreign key column names.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 5-16 Using the JoinTable Annotation


@Entity
public class Worker {
@Id
private int id;
@ManyToMany
s a
@JoinTable(name=CurrentProjects,
) h a
joinColumns=@JoinColumn(name=Worker),
m x
inverseJoinColumns=@JoinColumn(name=Project))
private Set <Project> projects; t g ob
s a de
//. . .
n a l@ Gui
er dent
}
b
to Stu
e s
n the joinColumns
Note Multiple values are allowed
( e rfor is
ththat attribute and the
inverseJoinColumns attribute
d e z for
u s e
entities use more than one column to

r n an e to
define their primary key.
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

5-24 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Fetch and Cascade Mode Settings

Examining Fetch and Cascade Mode Settings


Association mapping annotations have a number of optional attributes you can
set. This section discusses the following two attributes:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Fetch mode attribute


Cascade mode attribute

Fetch Mode Attribute


s a
All annotations that specify association mappings have a fetch mode attribute.
) h a
m x For example,
@ManyToOne(fetch=EAGER)
t g ob
private Customer customer; s a de
n a l@ Gui
er deprovider.
Fetch mode settings are instructions to the persistence
b nt You can specify
two possible values (EAGER or LAZY)to turegard
for the fetch mode attribute. Fetch mode
e s
n his S
loading into memory and z e r
settings are hints to the persistence provider with to the timing of the
the(targets of tthe association. The container interprets
d e u s e
an e to
the fetch mode setting as follows.
EAGER r n
e ens
l H
r n l lic setting of EAGER, either explicit or by default, instructs the
aA fetchemode
B e persistence
ab provider to load the association target at the time the entity is
t o f e r
r n es rans loaded from the database. The EAGER strategy is a requirement on the
s E n-t persistence provider runtime that data must be eagerly fetched.
r l o n o
Ca LAZY
A fetch mode setting of LAZY, either explicit or by default, is a hint to the
persistence provider to defer the loading of the association target to the time
the association target is accessed. The implementation is permitted to
eagerly fetch data for which the LAZY strategy hint has been specified. In
particular, lazy fetching might only be available for mappings for which
property-based access is used.

In addition to association annotations, you can also specify the fetch mode for the
Basic and LOB annotation. Table 5-2 contains the default values for annotations.

Table 5-2 Fetch Mode Default Values

Annotation Default

Basic EAGER

Modeling Entity Relationships 5-25


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Fetch and Cascade Mode Settings

Table 5-2 Fetch Mode Default Values

Annotation Default

OneToOne EAGER
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

ManyToOne EAGER
OneToMany LAZY
ManyToMany LAZY
ElementCollection LAZY

s a
The Lob annotation does not have a fetch mode attribute. To override the default,
) h a
follow the LOB annotation with a Basic annotation. For example:
m x
@Lob @Basic(fetch=LAZY)
t g ob
private Image photo; s a de
n a l@ Gui
The default fetch mode for the Basic annotation
b eisr EAGER.
e n t
e s to Stud
( e rn this
Cascade Mode Attribute e z use
d
an e to
r n
e mode s you can also specify cascade mode settings for
In addition to fetch
l H c e nsettings,
r n a e li
all association mapping annotations. For example:
B ab l
e@OneToOne(cascade=PERSIST)
t o f e r
r n es ransprivate Customer customer;
s E n-t
ar l o no
C

5-26 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Fetch and Cascade Mode Settings

Cascade mode settings can cause specific entity instance life-cycle events to
cascade across relationships. Cascade mode settings are used when the
EntityManager API is invoked. The default is for no cascading to occur.
Table 5-3 contains the possible values for the cascade attribute.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Table 5-3 Cascade Mode Attribute Values

Value Comment

PERSIST Causes the persist operation to cascade to the target entity


of the association when the entity managers persist
operation is invoked on the source entity.
Causes the merge operation to cascade to the target entity of s a
MERGE
the association when the entity managers merge operation is) h a
invoked on the source entity. m x
t g ob
REMOVE Causes the remove operation to cascadeato the target entity
s i d e
r
operation is invoked on the sourcen a@
of the association when the entitylmanagers
t
entity.G u remove

b e den
REFRESH Causes the refresh o
st operation tuto cascade to the target entity
r n e is S
( e
of the association
z is invoked
when
t h the entity managers refresh
e on the source entity.
e
operation
d u s
ALL r n anCausese alltothe entity state change operations (persist,
l H e emerge,
c ns remove, refresh, and detach) to cascade to the
e rna ble li target entity of the association.
t o B DETACH
e ra
e s s f Causes the detach operation to cascade to the target entities

E rn -tran of the association when the entity managers detach

r l o s non operation is invoked on the source entity.


C a

Modeling Entity Relationships 5-27


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Fetch and Cascade Mode Settings
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

5-28 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 6
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Entity Inheritance and Object-Relational


Mapping

s a
Objectives ) h a
m x
Upon completion of this module, you should be able to: atg
ob
s d e
Examine entity inheritance al@ t Gu i
r n
ehierarchy n
Examining object/relational inheritance
t o b u d emapping strategies
Inherit from an entity classrne
s S t

e
(superclass t h i s
Inherit using a mappede z
d to u s e
n a nnon-entity
r nse class
Inherit from
e a

n a l H inheritance
Examine l i c e mapping strategies
r leembeddable class
Be Use a b
e s to sfer an

E rn -tran
arlos non
C

6-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

6-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Entity Inheritance

Examining Entity Inheritance


This section examines entity inheritance. Note the context information you need
to use entity inheritance.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Entity inheritance is the provision of standard Java technology inheritance


capability to entity classes. The end result is that you have the capability to
create a set of entity classes that have a hierarchical relationship.
From a developers perspective, the two key decisions associated with using
inheritance in entity classes are:
The choice of class for the inheriting classs superclass
s a
The choice of object/relational mapping strategy
) h a
m x

t g ob
An entity instances superclass can be any of the following:
An entity class (abstract or concrete)
s a de
A mapped superclass (abstract or concrete)
n a l@ Gui
b er dent

e s to Stu
A non-entity class (abstract or concrete)
n
(e e this
The Java Persistence API rproposes the following object/relational mapping
strategies for entity z
inheritance:
a n
de to uhierarchy
Single-table-per-class
s
strategy
e rn nse
l HJoined-subclass
e strategy
n a l i c
B er abTable-per-class
le strategy
o r
st n sfeThe object relational mapping strategy for entity inheritance is specified
n e
s Er n-tra using the strategy attribute of the Inheritance annotation or the

C arlo no inheritance element in the XML descriptor.

Entity Inheritance and Object-Relational Mapping 6-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Object/Relational Inheritance Hierarchy Mapping Strategies

Examining Object/Relational Inheritance Hierarchy


Mapping Strategies
This section introduces you to the available object/relational inheritance mapping
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

strategies. Consider the following hierarchy of entity classes:


1 // hierarchy root
2 @Entity public class InsurancePolicy{
3 @Id
4 protected int policyId;
5 protected String client;
6 protected double premium;
s a
7 //
) h a
m x 8 }

t g ob 9
// Direct child of hierarchy root
s a de 10
@Entity public class CarInsurance extends InsurancePolicy
n a l@ G{ui 11
protected int vin; er dnumber
// vehicle identification
b e nt 12
protected boolean comprehensive;
e s to Stu 13

}
//
( e rn this 14
15
d e z use 16
// Another direct child n
r of anhierarchy
e to root 17
@Entity public class H e ens
HouseInsurance extends InsurancePolicy { 18
a l l i c
ern aaddress;
protected String dwellingType; 19
protectedBString b le 20
s
protected
e s f er flood;
to boolean 21
E r//n -tran 22

arlos } non 23
C
Code 6-1 Entity Class Hierarchy

To map the inheritance hierarchy to a relational database, you must use one of the
following strategies.
Single-table-per-class hierarchy strategy
Joined-subclass strategy
Table-per-class strategy

The object relational mapping strategy for entity inheritance is specified using the
strategy attribute of the Inheritance annotation or the inheritance
element in the deployment descriptor.

The following sections provide details of each of these mapping strategies.

6-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Object/Relational Inheritance Hierarchy Mapping Strategies

Mapping Inheritance Using the Single-Table-Per-


Class Hierarchy Strategy
The single-table-per-class hierarchy object/relational mapping strategy is
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

implemented by Java Persistence API as follows:


All the classes in a hierarchy map to a single table in the relational
database.
This single table has a column for each unique persistence field in the
hierarchy.
This single table also contains an extra column called the
s a
discriminator column. The value in the discriminator column identifies
) h a
m x
the specific subclass to which the instance that is represented by the
row belongs.
t g ob
s a de hierarchy
Figure 6-1 shows the table structure for the single-table-per-class
strategy for the entity hierarchy.
n a l@ Gui
b er dent
s to Stu
INSURANCE_POLICY
e
( e rn VINthiCOMPREHENSIVE
s
POLICYID DISC CLIENT PREMIUM
e z s e ADDRESS FLOOD

Figure 6-1 n a nd to u
Single-Table-Per-Hierarchy Example
e r nse
n a l H lice
B er Thisa b le strategy provides good support for polymorphic relationships
mapping

s t o sfer between entities and for queries that range over the class hierarchy.

E rne -tran The drawback of using single-table-per-class hierarchy object/relational


s non
arlo
mapping strategy, however, is that it requires that the columns that
C correspond to state specific to the subclasses are nullable.
To implement the single-table-per-class hierarchy object/relational mapping
strategy, annotate the root of the inheritance hierarchy:
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)

Note The single-table-per-class strategy is the default strategy. If you use this
strategy, you do not need to annotate the root class with the Inheritance
annotation.

Entity Inheritance and Object-Relational Mapping 6-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Object/Relational Inheritance Hierarchy Mapping Strategies

Mapping Inheritance Using the Joined-Subclass


Strategy
The joined-subclass object/relational mapping strategy requires a common table
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

to represent the root entity class in the hierarchy.


Each entity subclass is represented by a separate table that contains columns
specific to the subclass as well as the columns that represent its primary
key.
The primary key column or columns of the subclass table serves as a
foreign key to the primary key of the superclass table.
s a
Figure 6-2 shows the table structure for the joined-subclass strategy for the
) h a
m x entity hierarchy .
INSURANCE_POLICY
t g ob
POLICYID CLIENT PREMIUM l@
sa ide
r n a t Gu
b e den
st o tuHOUSE_INSURANCE
CAR_INSURANCE
n e S
z (er e thisPOLICYID ADDRESS FLOOD
de to us
POLICYID VIN COMPREHENSIVE

a n

Figure 6-2 e rn nTables
Example: se for Joined-Subclass Mapping Strategy
H
al e lic e
r n l a joined-subclass object/relational mapping strategy is this
ebenefitaofbusing
B
The
tostrategy r
eprovides
e s n s f support for polymorphic relationships between entities. Another
n a
Er n-tradvantage is the database schema is normalized.
rlo s no The drawback of using a joined-subclass object/relational mapping strategy it that
C a
it requires that one or more join operations be performed to instantiate instances
of a subclass. In deep class hierarchies, this can lead to unacceptable
performance. Queries that range over the class hierarchy likewise require joins.

6-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Object/Relational Inheritance Hierarchy Mapping Strategies

Mapping Inheritance Using a Table-Per-Class


Strategy
The table-per-class object/relational mapping strategy is implemented by Java
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Persistence API as follows:.


This mapping strategy requires a table for each concrete class in the
hierarchy.
Each table has a column for each persistence field, including inherited
fields, in the entity to which it maps.
Figure 6-3 shows the table structure for the table-per-class strategy for the
s a
entity hierarchy
) h a
m x
ob
INSURANCE_POLICY

t
a de g
POLICYID CLIENT PREMIUM
s
n a l@ Gui
b er dent
e s to Stu
CAR_INSURANCE
( e rn this
e z usPREMIUM
POLICYID CLIENT
d e VIN COMPREHENSIVE

r n an e to
H e ens
n l
a e lic
r
e abl HOUSE_INSURANCE
B
to sfer
n e s n
POLICYID CLIENT PREMIUM ADDRESS FLOOD

s Er n-tra
C arlo no Figure 6-3 Table-Per_Class Example

There are drawbacks to using a table-per-class object/relational mapping strategy:


It provides poor support for polymorphic relationships.
It typically requires that SQL UNION queries or a separate SQL query
per subclass be issued for queries that are intended to range over the
class hierarchy.

Note The Java Persistence API does not require persistence providers to
support the table-per-class mapping strategy.

Entity Inheritance and Object-Relational Mapping 6-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Inheriting From an Entity Class

Inheriting From an Entity Class


You can create an entity class that inherits from either a concrete or abstract
entity class.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The following steps outline a process you can follow to create an inheritance
hierarchy of entity classes.
1. Declare the root entity class of the inheritance hierarchy.
The root class can be an abstract entity class.
2. Choose the object/relational strategy you plan to use for the inheritance
s a
hierarchy you are about to create.
) h a
3. m x
Use the strategy attribute of the Inheritance annotation to specify
g ob
your selected object/relational mapping strategy on the root entity class.
t
a de
Some persistence providers might allow you to overridesthe strategy
a
specified in the root entity by permitting you tonspecify ui
l@ anGoverriding
strategy in the child class. b er dent
e s tothe hierarchy.
S tu
n
thiskeyword to extend the parent
4. Declare the remaining entity classes of
z
Each child entity classeuses
(ether extends
e
entity class. and t o us
e rn nse
H iceClass Example
Code 6-2al Root Entity
r n l e l
e
B erab
1 o
@Entity t@Table(name="EMP")
s nsf
2 n e
@Inheritance(strategy=InheritanceType.JOINED)
3
s public tra class Employee {
Er nabstract
-
C arl4o no
@Id
5 protected Integer empId;
6 @Version
7 protected Integer version;
8 @ManyToOne
9 protected Address address;
10 // ...
11 }

Code 6-3 Child Entity Extending Entity Class Example 1


1 @Entity
2 @Table(name="FT_EMP")
3 @DiscriminatorValue("FT")
4 @PrimaryKeyJoinColumn(name="FT_EMPID")
5 public class FullTimeEmployee extends Employee {
6 // Inherit empId, but mapped in this class to FT_EMP.FT_EMPID

6-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Inheriting From an Entity Class

7 // Inherit version mapped to EMP.VERSION


8 // Inherit address mapped to EMP.ADDRESS fk
9 protected Integer salary;
10 // Defaults to FT_EMP.SALARY
11 public Integer getSalary() {
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

12 return salary;
13 }
14 // ...
15 }

The use of the DiscriminatorValue annotation is optional and applies to only


concrete entity classes. If this annotation is not supplied, a persistence provider
specific discriminator value is used. Note that the entity does not contain a s a
DiscriminatorColumn annotation declaration. In this case, the default ) h a
m x
discriminator column having the column name DTYPE and column data type
g ob
STRING is used. The joined subclass strategy can use a discriminator column to
t
s a de
implement object/relational mapping but it is not required to do so.
n a l@ Gui
b er dent
e s to Scolumn
Note Some providers require a discriminator t u for joined inheritance
mappings.
( e rn this
d e z use
Code 6-4 Childn n Extending
aEntity to Entity Class Example 2
r
e ens e
1 @Entity l H
a e lic
2 r n
e abl
@Table(name="PT_EMP")
3 B
to sfer
@DiscriminatorValue("PT")
e s
n tfield n is PT_EMP.EMPID due to PrimaryKeyJoinColumn default
4 r//
E
PK
r a
r l o s56 public
n o n- classFloat
PartTimeEmployee extends Employee {

C a protected
7 // ...
hourlyWage;

8 }

Entity Inheritance and Object-Relational Mapping 6-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Inheriting Using a Mapped Superclass

Inheriting Using a Mapped Superclass


You can create an entity class that inherits from either a concrete or abstract non-
entity class known as a mapped superclass.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

A mapped superclass is a plain Java technology class that is designated with


the MappedSuperclass annotation or mapped-superclass XML
descriptor element.
A mapped superclass is primarily created to provide state and the
corresponding object/relational mapping information to child classes
through the inheritance mechanism.
s a
All behavior, state, and state mapping information is inherited from the
) h a
m x mapped superclass.
All object/relational mapping annotations declared in the mapped g b
osuperclass
t
a de
are processed. s
n a l@ isG
The object/relational mapping metadata of the attributes ui to both
common
mapped superclasses and entities. b er dent
s o
tentity tu
n e S
thisdirectly to a table in the database.
A mapped superclass differs from an in several ways:
z erentitye map
(an
de tosuperclass
us does not have a table that
Attributes declared in
a
In contrast, n
a mapped
e rn tonitsdirectly.
corresponds e Instead, the attributes declared in a mapped
H
alsuperclass e
r n l e licmap to a table that corresponds to the inheriting entity
B e ab subclass.
s t o r
fe Mapped superclasses cannot be passed as arguments to methods of the
e s
rn -tran EntityManager or Query interfaces. A mapped superclass cannot
E
arlos non be the target of a persistent relationship.
C
Code 6-5 Mapped Superclass Example
1 @MappedSuperclass
2 public class Employee {
3 @Id
4 protected Integer empId;
5 @Version
6 protected Integer version;
7 @ManyToOne
8 @JoinColumn(name="ADDR")
9 protected Address address;
10
11 public Integer getEmpId() { ... }
12 public void setEmpId(Integer id) { ... }
13 public Address getAddress() { ... }
14 public void setAddress(Address addr) { ... }

6-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Inheriting Using a Mapped Superclass

15 }

Code 6-6 Example of an Entity Extending a Mapped Superclass


1 // Default table is FTEMPLOYEE table
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

2 @Entity
3 public class FTEmployee extends Employee {
4 // Inherited empId field mapped to FTEMPLOYEE.EMPID
5 // Inherited version field mapped to FTEMPLOYEE.VERSION
6 // Inherited address field mapped to FTEMPLOYEE.ADDR fk
7 protected Integer salary; // Defaults to FTEMPLOYEE.SALARY
8
9 public FTEmployee() {}
s a
10 public Integer getSalary() { ... }
) h a
m x 11 public void setSalary(Integer salary) { ... }
}
t g ob 12
s a de
Code 6-7 Second Example of an Entity Extending
a l@ i
a MappeduSuperclass
n
er dent G
1 @Entity b
to Stu
2 @Table(name="PT_EMP") e s
3 @AssociationOverride(name="address", ( e rn this
4 e z use
joinColumns=@JoinColumn(name="ADDR_ID"))
d
5 public class PartTimeEmployee
r n an e extends
to Employee {
6 // Inherited empId e
H icfield
field s
en mapped to PT_EMP.VERSION
mapped to PT_EMP.EMPID
// Inheritedalversion l
ernfield
7
8 // addressB a b lemapping overridden to PT_EMP.ADDR_ID fk
9
e s to sfer
@Column(name="WAGE")
10 rn protected
E - t r an Float hourlyWage;
rlos12 nopublic
n
11
C a PartTimeEmployee() {}
13 public Float getHourlyWage() { ... }
14 public void setHourlyWage(Float wage) { ... }
15 }

Note For more information on the AssociationOverride annotation, see


Advanced Java Persistence API Concepts.

Entity Inheritance and Object-Relational Mapping 6-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Inheriting From a Non-Entity Class

Inheriting From a Non-Entity Class


You can create an entity class that inherits from either a concrete or abstract non-
entity class.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The purpose of inheriting from a non-entity class is to inherit the behavior


of the non-entity parent and not the state. All inherited attributes are
transient.
The state declared in the entity class is persistent. The state declared in the
non-entity superclass is not persistent.
This non-persistent state is not managed by the EntityManager, nor
s a
is it required to be retained across transactions.
) h a

m x
Annotations declared on the entity class are processed. Any annotations on
non-entity superclasses are ignored.
t g ob
s a ofdthee
ui
Non-entity classes cannot be passed as arguments to methods
EntityManager or Query interfaces and cannot n a l@ mapping
carry G
information. b er dent
e s to Stu
Code 6-8 Example of a Non-Entity
( e rnClassthforisUse as a Superclass
d e z use
1 public class Cart {
r n an e to
2 e ens
// This state is transient
H
3 l
a e lic
Integer operationCount;
n
r
Be e{rabl
4
5 publictoCart()
6 n e s nsf = 0;
operationCount
7
s Er} n-tra
C arl8o no
9 public Integer getOperationCount() {
10 return operationCount;
11 }
12
13 public void incrementOperationCount() {
14 operationCount++;
15 }
16 }

Code 6-9 Example of an Entity Inheriting From a Non-Entity Class


1 @Entity
2 public class ShoppingCart extends Cart {
3 int id;
4 Collection<Item> items = new Vector<Item>();
5 public ShoppingCart() {

6-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Inheriting From a Non-Entity Class

6 super();
7 }
8 //...
9
10 @Id
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

11 public int getId()


12 return id;
13 }
14 @OneToMany
15 public Collection<Item> getItems() {
16 return items;
17 }
18 public void addItem(Item item) { s a
19 items.add(item); ) h a
20 incrementOperationCount(); m x
21 }
t g ob
} 22 s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Entity Inheritance and Object-Relational Mapping 6-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using an Embeddable Class

Using an Embeddable Class


You can create an entity class that embeds another class defined by the Java
Persistence API as an embeddable class.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

An embeddable class is a fine grained class that encapsulates common state


used by many domain classes. An entity class then embeds the embeddable
class.
Embeddable classes are appropriate for the expression of composition
relationships.
For example, an Address class would make a good candidate for being
marked as an embeddable class. The states represented by an Address
s a
class (street, city, postal code, country) are commonly required in many
) h a
m x
domain classes that represent the customer, employee, and supplier.

t
It would be inappropriate for a class that has an Address g ob to inherit
field
from the Address class. s a de
n a l@ Gui

er didentity.
Embeddable class instances do not have persistent
only as embedded objects of the entityotobwhich they e nt Instead, they exist
t
esrequirement
S tu belong.
Embeddable classes must meetrn the is for an entity class. However,
( e
z uswith
embeddable classes are annotated t h
e the Embeddable annotation instead of
d e
r n an e to
the Entity annotation.
H
The Java e enAPI
Persistence s specification allows for classes to embedded to any
l c
e rna ble li
depth.

t o B erFor
a example, a Person class could have an embedded Address class
s s f
E rne -tran which contains an embedded PhoneNumber class.
s non
C arlo Defining Entity Classes by Using an Embeddable Class
The rules for defining an embeddable class are the same as those used for defining
an entity class with one important exception: embeddable classes do not support
inheritance. Annotate the embeddable class with the Embeddable annotation
instead of the Entity annotation.

Code 6-10 Example of an Embeddable Class


1 @Embeddable
2 public class Address implements Serializable {
3 String addressLine1;
4 String addressLine2;
5 String city;
6 String postalCode;
7 String country
8
9 public Address() {}
6-14 Building Database-Driven Applications With the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using an Embeddable Class

10 }

Code 6-11 Example of Using an Embedded Class


1 @Entity
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

2 public class Customer implements Serializable {


3 @Id
4 private int custId;
5 private String name;
6 @Embedded
7 private Address address;
8
9 public Customer() { }
s a
10
) h a
11 //...
m x
} 12
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Entity Inheritance and Object-Relational Mapping 6-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using an Embeddable Class

Embedded Classes With Relationships


Embedded classes can have nested relationships. For example, the embedded
Address class can have a one-to-many relationship with the Phone class.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 6-12 Example of an Embeddable Class With a Relationship


1 @Embeddable
2 public class Address implements Serializable {
3 String addressLine1;
4 String addressLine2;
5 String city;
s a
6 String postalCode;
) h a
7 String country
m x
8
9
@OneToMany(mappedBy=address) t g ob
s a de
10
private List <PhoneNumber> phoneNumbers;
n a l@ Gui
er dent
} 11
b
to Stu
e s
Note Embeddable classes can also
( e rnbe stored
thiinsa collection
collections. For example. in
d e z
Code 6-11, the Customer entity could
u s e
contain of Address

r n anmoreeinformation
embeddable classes. For to on collections, see Persisting Enums
e ens
and Collections.
H
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

6-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 7
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Persisting Enums and Collections

Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
t g ob
Persist entities that contain enums with @Enumerated
s a de
a l@ Gui
Persist entities that contain lists with @ElementCollection
n
Persist entities that contain maps with b er dent
@ElementCollection
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C

7-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

7-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

Introduction
Up to this point, the focus has been on persisting entities and describing
relationships between entities. For example, recall the one-to-many relationship
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

that an Auction entity shares with a Bid entity.

<<entity>> 1 * <<entity>>
Auction Bid

s a
) h a
m x
1 1 <<entity>>
t g ob
Item
s a de
n a l@ Gui
b r entRelationships
eAssociation
Figure 7-1
to Stud
Object Model Showing Object
e s
( e rn tAssociation
Code 7-1 Bidirectional One-to-Many his Example
e z s e
@Entity
n a nd to u
public class Auction { er
H e n se
@Id
r n al e lic
private int e
B b
auctionId;
a l
s to sfer
@OneToMany(mappedBy=auction)
e
E r an
rn -tCollection
private <Bid> bids;
s..// n
C arlo } no
Code 7-2 Bidirectional Many-to-One Association Example
@Entity
public class Bid {
@Id
private int bidId;
@ManyToOne
private Auction auction;
..//
}

This module explores persisting entities that have fields that contain non-entity
values such as enums and collections of primitives and simple Strings.

Persisting Enums and Collections 7-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

Persisting Entities With Enums


An enumeration is a set of named constants. The Auction class requires the use
of an enumeration to represent the possible values for the Status field.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The Auction domain object represents a single online auction within the auction
application. The Auction domain object contains the following attributes:
auctionID attribute A unique identity for the Auction object.
startAmount attribute The start amount specified by the seller.
increment attribute The minimum bid increment.
s a
status attribute The auction status. Status values are OPEN, CLOSED,
) h a
m x CANCELLED.
openTime attribute The start time of the auction. t g ob
s a de
l@ Gui
closeTime attribute The close time of the auction.
n a
b er dent
e s to Stu
( e rn thsupport
is for enumerated types via the
enum keyword. Prior tonthat,
z
Java Standard Edition 5 introduced
e
language
de thetostandard
us way to represent an enumerated type
was the int enumrn a e example, the following code represents the status
pattern. For
e n s
H ice enum pattern.
a l
of an Auction using the int
e rn ble l
t o B 7-3eraint Enum Pattern (Used Prior to Java SE 5)
Code
n e s nsf
Erclass
public
s n - ra
tAuction{
arlo public
no static final int STATUS_OPEN = 0;
C public static final int STATUS_CLOSED = 1;
public static final int STATUS_CANCELLED = 2;

private int status;

public int getStatus(){


return status;
}

public void setStatus(int status){


this.status = status;
}

//...
}

7-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

This pattern has many disadvantages:


Not typesafe - You can pass in any other int value where a Status is
required, or add two Status values together (which makes no sense).
No namespace - You must prefix constants of an int enum with a string,
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

in this case, STATUS_, to avoid collisions with other int enum types.
Brittleness - Because int enums are compile-time constants, they are
compiled into clients that use them. If a new constant is added between two
existing constants or the order is changed, clients must be recompiled. If the
clients are not recompiled, they will still run, but their behavior will be
undefined.
Printed values are uninformative - If you print one of the constant values, s a
all you get is a number, which tells you nothing about what the value ) h a
m x
ob
represents or even what type it is.
t
a de g
s
n a l@ Gui
Declaring a new enum type for Status solves these shortcomings.

b r values
Typesafe - The status field now acceptseonly
e n tof the Status type.
tud Status.OPEN,
to namespaced:

e s
Namespace - All enums are implicitly
S
e rn this
Status.CLOSED, Status.CANCELLED.
(
Non-Brittle - Enumd e zvaluesuhave
s e an internal ordinal value but because you
n n by value
aenum to name, reordering the definition of enum values
r
refer to the
e enOPEN, e
s CLOSED) has no effect on compiled code.
l H
(CANCELLED,
c
a evalues
rn Printedl li are informative - Printing the value of an enum displays
e
B ethe b text, not the ordinal value.
aenum
t o f r
r n es rans
s E n-t Code 7-4 Declaring an Enum (Used Starting With Java SE 5)
ar l o no
C public enum Status{
OPEN, CLOSED, CANCELLED
}

@Entity
public class Auction{

private Status status;

public int getStatus(){


return status;
}

public void setStatus(Status status){


this.status = status;
}

Persisting Enums and Collections 7-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

//...
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note Only a class can be an Entity. Enums and interfaces may not be annotated
with the @Entity annotation.

By default, the Java Persistence API will map the Status enum to an integer
column. The column value is result of the ordinal() call on the enum.

Persisting the ordinal instead of the enum value can introduce brittleness back
s a
into the code if the order of the enum values change. To avoid this problem, use
) h a
m x the @Enumerated annotation on the Status field.

t g ob
The @Enumerated annotation accepts a value of EnumTypesenum. a Code d e 7-5
demonstrates the use of the @Enumerated annotation. l@
a t Gu i
r n
e den
Table 7-1 Acceptable Values for the @Enumerated Annotationo b
n e st S tu
Value Default
z (er e this Description
e us
EnumType.ORDINAL yes and t o Persist enumerated type
r
e ensn e property or field as an integer
l H c
EnumType.STRING rna l e li Persist enumerated type
B e b
s t o sfera property or field as a string

E rne -tran
rlos non
Code 7-5 Using the @Enumerated Annotation to Persist the Status enum as
C a a String
public enum Status{
OPEN, CLOSED, CANCELLED
}

@Entity
public class Auction{

@Enumerated(EnumType.STRING)
private Status status;

public int getStatus(){


return status;
}

public void setStatus(Status status){

7-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

this.status = status;
}

//...
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Because of the @Enumerated(EnumType.STRING) annotation, the Java


Persistence API will map the Status enum to an VARCHAR column. The column
value is result of the name() call on the enum.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Persisting Enums and Collections 7-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

Persisting Entities With Lists


Sometimes you might need to persist an Entity that has a list of simple values
instead of other entities.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Item item auction


Auction
itemID : Integer 1 1 1
bids
description : String * *
image : String auctions
Bid
...
1 *
seller bids
s a
1 ) h a
BookItem AuctionUser
m x
t g ob bidder

Figure 7-2 s a de
Item Domain Object
n a l@ Gui
b er fordesale
ntin an auction. The
The Item domain object represents the article
e s toattributes:
offered
S tu
r n
Item domain object contains the following
histhe item.
itemID attribute Ae z (eidentity
e tfor

a n
d to us
unique
description
e rn nse The items description.
attribute
a
image
n lHattributeiceThe location of an image of the item.
l
e r l e
t o B ethat
Suppose f r abafter the customer sees the initial design, you are tasked with
r n es rmodifying
a n s Item so that it can store a list of keywords. Since the keywords are
s E n-t simple strings, do not add unnecessary complexity to the application by creating
ar l o no a Keyword entity.
C
If you annotate the list with the @ElementCollection annotation, the Java
Persistence API will create a separate collection table to store the values of the
list.

Note You may also use the @ElementCollection annotation with a set,
collection, or map. An @ElementCollection can also contain embeddables.

The collection table name is the name of the entity concatenated with the
name of the field separated with an underscore.
In this case, a new table will be created named ITEM_KEYWORDS.

7-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

An implicit one-to-many relationship is created between the ITEM and


ITEM_KEYWORDS table.

Code 7-6 Item Entity With a List of Keywords Annotated With the
@ElementCollection Annotation
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

@Entity
public class Item{

@Id
private int itemId;
private String description;
s a
private String image;
) h a
@ElementCollection
m x
private List<String> keywords;
t g ob
s a de
//...
n a l@ Gui
}
b er dent
e s to Stu
( e rn this
d e z use
Overriding theaDefault
n n to
Collection Table Name
r
e ens e
l H
a the ic collection table name, use the @CollectionTable
To override
r n l e ldefault
B eannotation
a bwith the name attribute.
o
st nThe fe r
r n e s
a @CollectionTable annotation has many elements that can be used to
E
s non - t r
arlo
further refine the mapping to the default collection table.
C Table 7-2 Elements of the @Column Annotation

Name Type Default Description

catalog String The name of the catalog


joinColumns JoinColumn[] empty An array of JoinColumn
annotations
name String The name of the table
schema String The name of the schema
uniqueConstraints UniqueContraint[] empty An array of UniqueConstraint
annotations

Persisting Enums and Collections 7-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

Code 7-7 Overriding the Default Collection Table Name With the
@CollectionTable Annotation.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

@Entity
public class Item{

@Id
private int itemId;
private String description;
private String image;
s a
@ElementCollection
) h a
@CollectionTable(name = TAGS)
m x
private List<String> keywords;
t g ob
s a de
//...
n a l@ Gui
}
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

7-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

Persisting Entities With Maps


Sometimes you might need to persist an entity that has a map of simple values
instead of other entities. Collections of entity elements and relationships may be
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

represented by java.util.Map collections. A Map consists of a key and value.

When using Map elements or relationships, the following rules apply:


The Map key or value may be a basic Java programming language type, an
embeddable class, or an entity.
When the Map value is an embeddable class or basic type, use the
@ElementCollection annotation. s a
) h a
m x When the Map value is an entity use the @OneToMany or @ManyToMany

t g ob annotation.

s a de
Only use the Map type on one side of a bidirectional relationship.

n a l@ Gui
If the Map key is the primary key, or a persistent
b er fielde t
ornproperty of the entity

e s to Stud
that is the Map value, use the javax.persistence.MapKey annotation. The
@MapKeyClass and @MapKey annotations
e r n his cannot be used on the same field or
property. z ( e t
e
nd to u s
If Map value isrn aa s e
Java programming language basic type or an embeddable class,
e n
lH
it will be
a mappedcasea collection table in the underlying database. If generic types
i
earer n
not l
used, ethel @ElementCollection annotation's targetClass attribute
t o B musteberasetb to the type of the Map value.
n e s nsf
s Er n-tra If the entity is part of a one-to-many/many-to-one bidirectional relationship, it
arlo no will be mapped in the table of the entity that represents the value of the Map. If
C generic types are not used, the targetEntity attribute of the @OneToMany and
@ManyToMany annotations must be set to the type of the Map value.

Entity Map Example

Suppose that the customer would like to have the ability to store an arbitrary
number of additional key/value pairs of information about the Item in a Map
field named miscInfo. These values are not consistently used from Item to
Item, so an enum or formal entity cannot be used.

The following lists some possible values that might be stored for an Item:
Warranty : yes
Manufacturer : Acme
Condition : Slightly used

Persisting Enums and Collections 7-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

If you annotate the map with the @ElementCollection annotation, the Java
Persistence API will create separate collection table to store the values of the
map.
The collection table name is the name of the entity concatenated with the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

name of the field separated with an underscore.


In this case, a new table will be created named ITEM_MISCINFO.
The map key is stored in a field named MISCINFO_KEY.
The map value is stored in a field named MISCINFO.
The datatype of the columns is based on the Generic types of the key and
value in the map declaration.
s a
) h a
Code 7-8 x
Defining a Map Field Using the @ElementCollection Annotation.
m
t g ob
@Entity s a de
public class Item{ n a l@ Gui
b er dent
@Id
e s to Stu
private int itemId;
( e rn this
private String description;
d e z use
private String image;
r n an e to
@ElementCollection
H s
e enmiscInfo;
l c
rna ble li
private Map<String, String>
e
//... to B e ra
s s f
}
E rne -tran
s non
C arlo Note Map keys can be entities as well as simple types.

Overriding the Default Collection Table Name

To override the default collection table name, use the @CollectionTable


annotation with the name attribute.

Code 7-9 Overriding the Default Collection Table Name With the
@CollectionTable Annotation

@Entity
public class Item{

7-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

@Id
private int itemId;
private String description;
private String image;
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

@ElementCollection
@CollectionTable( name = additional_info)
private Map<String, String> miscInfo;

//...
}

s a
) h a
m x
Overriding the Map Key Column Name
t g ob
s a de
n a l@ Guiannotation with
To override the Map key column name, use the @MapKeyColumn
the name attribute.
b er dent
Code 7-10 Overriding the Map n e to SName
sColumn tu With the @MapKeyColumn
(er e this
Key
Annotation
z
de to us
a n

@Entity e rn nse
public class Item{al H l i c e
n
er able
@Id to
B er
e s s f
n itemId;
E n traint
rprivate
o s non -
private String description;
r l
Ca private String image;
@ElementCollection
@CollectionTable( name = additional_info)
@MapKeyColumn( name = name)
private Map<String, String> miscInfo;

//...
}

Persisting Enums and Collections 7-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction

Overriding the Map Value Column Name

To override the Map value column name, use the @Column annotation with the
name attribute.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 7-11 Overriding the Map Value Column Name With the @Column
Annotation

@Entity
public class Item{

@Id s a
private int itemId;
) h a
private String description; m x
private String image;
t g ob
@ElementCollection s a de
n a l@ Gui
@CollectionTable( name = additional_info)
@MapKeyColumn( name = name)
b er dent
@Column( name = value)
e s to Stu
( e rn this
private Map<String, String> miscInfo;

//... d e z use
} r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

7-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 8
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Introduction to Querying

Objectives a
h a s
x )

Upon completion of this module, you should be able to: m
t g ob
Find an Entity by its primary key
s a de
Understand basic Java Persistence API querya
n language ui
l@ Gqueries
Understand native SQL queries b er dent
e s to Stu

( e rn this
Understand basic Criteria API queries

d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

8-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.
Sun Microsystems, The Java EE 6 Tutorial, Chapter 18,
[http://java.sun.com/javaee/6/docs/tutorial/doc/], accessed
September 15, 2009.
s a
The Eclipse Foundation, Using EclipseLink JPA Extensions (ELUG),
) h a
[http://wiki.eclipse.org/
m x
15, 2009. t ob
Using_EclipseLink_JPA_Extensions_(ELUG)], accessed September
g
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

8-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction to Querying Entities

Introduction to Querying Entities


The Java Persistence API provides several mechanisms to query entities. These
mechanisms are:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The Entity Manager methods find()


Queries written in the Java Persistence query language
Queries written in native SQL
Queries written using the Criteria API

Each mechanism will be explored in greater detail in this module. s a


) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Introduction to Querying 8-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Querying Using the Entity Manager

Querying Using the Entity Manager


For simple querying, use the Entity Manager. For example, if you already know
the primary key of an Entity, you can use the find() method to return the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

instance.

Code 8-1 Calling the find() Method on an Entity Manager


1 public ItemDao {
2 @PersistenceContext
3 private EntityManager entityManager;
4
s a
5 public Item find(Integer key) {
) h a
6 return entityManager.find(Item.class, key);
m x
7 }
t g ob
8
s a de
// ... 9
n a l@ Gui
} 10
b er dent
e s to Stu
( e rn this
0
d e z use
r n an e to
H e ensbe found based on the primary key provided, a null
n l
Note If the
a e lic
entity cannot
value r
e abl
is returned.
B
to sfer
e s
E an the find() method of the entity manager provides rudimentary querying
rn -trWhile
s non capabilities, you will most likely need to perform more sophisticated queries as
C arlo well. The Entity Manager also provides the ability to create Query objects.

8-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Query Objects

Examining Query Objects


A Query object is an instance of the javax.persistence.Query interface. A
Query object contains criteria defined using a Java Persistence Query Language
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

query string or a native SQL query string. This section provides a brief
introduction to query objects.

Dynamic Queries
A dynamic query is an ad hoc query that is created at the point and then executed.
s a
Dynamic queries are not as performant as static queries if they are called
) h a
m x
repeatedly, therefore, they should only be used in situations where the query is

ob
not known at the time you are writing the code.
t g
a in JDBC.
A dynamic query is analogous to a java.sql.Statement s i d e
r n al@ t Gu

A dynamic query object is created by callingb ethe createQuery()
d e n method of an
t o t u
r n es is S
entity manager instance. For example:

z (e e th
Query query = entityManager.createQuery(queryString);
a n
de to us
e rn nse
Named Queries
n a l H lice
B er able
e s f er query is declared on an entity using the @NamedQuery annotation. A
to Asnamed
E rn -trannamed query is precompiled, and therefore is appropriate for queries that will be

r l o s non called many times.


C a
A named query is analogous to a java.sql.PreparedStatement in JDBC.

A named query object is created by calling the createNamedQuery() method


of an entity manager instance. For example:
Query query = entityManager.createNamedQuery(queryName);

Query Execution
The getResultList() method executes the equivalent of a SQL select query
and returns the result as a list object. To return a single object, use the
getSingleResult() method. For update or delete queries, use the
executeUpdate() method. For example:
// Returns a List of Items

Introduction to Querying 8-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining Query Objects

List items = query.getResultList();

// Returns a single Item


Item item = query.getSingleResult();
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

// Returns the number of Items affected


// by the update or delete query
int results = query.executeUpdate();

The Query interface offers two methods to facilitate paging through multiple
pages of results. The setMaxResults() method sets the maximum number of
results to retrieve. The setFirstResult() method sets the position of the first
result to retrieve. For example, to return the third page of results with 10 results s a
to a page: ) h a
m x
int resultsPerPage = 10;
t g ob
query.setFirstResult(3 * resultsPerPage);
s a de
query.setMaxResults(resultsPerPage);
n a l@ Gui
List page3 = query.getResultList();
b er dent
e s to Stu
Note Java Persistence API version( e rn2.0 introduces
this the
javax.persistence.TypedQueryd e z u e
sinterface. The TypedQuery interface
n n

a For
enables the use of generics. o
tmore information on the TypedQuery interface,
e r n s e
a l HCriteria
see Using the
i c eAPI.
l
B ern able
e s to sfer
E rn -tran
s non
C arlo

8-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Setting Query Object Metadata

Setting Query Object Metadata


You can adjust the behavior of a Query object or a TypedQuery object by
setting metadata on it. Examples of methods that enable you to set the metadata
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

include setFlushMode(), setLockMode(), and setHint().

Setting the Flush Mode


The setFlushMode() method sets the flush mode type to be used for the query
execution. The flush mode type applies to the query regardless of the flush mode
s a
type in use for the entity manager.
) h a
m x
t g ob
The setFlushMode() method accepts a value of FlushModeType enum.

Table 8-1 Acceptable Values for the setFlushMode() Method s a de


n a l@ Gui
Value Default
b er Description
e n t
e s to Stud
FlushModeType.AUTO yes
e r n his Flushing to occur at query
z ( e t execution
e
nd to u s
FlushModeType.COMMIT
r n a e
Flushing to occur at
H e ens transaction commit
l c
e rna ble li
t o B Codee8-2
ra Setting the Flush Mode of a Query Object
s s f
rne -tran
query.setFlushMode(FlushModeType.COMMIT);
E
s non
C arlo

Setting the Lock Mode


The setLockMode() method sets the lock mode type to be used for the query
execution.

Note For more on locking semantics, see Implementing Transactions and


Locking.

Introduction to Querying 8-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Setting Query Object Metadata

The setLockMode() method accepts a value of LockModeType enum.

Table 8-2 Acceptable Values for the setLockMode() Method

Value Description
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

LockModeType.NONE No locking
LockModeType.OPTIMISTIC Causes the persistence provider
to verify that the entity data has
not been changed by another
transaction since it was read
from the database.
s a
LockModeType.OPTIMISTIC_FORCE_INCREMENT Equivalent to OPTIMISTIC, and
) h a
m x additionally increments the

t g ob version attribute.
LockModeType.READ The same as s a de
n a l@ Gui
LockModeType.OPTIMISTIC
b e r ent
LockModeType.WRITE toThe t asd
same u
e s S
( e rn tFORCE_INCREMENT
his
LockModeType.OPTIMISTIC_

e z e
us Causes the persistence provider
LockModeType.PESSIMISTIC_READand t o
e rn nse to lock the underlying database
l H
a e li c e records for duration of a
r
e abn l transation.
B
to sfer
e s n
LockModeType.PESSIMISTIC_WRITE
n Causes the persistence provider
r
E n-t r a to lock the underlying database
s
C arlo no records when they are read until
the write transaction completes.
LockModeType.PESSIMISTIC_FORCE_INCREMENT Equivalent to
PESSIMISTIC_READ or
PESSIMISTIC_WRITE and
additionally increments the
version attribute.

8-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Setting Query Object Metadata

Note For more information on optimistic and pessimistic locking, see


Implementing Transactions and Locking.

Code 8-3 Setting the Lock Mode of a Query object.


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

query.setLockMode(LockModeType.OPTIMISTIC);

Setting Hints s a
) h a
m x
The setHint() method sets a standard query property, a standard b hint, or
goquery
an implementation-specific hint. It accepts two arguments: a thethint
name and the
s
ignored. id
value. If the hint name is not recognized, it is silentlyl@ e
n a G u
b r
e properties:
e n t
o d
n e st
The Java Persistence API defines the following
S tu

(er e this
javax.persistence.cache.retrieveMode
z

a n
de to us
javax.persistence.cache.storeMode

e rn nse
n a l H limust
These properties
c e be observed by the persistence provider.
B eTher JavaabPersistence
le
s t o sfer API defines the following hint:

E rne -tran javax.persistence.query.timeout


arlos non
C Note Portable applications should not rely on the
javax.persistence.query.timeout hint. This hint may not be observed
by persistence providers or databases.

Hints can also be database-specific. Consult the documentation of your


persistence provider for a full list of the possible hints.

Some of the hints supported by EclipseLink are:


eclipselink.cache-usage
eclipselink.query-type
eclipselink.jdbc.bind-parameters
eclipselink.pessimistic-lock

Introduction to Querying 8-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Setting Query Object Metadata

eclipselink.refresh
eclipselink.refresh.cascade
eclipselink.batch
eclipselink.join-fetch
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

eclipselink.read-only
eclipselink.jdbc.timeout
eclipselink.jdbc.fetch-size
eclipselink.jdbc.max-rows
eclipselink.result-collection-type
s a
) h a
m x Code 8-4 Setting an EclipseLink-Specific Hint on a Query Object
import org.eclipse.persistence.config.HintValues; t g ob
s a de
import org.eclipse.persistence.config.QueryHints;
n a l@ Gui
er dent
query.setHint(QueryHints.READ_ONLY, HintValues.TRUE);
b
to Stu
e s
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C

8-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the Java Persistence API Query Language

Introducing the Java Persistence API Query Language


The Java Persistence API query language is a string-based query language used to
define queries over entities and their persistent state. It enables the application
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

developer to specify the semantics of queries in a portable way, independent of


the particular database schema in use in an enterprise environment. The full range
of the language may be used in both static and dynamic queries.

The following steps outline the process required to use Java Persistence API
query language statements and query objects. In particular, note the requirement
to wrap Java Persistence API query language statement strings using query
objects of type javax.persistence.Query, shown in Step 2. s a
) h a
m x 1. Create Java Persistence API query language statement string.
String queryString = SELECT o FROM Order o +
t g ob
WHERE o.shippingAddress.state = CA;
s a de
This select statement returns Order objects
n a G ui address in
@ a shipping
lwith
the state of California.
b er dent
2. Create a query object wrapperefor s tothe JavaStPersistence
u API query language
e r n h i s
z ( e t
string, of type javax.persistence.Query interface.
// Assume entityManager references e
nd tan s
uEntityManager object
n a
r nse o
Query query = entityManager.createQuery(queryString); // create Query
e
3. a
n l H thelicquery
Execute e object.
List orders B=e
r b le
t o f e r a
query.getResultList(); // execute Query

r n es rans
s E n-t
ar l o no
C

Introduction to Querying 8-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing Native Queries Using SQL

Introducing Native Queries Using SQL


Queries may be expressed in native SQL. The result of a native SQL query may
consist of entities, scalar values, or a combination of the two. The entities
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

returned by a query may be of different entity types.

The SQL query facility enables you to use the native SQL of the target database
when the Java Persistence API query language cannot be used. Native SQL
queries are not expected to be portable across databases.

The following steps outline the process required to use SQL statements and query
objects. In particular, note the requirement to wrap SQL statement strings using s a
query objects of type javax.persistence.Query, shown in Step 2. ) h a
m x
1. Create SQL statement string.
t g ob
String queryString = SELECT * FROM ORDER WHERE STATE = CA; s a de
This select statement returns Order objects n a
withl@ G
a shippinguiaddress in
the state of California. b er dent
e s toSQL string,
S tu of type
2. Create a query object wrapper for n the
is that you must pass in the
javax.persistence.Query
z (erinterface.
e thNotice
a n
de to us
class type for the results.
// Assume entityManager references e rn nsean EntityManager object
a l H lice
Query query = entityManager.createNativeQuery(queryString,
n
Order.class);
r
eExecute b lequery object.
B
3.
er a the
t=o query.getResultList();
List orderse s n s f // execute Query
r n
E n-t r a
r l o s no Note When an entity is being returned, the SQL statement should select all of
C a
the columns that are mapped to the entity object, including foreign key columns
to related entities. The results obtained when insufficient data is available are
undefined.

8-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the Criteria API

Introducing the Criteria API


The Java Persistence Criteria API is used to define queries through the
construction of object-based query definition objects, rather than the string-based
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

approach of the Java Persistence query language. However, strings can be used to
specify joins and path navigation in the Criteria API.

The syntax of the Criteria API is designed to allow the construction of an object-
based query graph, whose nodes correspond to the semantic query elements.

Java Persistence criteria queries are based on a metamodel of the managed classes
of the persistence unit. This metamodel can be accessed dynamically. In s a
addition, static metamodel classes that capture the state of this metamodel can be ) h a
m x generated at development time.
t g ob
The Java Persistence API specification defines a canonical s arepresentation
d e of the
l@ Gu
metamodel in terms of static metamodel classes asafollows.
i
r n
e dent
b
to unit,Satcorresponding
u
n e s
For every managed class in the persistence metamodel class
is produced as follows:
z (er e this
For each managed
a n
declasstoX uinspackage p, a metamodel class X_ in package
rn nse
p is created.
e

n a l Hnameloficthe
The e metamodel class is derived from the name of the managed
B er classa b leappending "_" to the name of the managed class.
by
s to sfeTher metamodel class X must be annotated with the
e
rn -tran javax.persistence.StaticMetamodel annotation.
E
arlos non If class X extends another class S, then class X_ must extend S_.
C
For every persistent attribute Y of class X, the metamodel class must
contain a declaration like public static volatile
SingularAttribute<X,Y> y.
For every persistent collection attribute of class X, the metamodel class must
contain declarations like public static volatile
CollectionAttribute, SetAttribute, ListAttribute, or
MapAttribute.

Note The software developer typically creates the static metamodel using the
tools provided by the persistence provider.

Introduction to Querying 8-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the Criteria API

The following steps outline the process required to use Criteria API objects and
query objects. In particular, note the requirement to wrap criteria objects using
query objects of type javax.persistence.TypedQuery, shown in Step 2.
1. Create the criteria object.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> criteria = cb.createQuery(Person.class);
Root<Person> person= criteria.from(Person.class);
Predicate condition = cb.gt(person.get(Person_.age), 40);
criteria.where(condition);
This criteria object returns Person objects with an age greater than 40.
2. Create a TypedQuery object wrapper for the criteria object, of type
s a
javax.persistence.TypedQuery interface.
) h a
// Assume entityManager references an EntityManager object m x
TypedQuery<Person> query = entityManager.createQuery(criteria);
t g ob
s a de
3. Execute the query object.
n a l@ Gui
List<Person> orders = query.getResultList();
b er dent
e s to Stu
Note The Criteria API enables(youe rnto avoid is use of strings, enabling the use
ththe
of strongly typed criteria d
z
e instead.
objects e
us Typos can accidentally occur in a Java
a n

n sstring. t o
Persistence query rlanguage
e n e However, the Criteria API allows the use of

a l H ice
strings as well. For more information, see Chapter 6, Criteria API of the Java
l
ern aAPI,
Persistence
B b leVersion 2.0 specification.
e s to sfer
E rn -tran
s non
C arlo

8-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Named Queries

Using Named Queries


Named queries are static queries expressed in metadata. Named queries can be
defined in Java Persistence API query language or in SQL. Query names are
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

scoped to the persistence unit.

A named query is first specified using the NamedQuery metadata annotation. It is


then created using the createNamedQuery method of the entity manager. The
NamedQuery annotation can be applied to an entity or mapped superclass.

Code 8-5 Named Query Declaration Example


s a
1 @Entity
) h a
2 @NamedQuery(name="FindAllAuctions",
m x
3 query="SELECT a FROM Auction a")
t g ob
4 public class Auction{
s a de
5 // ...
n a l@ Gui
6 }
b er dent
e sto Stu
Code 8-6 Using Named QuerynExample
z ( er e this
// This is a code snippet e
1
2 // Assume entityManageran
d to usan instance of an EntityManager
references
3 Query query = e rn nse
4 a l H lice
entityManager.createNamedQuery("FindAllAuctions");
n
5
B er =aquery.getResultList();
List auctions b le
6 s
// ...
e to sfer
E rn -tran
s non
C arlo

Introduction to Querying 8-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Named Queries

Declaring and Using Named Parameters


Queries allow the use of named parameters. A named parameter of a Java
Persistence query language query is an identifier that is prefixed by the ":"
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

symbol. The parameter names passed to the setParameter() methods of the


Query API do not include this ":" prefix.

For example, the following example defines a query with a named parameter:
Query query = entityManager.createQuery
(select o from Order o where customer.id = :id);

s a
You use the named format of the setParameter() method to set the parameter
) h a
m x
value for the query, as shown in the following code snippet:
int id = 24;
t g ob
query.setParameter(id, id) s a de
List orders = query.getResultList();
n a l@ Gui
b er dent
e s to Stu
Note Named parameters cannot bern is
used in conjunction with native SQL
queries. ( e
z use t h
d e
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

8-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Named Queries

Declaring and Using Positional Parameters


Queries allow the use of positional parameters. A positional parameter of a query
is a number that is prefixed by the "?" symbol.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

For example, the following example defines a query with a positional parameter:
Query query = entityManager.createQuery
(select o from Order o where customer.id = ?1);

You use the positional format of the setParameter method to set the parameter
value for the query, as shown in the following code snippet:
s a
int id = 24; ) h a
query.setParameter(1, id) m x
List orders = query.getResultList();
t g ob
s a de
n a l@ Gui
r enaccess
Note Only positional parameter binding andepositional
b t to result items

to Stud
may be portably used for native queries.
e s
( e rn this
Positional parametersd e
are znot supported
u s e by the Criteria API.
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Introduction to Querying 8-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Named Queries
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

8-18 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 9
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Using the Java Persistence Query Language

Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
Examine the Java Persistence API query language atg
ob

s d e
Create and use the SELECT statement al@ t Gu i
r n
Create and use the UPDATE statementbe e n

st o tu d
Create and use the DELETEn e S
(er e this
statement
z
de to us
a n

e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C

9-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Sun Microsystems, The Java EE 6 Tutorial, Chapter 29,


[http://java.sun.com/javaee/6/docs/tutorial/doc/], accessed
September 15, 2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

9-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the Java Persistence API Query Language

Introducing the Java Persistence API Query Language


Java Persistence API query language is a query specification language for
dynamic queries and for static queries expressed through metadata. Java
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Persistence API query language can be compiled to a target language, such as


SQL, of a database or other persistent store. This feature enables the execution of
queries to be shifted to the native language facilities provided by the database,
instead of requiring queries to be executed on the runtime representation of the
entity state. As a result, queries can be optimized as well as portable.

Note For easy identification, all Java Persistence API query language keywords
s a
used in this module are capitalized. However, Java Persistence API query
) h a
language keywords are not case sensitive.
m x
t g ob
s astatement
d e types.
Java Persistence API query language supports the following
al@ t Gu i
SELECT statement r n
e den
t o b
The Java Persistence API querye slanguage S tu statement returns row
SELECT
n
eras entity
data stored in the database is It can also be used to return
hobjects.
z ( e t
scalar data.
a n
de to us

e n se
UPDATErstatement

a l
The l i c en API query language UPDATE statement updates one or
HJava Persistence
B ern more
a b le instances. Behind the scenes, the updates to the entity instances
entity
s to sfeare r reflected in updates to rows of a specific table in the database.
e
rn -tran DELETE statement
E
s non
C arlo The Java Persistence API query language DELETE statement deletes one or
more entity instances. Behind the scenes, the deletion of entity instances are
reflected in the deletion of one or more rows from a specific table in the
database.

Java Persistence API query language statements consist of Java Persistence API
query language keywords, entity class names, and entity field identifiers.
SELECT o FROM Order AS o
SELECT c.id, c.status FROM Customer c
JOIN c.orders o WHERE o.quantity > 100

Using the Java Persistence Query Language 9-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

Declaring Query Strings: The SELECT Statement


The Java Persistence API query language SELECT statement enables the querying
of entities. This section provides a brief introduction to the constituent clauses of
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

the SELECT statement.


The Java Persistence API query language SELECT statement returns entity
instances from the database table. It can also be used to return scalar data.
A SELECT statement has the following structure:
SELECT_clause FROM_clause [WHERE_clause] [GROUPBY_clause] [HAVING_clause]
[ORDERBY_clause]
s a
) h a
m x
Note The use of [ ] in Java Persistence API query language expression
g ob
examples in this module indicates an optional Java Persistence API query
t
language keyword or clause. s a de
n a l@ Gui
For example:
b er dent
SELECT o FROM Order o e s to Stu
SELECT c.id, c.status FROM Customer c (ern t his
JOIN c.orders o WHERE o.quantity
d z
e > 100 us e
a n
t o
The FROM clause
e risnentity e the search domain. The search domain in the
specifies
n s
a H ice
FROMlclause types.
n
r SELECT l e l specifies what is returned. You can specify the return of
eThe
B entity b clause
ainstances
s t o f e r that correspond to entities specified in the FROM clause.
e s
rn -tran The WHERE clause is optional. It specifies a set of restrictive conditions that
E
s non
arlo
must be met by the entity instances that are selected for return.
C The GROUP BY construct enables the aggregation of values according to the
properties of an entity class. The HAVING construct enables conditions to be
specified that further restrict the query result as restrictions on the groups.
The GROUP BY and HAVING clauses are often used in combination.
Use the ORDER BY clause to order the objects or values that are returned by
the query.

Using Operators in the SELECT Clause


Operators can be used in the SELECT clause of a query. For example:
SELECT o.quantity, o.cost*1.08 AS taxedCost from Order o

9-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

Examining the FROM Clause


The FROM clause specifies the search domain in the persistence tier. This section
describes the FROM clause in detail.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

A FROM clause specifies which persistence entities should be queried by the


SELECT query.
A FROM clause is specified using one or more path expressions. For
example, the FROM clause in the following SELECT statement contains a
single path expression. For clarity, the path expression in the example is
underlined.
SELECT o.quantity FROM Order o s a
) h a
m x The FROM clause in the following SELECT statement contains two path

t g ob expressions. Note that each path expression is separated using a comma.


SELECT DISTINCT o1 FROM Order o1, Order o2 WHERE o1.quantity s a > de
o2.quantity AND o2.customer.lastname = Smith AND l@
n a G ui
o2.customer.firstname = John
b er dent
s
Path expressions are classified as o
tfollows: tu
n e S
Range variable path
z e this
(erexpressions
n
e path
dmember usexpressions
Collection
a t o
ern enstraversing
HAssociation
e path expressions
l c
e rna ble li
t o BRange e raVariable Path Expressions
s s f
E rne -tran A range variable path expression evaluates to a single entity instance (single
arlos non row of a table). The following statements are two examples of range
C variable path expressions.
SELECT o FROM Order o
SELECT o.quantity FROM Order o

Association Traversing Path Expressions

An association traversing path expression is used in queries that involve two


or more entities that have an association relationship. An association
traversing path expression provides SQL-like JOIN query capability. An
association traversing path expression begins with a root entity and then
traverses to a second entity using the association field that links the second
entity to the first.

Using the Java Persistence Query Language 9-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

A join is a rule that defines a relationship by determining which records are


retrieved. A join is a conditional expression that is applied to two or more
tables to retrieve a set of records that meet the condition.
The Java Persistence API supports the following association traversing
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

query capabilities.
Inner joins, also known as relationship joins
An inner join returns all records that meet the join condition.
Left outer joins
A left outer join returns all records that meet the join condition as well
as those that have no matching values.
s a
Fetch joins
) h a
m x
t ob
Fetch joins are variations of the inner and outer joins. A fetch join
g
enables the prefetching of related data items as a side effect of a query.
s a de
The syntax for the inner join operation is:
n a l@ Gui
[INNER]JOIN join_association_path_expression [AS]be r ent
identification_variable
d
toover Stheturelationship
For example, the following queryejoins
n s between
customers and orders. This(type r i s
e ofejointhtypically equates to a join over a
foreign key relationship
d e zin the s
database.
u
a n
t o
SELECT c FROM Customer c JOIN
e rn c.orders
n s e o WHERE c.status = 1
l H lINNER
Theakeyword
n i c e is optional. For example:
B er acbINNER
SELECT c FROM Customer le JOIN c.orders o WHERE c.status = 1
e s to sThe f erfollowing equivalent but less clear form of query omits the JOIN
E rn -tran keyword but keeps the IN keyword. The query selects those customers of
s non
C arlo status 1 for which at least one order exists.
SELECT OBJECT(c) FROM Customer c, IN(c.orders) o WHERE c.status = 1
The syntax for a left outer join is:
LEFT [OUTER]JOIN join_association_path_expression [AS]
identification_variable
For example:
SELECT c FROM Customer c LEFT JOIN c.orders o WHERE c.status = 1
The keyword OUTER is optional. For example:
SELECT c FROM Customer c LEFT OUTER JOIN c.orders o WHERE c.status = 1
The syntax for a fetch join is:
[LEFT [OUTER] |INNER]JOIN FETCH join_association_path_expression
For example, the following query results in the fetching of all employees in
the department that satisfies the join condition.

9-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

SELECT d FROM Department d LEFT JOIN FETCH d.employees WHERE d.deptno =


1
The association referenced by the right side of the FETCH JOIN clause
must be an association that belongs to an entity that is returned as a result of
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

the query. You cannot specify an identification variable for the entities
referenced by the right side of the FETCH JOIN clause. Therefore,
references to the implicitly fetched entities cannot appear elsewhere in the
query.

Note Entities that are prefetched as a result of a fetch join are not part of the
explicit query result.
s a
) h a
m x
t g ob
Collection Member Path Expressions s a de
n a l@ Gui
A collection member path expression is e
b r expression
a path
e n t that evaluates to a
member of a collection. Collection t o
value u
path
t d
expressions are used when a
n s
e anisentity
path expression involves evaluating S field that returns a collection.
( e r
For example, in the following h
patht expression, the state field lineItems
d e z
evaluates to a collection of u s e instances. The variable l evaluates to
LineItem
a specificrn an e instance
LineItem to within that collection.
l HeOrder c e nsIN(o.lineItems) l WHERE
SELECT DISTINCT o aFROM
li o,
rn b=leofficeSupplies
e
l.product.productType
B era
t o
s nsf Note the declaration of the range variable o and the useof the keyword IN
n e
s Er n-tra in the declaration of the collection member variable.

arlo no The previous example can also be expressed using JOIN.


C SELECT DISTINCT o FROM Order o JOIN o.lineItems l WHERE
l.product.productType = 'officeSupplies'

Using the Java Persistence Query Language 9-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

Examining the WHERE Clause


The WHERE clause is optional. It specifies a set of restrictive conditions that must
be met by the entities that are selected for return. This section provides more
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

details about the WHERE clause.


The WHERE clause consists of the WHERE keyword followed by either a
simple conditional expression or a complex conditional expression.
WHERE Simple_Conditional_Expression
WHERE Complex_Conditional_Expression

The syntax for a simple conditional expression is: s a


) h a
m x Operand_1 Conditional_Expression_Operator Operand_2
Operand_1 and Operand_2 can be any of the following:
t g ob
s a indthe
Java Persistence API query language identifiers declared e FROM
clause al@ t Gu i
e r n n
o
Java Persistence API query languagebliteralsde
n e st functions
S tu

z ( er e this
Java Persistence API query language

a n
de to us
Query method parameters

e rn nse
n a l H licExpression
e
Table 9-1 WHERE Clause
B er able
Conditional Types

e s to sfer Conditional Expression


E rn -tran Type Operators
Conditional Expression Operand Type
s non
rloComparison
C a expression =, >, >=, <, <=, <> Arithmetic
Between expression [NOT] BETWEEN Arithmetic, string, date_time
Like expression [NOT] LIKE String
In expression [NOT] IN All types
Null comparison expression IS [NOT] NULL
Empty collection comparison IS [NOT] EMPTY Collection
expression
Collection member expression [NOT] MEMBER OF Collection
Exist expression [NOT] LIKE String

The following SELECT statements demonstrate the use of some of the


conditional operators:

9-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

SELECT o1 FROM Order o1, Order o2 WHERE o1.quantity > o2.quantity


SELECT p FROM Person p WHERE p.age BETWEEN 15 and 19
SELECT a FROM Address a WHERE a.country IN ( UK, US , France )
SELECT o FROM Order o WHERE o.lineItems IS EMPTY
SELECT a FROM Address a WHERE a.phone LIKE 12%3
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note The LIKE operator operates on a string expression. The string expression
must have a string value. The pattern value 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 an empty
sequence, and all other characters stand for themselves.
s a
The syntax for a complex conditional expression is: ) h a
m x
Simple_Cond_Expr_1 Binary_Relational_Operator Simple_Cond_Expr_2
t g ob
s a de
The binary relational operator can be one of the following:
AND n a l@ Gui
b er dent
OR
e s to Stu
For example:
( e rn this
SELECT DISTINCT o1 FROM Order o1,
d e zOrderuso2
e WHERE o1.quantity >o2.quantity
r n an e to
AND o2.customer.lastname = Smith
H e ens
AND o2.customer.firstname= John
rna
l c
li the following types of literals in conditional expressions.
e You can
l euse
B erabString literals like Stephen
t o
s nsf
n e
s Er n-tra Numeric literals like 52 or 3.55

C arlo no Boolean literals like TRUE or FALSE


Date, Time, or Timestamp

Using the Java Persistence Query Language 9-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

Java Persistence API query language defines several functions for use in
expressions in the WHERE clause. Functions are classified as either string
functions or arithmetic functions.

Table 9-2 Java Persistence API query language Functions


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Function Name and Parameters Return Type

CONCAT(String, String) String


SUBSTRING(String, start, length) String
TRIM(char, String) String
s a
LOWER(String) String
) h a
UPPER(String) m x String
LOCATE(String, String [,simple t g ob
int
s a de
arithmetic expression])
n a l@ Gui
LENGTH(String)
b r ent
eint

to int, d
tufloat
ABS(number)
n e s S or double
r
(e e th doublei s
SQRT(double) z
de to us
MOD(int, int) nan int
e r nse
a l H lice
SIZE(Collection_valued_path_expr}
n int
r
e ab l e
t o B er functions operate on strings and return either a string or an integer
e s s f
E rn -tran property of the string operated on. Arithmetic functions operate on numeric
String
s non
C arlo types and return a number. The argument to an arithmetic function can be a
numeric Java technology object type or primitive type.

9-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

Using Subqueries
Subqueries can be used in the WHERE clause of a query. Subqueries are queries
whose results are used by the outer query. For example, the following query finds
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

the highest bid entity.

SELECT b
FROM Bid b
WHERE b.amount = (SELECT MAX(bid.amount) from Bid bid)

You can use one of the following two conventions to specify query method s a
parameters: ) h a
m x
t g ob Positional specification of parameters

s a ofdthe
Positional specification is based on using the position e parameter
in the query method. For example, suppose al@yout have i
ua query method
with the following signature: r n
e den G
o b
public List findAuctionsWithBidsGreaterThan(Double
n e st S tuamount);
(er from
To reference parameters is Persistence API query language
thJava
queries, you z
dewould e
usthe ?1 syntax for the first parameter as shown
use
a n
t o
e rn nse
in the following query:

a H Auction
SELECT DISTINCT aucl FROM
i c e auc, IN(auc.bids) AS b
n l
B er able
WHERE b.amount > ?1

e s to sfer For methods with multiple parameters, you would use ?2 for the
E rn -tran second parameter and ?3 for the third parameter.

arlos non Named specification of parameters


C A named parameter is an identifier that is prefixed by the ":" symbol,
for example:
SELECT DISTINCT auc FROM Auction auc, IN(auc.bids) AS b
WHERE b.amount > :amount

Note You cannot mix the use of the positional parameter convention with the
named parameter convention in the same Java Persistence API query language
query string.

Using the Java Persistence Query Language 9-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

Examining the SELECT Clause


The SELECT clause denotes the query result. More than one value can be returned
from the SELECT clause of a query. In addition to the DISTINCT keyword,
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

operators, and functions, the SELECT clause can contain one or more of the
following elements:
A single identification variable that ranges over an entity abstract schema
type, for example:
SELECT o FROM Order o WHERE o.quantity > 500
An aggregate select expression, for example:
s a
SELECT AVG(o.quantity) FROM Order o
) h a
m x A constructor expression, for example:
SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count)
t g ob FROM
Customer c JOIN c.orders o WHERE o.count > 100 s a de
n a l@ Gui
The optional DISTINCT keyword is used to specify
b erthatdduplicate
e nt values must be
s
eliminated from the query result. For example:
e to Stu
SELECT DISTINCT l.product FROM Order AS ( e ro,n IN(o.lineItems)
this l
z
de to us e
a n

Examining the e rn nsBY
GROUP e and HAVING Clauses
H
al e lic e
r n
eGROUPaBYblconstruct enables the aggregation of values according to the
B
toproperties
The
erof an entity class. The HAVING construct enables conditions to be
e s s f
E an that further restrict the query result as restrictions upon the groups. The
rn -trspecified
arlos non GROUP BY and HAVING clauses are often used in combination. The following
C SELECT statements contain examples of the use of the GROUP BY and HAVING
clauses.
SELECT c.country, COUNT(c) FROM Customer c GROUP BY c.country HAVING
COUNT(c) > 3

SELECT c.status, avg(c.filledOrderCount), COUNT(c) FROM Customer c GROUP


BY c.status HAVING c.status IN (1, 2)

9-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

This section provides more details about the GROUP BY and HAVING clauses.
If a query contains both a WHERE clause and a GROUP BY clause, the effect
is that of first applying the where clause, and then forming the groups and
filtering them according to the HAVING clause.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Any item that appears in the SELECT clause other than as an argument to an
aggregate function must also appear in the GROUP BY clause.
If no GROUP BY clause is included and the HAVING clause is used, the result
is treated as a single group, and the SELECT list can only consist of
aggregate functions. The use of HAVING in the absence of GROUP BY is not
required to be supported by an implementation of Java Persistence
specification.
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Using the Java Persistence Query Language 9-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The SELECT Statement

Examining the ORDER BY Clause


The ORDER BY clause allows the objects or values that are returned by the query
to be ordered. This section provides more details about the ORDER BY clause.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The syntax of the ORDER BY clause is as follows:


ORDER BY orderby_item [ASC | DESC]{, orderby_item [ASC | DESC]}*
If the SELECT clause returns an identification variable, then each ORDER
BY item must be an orderable state-field of the entity type returned by the
SELECT clause. For example:
SELECT o FROM Customer c JOIN c.orders o JOIN c.address a WHERE a.state =
s a
CA ORDER BY o.quantity, o.totalcost
) h a
m x If the SELECT clause returns a single valued path expression, then each

t g ob ORDER BY item must be an orderable state-field of the entity type returned


s a de by the SELECT clause. For example:
SELECT e.address FROM Employee e ORDER BY e.address.zipCode
n a l@ Gui
If the SELECT clause returns a state fieldb er expression
e n t then the ORDER
tud by the SELECT
path
BY item must evaluate to the same e s to Sreturned
state-field
clause. For example: ( e rn this
SELECT o.quantity, a.zipcode FROMde
z usce JOIN c.orders o JOIN
an ORDER
Customer
c.address a WHERE a.state =rn CA e toBY o.quantity, a.zipcode
H e ens
Each
n l
a ascending
ORDER ic item can optionally be followed by the ASC keyword
lBY
r
e ab
denoting l e order or the DESC keyword denoting descending order.
B
to sFor r
eexample:
e s f
E - an
n FROMtrCustomer
SELECTro c JOIN c.orders o JOIN c.address a WHERE a.state =
rlo s
CA
no
ORDER nBY o.quantity DESC, o.totalcost ASC
C a

Note ORDER BY clauses are sorted in ascending order by default.

Expressions can be used with the ORDER BY clause. For example:

SELECT o.quantity, o.cost*1.08 AS taxedCost FROM Order o


ORDER BY taxedCost
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 the
Java Persistence API does not specify which.

9-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The UPDATE Statement

Declaring Query Strings: The UPDATE Statement


The Java Persistence API query language UPDATE statement updates one or more
rows of a specific table in the database. The UPDATE statement consists of an
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

UPDATE clause and an optional WHERE clause.


UPDATE_clause [WHERE_clause]

For example:
UPDATE customer c SET c.status = outstanding WHERE c.balance < 10000

s a
You can update multiple fields, for example,
) h a
UPDATE Product p SET p.discount = '10', p.shippingAmount = '0'
m x
t g ob
s
UPDATE statements apply only to entity instances of a single aentitydclass
e type. For
example, you cannot create a single UPDATE statement i
al@thatt applies
u to both the
Customer and Order entity class types. r n
e den G
o b
n e st need toSupdate
tu multiple entity instances.
this programatically using the UPDATE
r instance
An UPDATE statement is used when you
z
While you can update a single (eentitye
n
deis nottorecommended.
statement, this practice
a us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
s non
C arlo

Using the Java Persistence Query Language 9-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Declaring Query Strings: The DELETE Statement

Declaring Query Strings: The DELETE Statement


The Java Persistence API query language DELETE statement deletes one or more
rows from a specific table in the database. The DELETE statement consists of a
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

DELETE clause and an optional WHERE clause.


DELETE_clause [WHERE_clause]

For example:
DELETE FROM Customer c WHERE c.status = inactive

s a
DELETE statements apply only to entities of a single entity class type. For
) h a
m x example, you cannot create a single DELETE statement that deletes rows from

ob
both the Customer and Order tables.
t g
aentity dinstances.

A DELETE statement is used when you need to delete multiple s i e
n al@ t G
While you can delete a single entity instance programmatically
r
u a DELETE
using
statement, this practice is not recommended. be e n
st o tu d
n e S
Caution Caution should be used
z ( ewhen e t his bulk update or delete
r executing
operations because they may
n
d e result inusinconsistencies between the database and
r n a e to context. In general, bulk update and delete
the entities in the active persistence
operations should
H s
e only ebenperformed within a transaction in a new persistence
l c
li or accessing entities whose state might be affected by
contextnorabefore fetching
e r l e
t o B erab
such operations.

n e s nsf
s Er n-tra
arlo no
C

9-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 10
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Using the Criteria API

Objectives a
h a s
x )
Upon completion of this module, you should be able to: m
t
Contrast queries that use the Criteria API with queriesathat
obthe Java
guse

s d e
Persistence query language
al@ t Gu i
r n
Describe the metamodel object approacheto querying n
o b d e
Create Criteria API queries est S tu
n
z (er e this
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
s non
C arlo

10-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

10-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction to the Criteria API

Introduction to the Criteria API


Traditionally, Java Persistence API developers use string-based query languages
to retrieve entities from the database. While both the Java Persistence API query
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

language and SQL are mature and robust, they share a common problem: the Java
compiler cannot find syntax errors in string-based queries. For example, notice
the misspelled words in the following query:
1 String queryString = slect i from Itme i;
2 Query query = entityManager.createQuery(queryString);
3 List<Item> items = query.getResultList();

s a
The Criteria API was introduced in Java Persistence API version 2.0 to overcome
) h a
m x this problem. The Criteria API provides a strongly-typed way to create queries

t g ob using a CriteriaBuilder class. Since the queries are strongly typed, they can

s a de be validated by the Java compiler. For example, the following query uses the

n a l@ Gui Criteria API:


1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
b er dent
2 CriteriaQuery<Item> cq = cb.createQuery(Item.class);
e s to Stu
3 Root<Item> item = cq.from(Item.class);
( e rn this
4 z use
TypedQuery<Item> query = entityManager.createQuery(cq);
d e
5
an e to
List<Item> items = query.getResultList();
r n
H e ens
n l
a e list licdescribes each line of the Criteria API code example in greater
r
edetail: ab
The l
following
t o B er
e s s f
E rn -tran1. The entity manager creates an instance of a CriteriaBuilder. As the
arlos non name implies, the CriteriaBuilder class allows the developer to build
C the criteria for the query.
2. The CriteriaBuilder creates an instance of a CriteriaQuery. The
CriteriaQuery object uses generics in order to be strongly associated
with the Item entity class.
3. The CriteriaQuery creates a Root object that, again, uses generics to be
strongly associated with the Item entity class. This line is equivalent to the
from Item i clause in the Java Persistence API query language.
4. Once the CriteriaQuery object is populated, it is passed as a parameter
to the createQuery method of the entity manager.
5. Finally, the results of the query are returned as a list of entities.

Using the Criteria API 10-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Criteria Query API Usage

Criteria Query API Usage


The javax.persistence.criteria package contains interfaces that
correspond to the clauses of a Java Persistence API query language SELECT
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

statement.

Note The Criteria API does not support UPDATE or DELETE statements.

Table 10-1 Relating Java Persistence API Query Language Clauses to Criteria s a
) h a
m x API Interfaces

Java
t g ob
Persistence s a de
API Query Criteria API Interface
n a l@ Gui
Language
b er dent
Clause
e s to Stu
select ( e rn this
CriteriaQuery<T>,
d e z use
Selection<T>
r n an e to
from
H e ens
Root<T>
n l ic
a e lPredicate
r
where
e ab l
t o B r
eby
e s group
n s f Expression<T>
E rn -trahaving Predicate
r l o s n o n
Ca order by Order

The Criteria API interfaces will be explored in greater detail throughout this
module.

10-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Constructing Criteria Queries

Constructing Criteria Queries


A criteria query is constructed through the creation and modification of a
javax.persistence.criteria.CriteriaQuery object.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The CriteriaBuilder interface is the factory for CriteriaQuery objects.


The CriteriaBuilder implementation is accessed through the
getCriteriaBuilder() method of the EntityManager or
EntityManagerFactory interface.

For example:
s a
EntityManagerFactory emf = Persistence.getEntityManagerFactory();
) h a
m x CriteriaBuilder cb = emf.getCriteriaBuilder();

t g ob
a dtypically
The Java Persistence API query language conditional expressions
s e used
in a WHERE clause are provided by the Criteria API as l@ Gu
methods
aexpression i
of the
r n
e object.
CriteriaBuilder class. Calling the conditional
n t methods on the
b
to Stud
CriteriaBuilder class returns a Predicate e
e s
( e rn this
d e z use
anWHEREe Clause
Table 10-2 Relating Java Persistence
r n to Conditional Expressions to Methods of the
CriteriaBuilder
H e ens
Class

n l
a e lJava ic Persistence API Query
r
e aType l
b Language Conditional
t B
ConditionaloExpression
e r CriteriaBuilder Methods
s s f
E rne -tran Expression Operators

arlos Comparison
non expression =, >, >=, <, <=, <> equal, greaterThan,
C greaterThanOrEqualTo,
lessThan,
lessThanOrEqualTo,
notEqual, gt, ge, lt,
le
Between expression [NOT] BETWEEN between, notbetween
Like expression [NOT] LIKE like, notlike
In expression [NOT] IN in, not(in)
Null comparison expression IS [NOT] NULL isNull, isNotNull
Empty collection comparison IS [NOT] EMPTY isEmpty, isNotEmpty
expression
Collection member expression [NOT] MEMBER OF isMember, isNotMember

Using the Criteria API 10-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Constructing Criteria Queries

Table 10-2 Relating Java Persistence WHERE Clause Conditional Expressions to Methods of the
CriteriaBuilder Class

Java Persistence API Query


Conditional Expression Type Language Conditional CriteriaBuilder Methods
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Expression Operators

Exist expression [NOT] EXISTS exists


Binary relational operator AND, OR and, or

s a
The following example returns all Bid entities that have an amount greater than
) h a
m x 100.0:
b
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder(); tgo
s a de
2
3
CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
Root<Bid> bid = cq.from(Bid.class); n a l@ Gui
4 Predicate condition = cb.gt(bid.get(Bid_.amount), b er 100.0);
e n t
5 cq.where(condition);
e s to Stud
6 e rn this
TypedQuery<Bid> query = entityManager.createQuery(cq);
(
7 e
List<Bid> bids = query.getResultList();
d z use
r n an e to
CriteriaBuilder
complex a l e ns theexpression
HeForicconditional methods can be combined to form

r n queries.
l e l example, following example returns all Bid entities that
haveean amountb greater than 100.0 and an approval value of pending:
o B r a
1 e st nsfecb = entityManager.getCriteriaBuilder();
CriteriaBuilder
n
2
s Er n-tra
CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
r l
3 o n o
Root<Bid> bid = cq.from(Bid.class);
Ca 4 Predicate condition = cb.and(
5 cb.greaterThan(bid.get(Bid_.amount), 100.0),
6 cb.equal(bid.get(Bid_.approval), pending)
7 );
8 cq.where(condition);
9 TypedQuery<Bid> query = entityManager.createQuery(cq);
10 List<Bid> bids = query.getResultList();

Notice that the Predicate relies on calls like Bid_.amount and


Bid_.approval to build up the criteria for the query. This is called a path
expression. These examples use the Metamodel API introduced in Java
Persistence API version 2.0 to support strongly typed queries.

10-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding the Metamodel API

Understanding the Metamodel API


Each Java Persistence API entity class has a corresponding metamodel class. The
metamodel class enables the developer to create type-safe queries for the entity
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

class.

The metamodel class name is the same as the entity class name plus a trailing
underscore character. For example, the Bid entity has a metamodel class named
Bid_.

The software developer creates the metamodel using the tools provided by the
persistence provider. The resulting metamodel is the canonical metamodel class s a
for the entity class. The metamodel class is canonical if it provides public static ) h a
m x
fields for each persistent field in the entity. The persistence provider is
g ob
responsible for initializing the metamodel class when the persistence unit is
t
deployed. s a de
n a l@ Gui
For example, the following is the Bid entity
b er dethat
definition nt the developer creates:
e s to Stu
1
2
@Entity
public class Bid{ ( e rn this
3 @Id d e z use
4 private long bidId;
r n an e to
5 e ens
private doubleHamount;
n l
a approval;lic
6
r
private String
e ab l e
7 B
t ... sfer
o
8
e s
//
n tran
9 Er}
r l o s non-
C a The following is the corresponding metamodel class:
1 @StaticMetamodel(Bid.class)
2 public class Bid_{
3 public static volatile SingularAttribute<Bid, Long> bidId;
4 public static volatile SingularAttribute<Bid, Double> amount;
5 public static volatile SingularAttribute<Bid, String> approval;
6
7 // ...
8 }

Since the metamodel class provides an easy way to supply both the field name
and the datatype for the criteria, the Java compiler can guard against misspelled
field names and mismatched datatypes. In the following example, both the invalid
field name amt and the incorrect boolean value supplied for a string field will be
caught by the compiler or the IDE as you write the code:

Using the Criteria API 10-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding the Metamodel API

1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
3 Root<Bid> bid = cq.from(Bid.class);
4 Predicate condition = cb.and(
5 cb.gt(bid.get(Bid_.amt), 100.0),
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

6 cb.equal(bid.get(Bid_.approval), true)
7 );
8 cq.where(condition);
9 TypedQuery<Bid> query = entityManager.createQuery(cq);
10 List<Bid> bids = query.getResultList();

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

10-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding the Metamodel API

Using String-Based Methods


If there isnt a canonical metamodel class, you can use the alternate string-based
methods.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note If you use the string-based methods, misspelled class names and fields
names can appear once again in the queries.

The following example uses string-based methods to return all Bid entities with
an amount greater than 100.0:
s a
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
) h a
2 CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
m x
3 Root<Bid> bid = cq.from(Bid.class);
t g ob
4
s a de
Path<Double> amount = bid.<Double>get(amount);
5 l@ Gui
Predicate condition = cb.gt(amount, 100.0);
n a
6 cq.where(condition);
b er dent
7 to Stu
TypedQuery<Bid> query = entityManager.createQuery(cq);
e s
8
rn this
List<Bid> bids = query.getResultList();
( e
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Using the Criteria API 10-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Parameter Expressions

Parameter Expressions
A ParameterExpression instance is an expression that corresponds to a
parameter whose value will be supplied before the query is executed. Parameter
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

expressions can be used only in the construction of conditional predicates.

If a name is supplied when the ParameterExpression instance is created, the


parameter may also be treated as a named parameter when the query is executed:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
3 Root<Bid> bid = cq.from(Bid.class);
s a
4 ParameterExpression<Double> param =
) h a
5 cb.parameter(Double.class, amt);
m x
6
t g ob
Predicate condition = cb.gt(bid.get(Bid_.amount), param);
7 cq.where(condition);
s a de
8
l@ Gui
TypedQuery<Bid> query = entityManager.createQuery(cq);
n a
9
b er dent
List<Bid> bids = query.setParameter(amt, 250.0).getResultList();

e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

10-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Joins

Joins
The join methods of the From interface extend the query domain by creating a
join with a related class that can be navigated to or that is an element of the given
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

class of the query domain. The join methods may be applied to instances of the
Root and Join types.

For example, given the Order entity and corresponding Order_ metamodel
class, a join to the line items of the order would be expressed as follows:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<Order> cq = cb.createQuery(Order.class);
s a
3 Root<Order> order = cq.from(Order.class);
) h a
4 Join<Order, Item> item = order.join(Order_.lineitems);
m x
5 cq.select(order);
t g ob
6
a de
TypedQuery<Order> query = entityManager.createQuery(cq);
s
7 List<Order> orders = query.getResultList();
n a l@ Gui
b er dent
e s to Stu
e
The join methods have the (samernsemantics
thisas the corresponding Java
z
de operations.
Persistence query language us e
a n
t o
e rn nse
n a l H lice
For example:
1
B er acbble= entityManager.getCriteriaBuilder();
CriteriaBuilder
2 s to sfer
CriteriaQuery<String>
e
cq = qb.createQuery(String.class);
n tran customer = cq.from(Customer.class);
3 rRoot<Customer>
E
r l o s non-
4 Join<Customer, Order> order = customer.join(Customer_.orders);
C a 5 Join<Order, Item> item = order.join(Order_.lineitems);
6 cq.select(customer.get(Customer_.name))
7 .where(qb.equal(item.get(Item_.product).get(Product_.productType),
8 "printer"));
9 TypedQuery<String> query = entityManager.createQuery(cq);
10 List<String> names = query.getResultList();
11

This query is equivalent to the following Java Persistence query language query:
SELECT c.name
FROM Customer c JOIN c.orders o JOIN o.lineitems i
WHERE i.product.productType = 'printer'

Using the Criteria API 10-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Joins

Chaining Joins
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Joins can be chained, which enables you to write queries more concisely:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<String> cq = qb.createQuery(String.class);
3 Root<Customer> customer = cq.from(Customer.class);
4 Join<Order, Item> item =
5 customer.join(Customer_.orders).join(Order_.lineitems);
6 cq.select(customer.get(Customer_.name)) s a
7 .where(qb.equal(item.get(Item_.product).get(Product_.productType), ) h a
8 "printer")); m x
9 TypedQuery<String> query = entityManager.createQuery(cq);
t g ob
10 List<String> names = query.getResultList(); s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
Outer Joins e z use
d
an e to
r n
l H e method
By default, the join
c e ns defines an inner join. Outer joins are defined by
e rna ble li
specifying a JoinType argument.

t o B era
n e s NotensfOnly left outer joins are required to be supported in Java Persistence API
Er n-tr2.0.a
r l o s n o Applications that use right outer joins or right outer fetch joins are not
C a portable.

The following query uses a left outer join:


1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<Customer> cq = qb.createQuery(Customer.class);
3 Root<Customer> customer = cq.from(Customer.class);
4 Join<Customer,Order> order =
5 customer.join(Customer_.orders, JoinType.LEFT);
6 cq.where(qb.equal(customer.get(Customer_.status), 1))
7 .select(customer);
8 TypedQuery<Customer> query = entityManager.createQuery(cq);
9 List<Customer> customers = query.getResultList();

This query is equivalent to the following Java Persistence query language query:

10-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Joins

SELECT c FROM Customer c LEFT JOIN c.orders o WHERE c.status = 1


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Using the Criteria API 10-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Query Modification

Query Modification
A CriteriaQuery object may be modified either before or after TypedQuery
objects have been created and executed from it. For example, such modification
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

might entail replacement of the where predicate or the select list. Query
modifications could thus result in the same CriteriaQuery base being reused
for several query instances.

For example, the user might create and execute a query from the following
CriteriaQuery object:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
s a
2 CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
) h a
3 Root<Customer> c = cq.from(Customer.class);
m x
4 Predicate pred =
t g ob
5
a de
cb.equal(c.get(Customer_.address).get(Address_.city),"Chicago");
s
6 cq.select(c);
n a l@ Gui
7
8
cq.where(pred);
b er dent
TypedQuery<Customer> chicagoQuery = entityManager.createQuery(cq);
9 e s to Stu
List<Customer> chicagoCustomers = chicagoQuery.getResultList();
( e rn this
The CriteriaQuery object d e zmight uthen
s ebe modified to reflect a different
anexample:
predicate condition,nfor
r e to
10 Predicate pred2 = l H
e ens
r n a e lic
11 e abl
cb.gt(c.get(Customer_.balancedOwed),
B
1000);

e s to sfer chicagoPastDueQuery =
12 cq.where(pred2);
n tran
13 TypedQuery<Customer>
14 Er entityManager.createQuery(cq);
r l o n o n-
s List<Customer> chicagoPastDueCustomers =
C a 15
16 chicagoPastDueQuery.getResultList();

Note that query elements are dependent on the CriteriaQuery instance, and
are thus not portably reusable with different CriteriaQuery instances.

10-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Ordering the Query Results

Ordering the Query Results


The ordering of the results of a query is defined by use of the orderBy method
of the CriteriaQuery instance. The arguments to the orderBy method are
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Order instances.

An Order instance is created by means of the asc and desc methods of the
QueryBuilder interface. If more than one Order instance is specified, the order
in which they appear in the argument list of the orderBy method determines the
precedence, whereby the first item has highest precedence.

For example: s a
) h a
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
m x
2 CriteriaQuery<Order> cq = cb.createQuery(Order.class);
t g ob
3 Root<Customer> c = cq.from(Customer.class);
s a de
4 l@ Gui
Join<Customer,Order> o = c.join(Customer_.orders);
n a
5
er dent
Join<Customer,Address> a = c.join(Customer_.address);
b
6
7 cq.select(o); e s to Stu
cq.where(cb.equal(a.get(Address_.state), "CA"));

8 ( e rn this
cq.orderBy(cb.desc(o.get(Order_.quantity)),
9 d e z use
cb.asc(o.get(Order_.totalCost)));
10 n an e to
TypedQuery<Order> query = entityManager.createQuery(cq);
r
11 H e ens
List<Order> orders = query.getResultList();
12 n l
a e lic
r
e abl
B
to This r corresponds to the following Java Persistence query language query:
equery
e s s f
E rn o -tran
sSELECT
on
C arlo FROM nCustomer c JOIN c.orders o JOIN c.address a
WHERE a.state = 'CA
ORDER BY o.quantity DESC, o.totalcost

Using the Criteria API 10-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Constructing Tuple Queries

Constructing Tuple Queries


A tuple is a list of name and value pairs similar to a java.util.Map. The Criteria
API enables you to perform queries that return results stored in a
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

javax.persistence.Tuple object. Tuple queries are typically used to return


multiple entity or attribute types, and use aliases to form the name/value pair.

For example:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<Customer> c = cq.from(Customer.class);
s a
Join<Customer, Order> o = cq.join(Customer_.orders);
) h a
Join<Customer, Address> a = cq.join(Customer_.address);
m x
cq.where(cb.equal(cq.get(Customer_.id), 97510));
t g ob
cq.multiselect(o.get(Order_.quantity).alias("quantity"),
s a de
n a l@ Gui
cb.prod(o.get(Order_.totalCost), 1.08).alias("taxedCost"),
a.get(Address_.zipcode).alias("zipcode"));
b er dent
TypedQuery<Tuple> typedQuery = em.createQuery(cq);
e s to Stu
Tuple result = typedQuery.getSingleResult();
( e rn this
Double cost = result.get("taxedCost", Double.class);
e z use
Integer quantity = result.get("quantity", Integer.class);
d
r n an e to
String zip = result.get("zipcode", String.class);
H e ens
n l licbe retrieved by position. For example:
a canealso
Tuple values
r
e ab l
Tuple resultto= B er
typedQuery.getSingleResult();
e s n=sfresult.get(0,
Integernquantity Integer.class);
E a
rcost -=trresult.get(1,
os zipnon= result.get(2, String.class);
Double Double.class);

C arlString

10-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 11
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Using the Java Persistence API in a


Container

s a
Objectives ) h a
m x
Upon completion of this module, you should be able to: atg
ob
s d e
Use the Java Persistence API from a servlet al@ Gu
i
b e rn ent
Use the Java Persistence API fromoastateless session
d bean
s t t u
e r ne his S
z ( e t
e
nd to u s
n a
H er ense
r n al e lic
B e abl
e s to sfer
E rn -tran
s non
C arlo

11-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.
Sun Microsystems, The Java EE 6 Tutorial,
[http://java.sun.com/javaee/6/docs/tutorial/doc/], accessed
September 15, 2009.
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

11-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introduction to Using the Java Persistence API in a Container

Introduction to Using the Java Persistence API in a


Container
The Java Persistence API is an integral part of the Java Enterprise Edition,
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

version 6.0. In this module, you will learn how to use the Java Persistence API
from various components, including:
Servlets
Stateless session beans

Each area will be explored in greater detail in this module.


s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Using the Java Persistence API in a Container 11-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Java Servlets

Java Servlets
A Java Servlet responds to HTTP requests. Servlets run within the Java EE
component container architecture. This container is called the web container, also
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

known as the servlet engine.

The web container performs initial processing and selects the intended servlet to
handle the request. The container also controls the life cycle of the servlet.
HTTP request
User Workstation Web Server

s a
Web Container
) h a
Browser HTTP
m x
Servlet
t g ob
s a dDatabase
e
al@ t Gu i
HTTP response
r n
e den
o b <HTML>

n e st S tu
z (er e this </HTML>

a n
de to us
Figure 11-1 Sample
e rn nsServer
Web
e Architecture With Java Servlets
n a l H lice
B
Noteer In some
a b learchitectures, the web container acts as a stand-alone HTTP
e s toservice.
s f eInrother architectures, the HTTP service forwards requests to be
E an by the web container.
rn -trprocessed
s non
C arlo

11-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Simple Java Servlet

Simple Java Servlet


A servlet is invoked by the web container when an appropriate request is received
by that container. In Java EE 6, an annotation specifies the URL or URL pattern
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

to which the servlet should respond.

The method in the servlet that is invoked depends on the type of HTTP request.
For example, an HTTP GET request will invoke the doGet method in the servlet.

The doGet method takes two parameters, one that carries information related to
the original request and another that controls the response.
s a
h a
x)
The servlets job is two-fold. First, it must perform the required computation.
Second, it must present the results in a well-formed HTML page. bm

a t go
Code 11-1 Simple Servlet
@ s ide
n a l G u
1 package sl351.m1;
b r
e den t
o
2
n e st S tu
r this
3 import java.io.IOException;
4 import java.io.PrintWriter; z (e e
5 n
de to us
import javax.servlet.ServletException;
a
6 rn nse
import javax.servlet.annotation.WebServlet;
e
7 l H lice
import javax.servlet.http.HttpServlet;
n a
8
er able
import javax.servlet.http.HttpServletRequest;
B
9
to sfer
import javax.servlet.http.HttpServletResponse;
e s
an
10
11Ern - t r
arlos12 n on
@WebServlet(name="ListServlet", urlPatterns={"/ListServlet"})
C 13 public class ListServlet extends HttpServlet {
14
15 @Override
16 protected void doGet(HttpServletRequest request,
17 HttpServletResponse response)
18 throws ServletException, IOException {
19 response.setContentType("text/html;charset=UTF-8");
20 PrintWriter out = response.getWriter();
21 try {
22 out.println("<html>");
23 out.println("<head>");
24 out.println("<title>HelloServlet</title>");
25 out.println("</head>");
26 out.println("<body>");
27 out.println("<h1>HelloServlet says \"Hello,
World!\"</h1>");

Using the Java Persistence API in a Container 11-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Simple Java Servlet

28 out.println("</body>");
29 out.println("</html>");
30 } finally {
31 out.close();
32 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

33 }
34 }

Notice the following features of the code:


The class extends javax.servlet.http.HttpServlet s a
The class overrides the method doGet, which provides the home for thex) h a
code that will service the HTTP request
o b m
The doGet method creates an entire HTML page and sends
s atitgtodthe
e
browser
al@ t Gu i
r n
ethe webdeserver
n by means of the

The servlet is associated with a URL within
o b
@WebServer annotation
n e st S tu
z (er e this
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
s non
C arlo

11-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Adding an Entity Manager to a Servlet

Adding an Entity Manager to a Servlet


Adding an entity manager to a servlet typically is accomplished by dependency
injection using the @PersistenceUnit annotation on the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

EntityManagerFactory field. The name of the persistence unit is passed into


the @PersistenceUnit annotation using the unitName element.

Once the entity manager factory is injected into the servlet, method calls like
getEntityManager and createQuery return the results to the servlet. The
results are then rendered as HTML.

Code 11-2 Servlet Using an Injected Entity Manager Factory s a


) h a
m x 1 @WebServlet(name="ListServlet", urlPatterns={"/ListServlet"})

t g ob 2 public class ListServlet extends HttpServlet {


s a de 3
@PersistenceUnit(unitName = "JPA1-warPU")
n a l@ Gui 4
private EntityManagerFactory emf;
b er dent 5

e s to Stu 6
@Override
( e rn this request,
protected void doGet(HttpServletRequest
7
8
HttpServletResponse response)d e z use 9
n an eIOException
throws ServletException,
r to { 10
e
H iem s
en= emf.getEntityManager(); 11
a l l c
ern ablelist = em.createQuery("select i from Item i")
EntityManager 12
B
List<Item>
to sfer
13

n e s n
.getResultList(); 14

s Er n-traresponse.setContentType("text/html;charset=UTF-8"); 15

arlo no 16
C PrintWriter out = response.getWriter(); 17
18 try {
19 out.println("<html>");
20 out.println("<head>");
21 out.println("<title>HelloServlet</title>");
22 out.println("</head>");
23 out.println("<body>");
24
25 out.println("<table border='1'>");
26 out.println("<tr><th>Name</th> +
27 <th>Description</th></tr>");
28 for(Item item: list){
29 out.println("<tr>");
30 out.println("<td>" + item.getName() + "</td>");
31 out.println("<td>" + item.getDescription() +
32 "</td>");

Using the Java Persistence API in a Container 11-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Adding an Entity Manager to a Servlet

33 out.println("</tr>");
34 }
35 out.println("</table>");
36
37 out.println("</body>");
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

38 out.println("</html>");
39 } finally {
40 out.close();
41 }
42 }
43 }

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non Figure 11-2 Output of the ListServlet Servlet Response
C arlo
Note the following additional information regarding persistence contexts and
entity managers:
A persistence context is a set of managed entity instances in which for any
persistent entity identity (primary key) there is a unique entity instance.
Within the persistence context, the entity instances and their lifecycle are
managed by the entity manager.
You do not create a persistence context directly. Instead, you use the
persistence context that is created when the entity manager is created.
An entity manager must not be shared among multiple concurrently
executing threads, as the entity manager and persistence context are not
required to be threadsafe. Entity managers must only be accessed in a
single-threaded manner.

11-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Using Transactions in a Servlet

Using Transactions in a Servlet


In the previous section, you created a query that did not require a transaction.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

For queries that require a transaction (typically statements that involve a SQL
INSERT, UPDATE, or DELETE), you have two transaction management options:
user-managed or container-managed.

If you choose to perform queries that require transactions in a servlet, you must
manage the all of the transaction handling yourself. These user-managed
transactions are controlled by obtaining a
javax.transaction.UserTransaction object from the entity manager. s a
) h a
m x
ob
To take advantage of container-managed transactions, you should move the Java
t g
Persistence API queries into an enterprise bean.
a de
s
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Using the Java Persistence API in a Container 11-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding EJB Components

Understanding EJB Components


The Java EE Platform describes two types of EJB components: session beans and
message-driven beans. This module introduces the characteristics, concepts, and
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

tasks required to build session beans.

What Is a Session Bean?


Simplistically, a session bean is a service object.

s a
From an architectural perspective, session beans encapsulate business logic in a
) h a
m x
centralized, reusable fashion, accessible by any number and styles of clients.

t g ob
s a de
From a developers perspective, a session bean is a Java object that adheres to a
small set of coding conventions and executes in a managed
n a l@ Gui
environment.

b er asda eserver-side
nt
s o oftua server.
From a clients perspective, a session bean functions
tcontext extension

e r n his S
that performs the business logic withinethe

z ( e t
e
nd to u s
Types of Session n a
Beans
H er ense
n l licdescribes three different types of session beans:
aspecification
r
The EJB
e ab l e
t o B ferStateless session beans (SLSB) - Generic business processing
e s s
E rn -tran Stateful session beans (SFSB) - User-specific business processing
s non
C arlo Singleton session beans (SSB) - Shared data access

Note This section focuses on Stateless session beans.

11-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding EJB Components

Session Bean Annotation Types


Within Java EE, annotations can be used to describe the characteristics of EJB
component client access, describe the type of EJB component to a container, and
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

gain access to other resources.


Table 11-1 Common Annotations Applicable to Session Beans

Annotation Applies To Description

@Stateful Session bean class Denotes the type of session bean.


@Stateless s a
@Singleton
) h a
m x
@Local
@Remote
Session bean class or
its business interface t ob
Denotes the client access model for the
g
session bean
s a de
n a l@ Gui
b er dent
e s to Stu
Characteristics of a Session ( e rn Beanthis
z
de to us e
a n

e rn ndescribes
The EJB specification se three different types of session beans, but all
H
albeansesharee
session
r n l lic the following characteristics:
B e abHave a managed life cycle
e s t o s f er
E rn -tran Execute on behalf of a client, without bean instances being directly

r l o s non accessed by the client


C a Can be transaction-aware and support security constraints
Can be invoked synchronously or asynchronously

Session Bean Clients


Session beans can be accessed by many different types of components and
objects. Typical session bean clients are:
Another enterprise bean, such as another session
A web component, such as a servlet
A plain Java class, such as an application client
A web service

Using the Java Persistence API in a Container 11-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Understanding EJB Components

Session beans support two types of client access models:


Local client access
Local clients are typically other EJB components or web-tier components
co-resident within the same enterprise application
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Remote client access


Remote clients could be stand-alone Java applications, web services, or
other enterprise beans executing in a remote JVM.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

11-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Creating Session Beans: Essential Tasks

Creating Session Beans: Essential Tasks


This section provides an overview of the essential tasks you need to perform to
create an EJB 3 session bean.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

No-Interface Implementation
Starting with EJB 3.1, Enterprise JavaBeans components can be developed
without the creation of a separate business interface. This implementation
strategy, known as a no-interface implementation, delivers a less cumbersome
s a
development process.
) h a
m x
t ob
To create a no-interface implementation of a session bean, apply the
g
@LocalBean annotation directly to the bean class.
s a de
n
Code 11-3 A No-Interface Stateless Session Beana l@ Gui
b er dent
1 @Stateless
e s to Stu
2 @LocalBean rn this
3 public class CalculatorBean {z (e e
d e u s
4 public CalculatorBean()
r n aton illustrate
{
e to requirements
5
e ens
//added explicitly
H
6 }
n l
a e lic
7 r
e add(int
b l
8 public
t Bint a
o safe+rb; a, int b) {
9
ne s n
return
10Er } -tra
s n
C arlo 11 no 12 public int subtract(int a, int b) {
13 return a - b;
14 }
15 }

Note When using the no-interface representation of a session bean, all of the
public methods defined within the bean are considered part of the local interface.
While no-interface implementation strategy requires less development overhead,
fine-grained control over the mode of method access is lost.

Using the Java Persistence API in a Container 11-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Adding a Container-Managed Entity Manager to a Stateless Session Bean

Adding a Container-Managed Entity Manager to a


Stateless Session Bean
Adding an container-managed entity manager to a stateless session bean typically
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

is accomplished through dependency injection using the


@PersistenceContext annotation on the EntityManager field. The name of
the persistence unit is passed into the @PersistenceContext annotation using
the unitName element.

Once the entity manager is injected into the stateless session bean, method calls
like createQuery return the results to the stateless session bean. The results are
s a
then returned to the client that created the method class.
) h a
m x
t g ob
Code 11-4 Stateless Session Bean Using an Injected Entity Manager
1 package com.acme.ejb; s a de
2
n a l@ Gui
3 import com.acme.entities.Item;
b er dent
4 import javax.ejb.LocalBean;
e s to Stu
5 import javax.ejb.Stateless;
( e rn this
6 z use
import javax.persistence.EntityManager;
d e
7
an e to
import javax.persistence.PersistenceContext;
r n
8
H e ens
9 @Stateless l
a e lic
10 @LocalBean ern l
11 public class B
o sfer a b
ItemDaoBean {
s t
e ran
12
r n@PersistenceContext(unitName = "JPA1-warPU")
13 E private
o s o n -t EntityManager em;
l
ar14 n
C 15 public void save(Item item) {
16 em.persist(item);
17 }
18 }
19

Because stateless session beans are single threaded, it is perfectly safe to use an
entity manager from a stateless session bean.

Additionally, stateless session beans automatically participate in container-


managed transactions, so Java Persistence API method calls like persist and
merge are safe to use.

11-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Adding a Container-Managed Entity Manager to a Stateless Session Bean

Injecting a Stateless Session Bean into a Servlet


Once the stateless session bean is in place, you can then inject it into a servlet
using the @EJB annotation.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Code 11-5 Injecting a Stateless Session Bean Into a Servlet


1 package com.acme.web;
2
3 @WebServlet(name="AddServlet", urlPatterns={"/AddServlet"})
4 public class AddServlet extends HttpServlet {
5
s a
6 @EJB
) h a
7 ItemDaoBean itemDaoBean;
m x
8
9 t g ob
protected void processRequest(HttpServletRequest request,
s a de
HttpServletResponse response)
n a l@ Gui
er dent
10 throws ServletException, IOException {
11 b
response.setContentType("text/html;charset=UTF-8");
to Stu
12 e s
PrintWriter out = response.getWriter();
13
( e rn this
14 e z use
Item item = new Item();
d
15
r n an e to
item.setId(Long.parseLong(request.getParameter("id")));
16
H e ens
item.setName(request.getParameter("name"));
17
n l
a e lic item.setDescription(request.getParameter("description"));
r
e abl
18 item.setPhoto(request.getParameter("photo"));
B
to sfer
19 itemDaoBean.save(item);
e s
E rn -tran 20
s non 21 try {
C arlo 22 out.println("<html>");
23 out.println("<head>");
24 out.println("<title>Servlet AddServlet</title>");
25 out.println("</head>");
26 out.println("<body>");
27
28 out.println("<a href='ListServlet'>Back to List</a>");
29 out.println("<h1>New Item:</h1>");
30
31 out.println("<table border='1'>");
32 out.println("<tr><th>Name</th><th>Value</th></tr>");
33 out.println("<tr><td>Id</td>");
34 out.println("<td>" + item.getId() + "</td></tr>");
35 out.println("<tr><td>Name</td>");
36 out.println("<td>" + item.getName() + "</td></tr>");
37 out.println("<tr><td>Description</td>");

Using the Java Persistence API in a Container 11-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Adding a Container-Managed Entity Manager to a Stateless Session Bean

38 out.println("<td>" + item.getDescription() +
"</td></tr>");
39 out.println("<tr><td>Photo</td>");
40 out.println("<td>" + item.getPhoto() + "</td></tr>");
41 out.println("</table>");
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

42
43 out.println("</body>");
44 out.println("</html>");
45 } finally {
46 out.close();
47 }
48 }
49 } s a
) h a
m x
t g ob
To test AddServlet, pass in the id, name, description, s aand photo
d e
al@intot the i
ubrowser:
attributes in the query string by typing the followingnURL
r
e den G
o b
http://localhost:8080/JPA1-war/AddServlet?
n e st S tu
(er e this
id=99&
name=New+Book&
description=New+Description&
z
de to us
a n

photo=New+Photo
e rn nse
n a l H lice
B
Noteer TheaURLb leshould be typed as a single line.
e s to sfer
E an
rn -trAddServlet
r l o s non does the following:
Ca Parses the query string using request.getParameter()
Builds a well-formed Item object
Passes the Item to the ItemDaoBean for persistence
Displays the results as HTML

11-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Adding a Container-Managed Entity Manager to a Stateless Session Bean
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
Figure 11-3 Output of the AddServlet Servlet Response gob
s at de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Using the Java Persistence API in a Container 11-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Adding a Container-Managed Entity Manager to a Stateless Session Bean
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

11-18 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 12
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Implementing Transactions and Locking

Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
Describe the transaction demarcation management atg
ob

s d e
al@ t Gu
Implement container-managed transactions (CMT) i
r n
e CMT n
b
Interact programmatically with an ongoing
o d etransaction
n e st (BMT) S tu
this API
(er Persistence
Implement bean-managed transactions
z
Apply transactionseto the Javase
n a nd to u
H er ense
r n al e lic
B e abl
e s to sfer
E rn -tran
arlos non
C

12-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JSR 317: Java Persistence, Version 2.0, Java Persistence API,


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.
JSR 907: Java Transaction API, Version 1.1,
[http://jcp.org/en/jsr/detail?id=907], accessed September 15,
2009.
s a
Sun Microsystems, The Java EE 6 Tutorial, Volume 1,
) h a
m x
[http://java.sun.com/javaee/6/docs/tutorial/doc/

t g ob
index.html], accessed September 15, 2009.

s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

12-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is a Transaction?

What Is a Transaction?
A typical enterprise application accesses and stores information in one or more
databases. Because this information is critical for business operations, it must be
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

accurate, current, and reliable. Data integrity would be lost if multiple programs
were allowed to update the same information simultaneously. Data integrity
would also be lost if a system that failed while processing a business transaction
were to leave the affected data only partially updated.

By preventing both of these scenarios, software transactions ensure data integrity.


Transactions control the concurrent access of data by multiple programs. In the
event of a system failure, they make sure that the data will be in a consistent state s a
after recovery. ) h a
m x
To emulate a business transaction, a program might need to perform
t g obseveral steps.
A financial program, for example, might transfer funds from s a a checking
d e account
to a savings account using the steps listed in the following u i
al@ t pseudocode:
r n
e den G
begin transaction
t o b
debit checking accountes S tu
n
credit savings account
z (er e this
update history
n
d e log us
n a e to
commit transaction
r
H e ens
n l
aall three loficthese steps must complete, or none of them at all. Otherwise,
r
Either
l
edata integrity e
t o B
f e r abis isoften
lost. Because the steps within a transaction are a unified whole, a

n e s ns transaction defined as an indivisible unit of work.

s Er n-tra
arlo no A transaction can end in two ways: with a commit or with a rollback. When a
C transaction commits, the data modifications made by its statements are saved. If a
statement within a transaction fails, the transaction rolls back, undoing the effects
of all statements in the transaction.

In the pseudocode, for example, if a disk drive were to crash during the credit
step, the transaction would roll back and undo the data modifications made by the
debit statement. Although the transaction fails, data integrity would be intact
because the accounts still balance.

In the preceding pseudocode, the begin and commit statements mark the
boundaries of the transaction. When designing an enterprise bean, you determine
how the boundaries are set by specifying either container-managed or bean-
managed transactions.

Implementing Transactions and Locking 12-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Container-Managed Transactions

Container-Managed Transactions
In an enterprise bean with container-managed transaction (CMT) demarcation,
the EJB container sets the boundaries of the transactions. You can use container-
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

managed transactions with any type of enterprise bean: session or message-


driven. Container-managed transactions simplify development because the
enterprise bean code does not explicitly mark the transactions boundaries. The
code does not include statements that begin and end the transaction.

Note If no transaction demarcation is specified, enterprise beans use container-


managed transaction demarcation by default.
s a
) h a
m x
t ob
Typically, the container begins a transaction immediately before an enterprise
g
bean method starts. It commits the transaction just before the method exits. Each
s a de
n a
transactions are not allowed within a method.l@ Gui
method can be associated with a single transaction. Nested or multiple

b er dent
s
Container-managed transactions do noterequire to allSmethods
tu to be associated with
n
er you
transactions. When developing a(bean, hisspecify which of the beans
z
methods are associated withetransactions e tcan

n
d u s by setting the transaction attributes.
o
rnausencontainer-managed
et
H
Enterprise beans e that
e s transaction demarcation must not
l i c
e r a demarcation
use anyntransaction
b l e lmanagement methods that interfere with the containers

o B
transaction
r a boundaries. Examples of such methods are the commit,

n e st setAutoCommit,
n s fe and rollback methods of java.sql.Connection or the
E r - t r a
commit and rollback methods of javax.jms.Session. If you require
s non control over the transaction demarcation, you must use application-managed
C arlo transaction demarcation.

Note Enterprise beans that use container-managed transaction demarcation also


must not use the javax.transaction.UserTransaction interface.

12-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Bean-Managed Transactions (BMT)

Bean-Managed Transactions (BMT)


In bean-managed transaction (BMT) demarcation, the code in the session or
message-driven bean explicitly marks the boundaries of the transaction. Although
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

beans with container-managed transactions require less coding, they have one
limitation: When a method is executing, it can be associated with either a single
transaction or no transaction at all. If this limitation will make coding your bean
difficult, you should consider using bean-managed transactions.

The following pseudocode illustrates the kind of fine-grained control you can
obtain with application-managed transactions. By checking various conditions,
the pseudocode decides whether to start or stop different transactions within the s a
business method. ) h a
m x
begin transaction
t g ob
...
s a de
update table-a
n a l@ Gui
...
if (condition-x) b er dent
e s
commit transactionto Stu
( e rn this
else if (condition-y)
e z use
update table-b
d
r n an e to
commit transaction
H e ens else
n l
a e lic rollback transaction
r
e abl
B
to sfer
begin transaction

e s update table-c
E rn -tran commit transaction
s non
C arlo When coding a application-managed transaction for session beans that use the
Java Persistence API, you must use either Java Transaction API transactions or
Java Persistence API EntityTransaction API transactions.

Implementing Transactions and Locking 12-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the Java Transaction API

Introducing the Java Transaction API


The Java Transaction API specifies standard Java interfaces between a transaction
manager and the parties involved in a distributed transaction system: the resource
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

manager, the application server, and the transactional applications.

This API enables you to demarcate transactions in a manner that is independent


of the transaction manager implementation. The Enterprise Server implements the
transaction manager with the Java Transaction Service. But your code doesnt call
the Java Transaction Service methods directly. Instead, it invokes the Java
Transaction API methods, which then call the lower-level Java Transaction
Service routines. s a
) h a
m x
A Java Transaction API transaction is controlled by the Java EE transaction
g ob
manager. These transactions can span updates to multiple databases from different
t
s a de
vendors. A particular DBMSs transaction manager may not work with
heterogeneous databases.
n a l@ Gui
b er dent
e s to Stu
ern euntil
Note The Java EE transaction manager
an (instance
cannot start a transaction for z
s support nested transactions. It
doesinot
th the preceding transaction has
ended. e
nd to u s
n a
H er ense
r n al e lic
B e abl
e s to sfer
E rn -tran
s non
C arlo

12-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Context Lifetime

Persistence Context Lifetime


The lifetime of a container-managed persistence context can either be scoped to a
transaction (transaction-scoped persistence context), or have a lifetime scope that
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

extends beyond that of a single transaction (extended persistence context). The


enum PersistenceContextType is used to define the persistence context
lifetime scope for container-managed entity managers.

The persistence context lifetime scope is defined when the EntityManager


instance is created.

The @PersistenceContext annotation is used for entity manager injection. All s a


elements of the @PersistenceContext annotation are optional. ) h a
m x
t g ob
s a de
Table 12-1 Elements of the @PersistenceContext
n a l@ Gui
annotations

b er dent
Name Type e s to StuDescription
Default
( e rn this
name String
d e z use The name by which the entity
n n

a et o manager is to be accessed in the
r
e ens environment referencing context.
l H
a e li c The name is not needed when
r
e abn l dependency injection is used.
B er
to PersistenceProperty[]
e s
properties
n s f Used to specify properties for the
r n
E n-t r a container or persistence provider.
s
C arlo no Vendor-specific properties may be
included in this set of properties.
Properties that are not recognized
by a vendor are ignored.
type PersistenceContextType TRANSACTION Specifies whether this is a
transaction-scoped persistence
context (TRANSACTION) or an
extended persistence context
(EXTENDED).
unitName String The name of the persistence unit.

Code 12-1 Using the @PersistenceContext Annotation to Inject an Entity


Manager Into a Class.

Implementing Transactions and Locking 12-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Persistence Context Lifetime

1 public class ItemDao{


2 @PersistenceContext(unitName = JpaDemoPU,
3 type = PersistenceContextType.TRANSACTION)
4 private EntityManager entityManager;
5 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

12-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Controlling Java Persistence API Transactions

Controlling Java Persistence API Transactions


Depending on the transactional type of the entity manager, transactions involving
entity manager operations may be controlled either through the Java Transaction
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

API or through use of the resource-local Entity Transaction API, which is


mapped to a resource transaction over the resource that underlies the entities
managed by the entity manager.
An entity manager whose underlying transactions are controlled through
Java Transaction API is called a Java Transaction API entity manager.
An entity manager whose underlying transactions are controlled by the
application through the Entity Transaction API is called a resource-local s a
entity manager. ) h a
m x
t g ob A container-managed entity manager must be a Java Transaction API entity
manager. These entity managers are only specified for use in Java EE
s a de
n a l@ Gui containers.
An application-managed entity manageremay
b r be eeither
n t a Java Transaction

to entity
API entity manager or a resource-local d
tumanager.
e s S
Both Java Transaction API
( e rnentity tmanagers
hisin JavaandEEresource-local entity
d e
managers are required z to be
u s e
supported web containers and EJB
containers. an to
r n e
H
Within
l c ns
ean EJBeenvironment, a Java Transaction API entity manager is
a l i
B ern typically
b l e used.
s t o sfeInrageneral, in Java SE environments only resource-local entity managers are
E rne -tran supported.
arlos non
C
Java Transaction API Entity Managers
An entity manager whose transactions are controlled through Java Transaction
API is a Java Transaction API entity manager. A Java Transaction API entity
manager participates in the current Java Transaction API transaction, which is
begun and committed external to the entity manager and propagated to the
underlying resource manager.

Implementing Transactions and Locking 12-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Controlling Java Persistence API Transactions

Resource-Local Entity Managers


An entity manager whose transactions are controlled by the application through
the Entity Transaction API is a resource-local entity manager. A resource-local
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

entity manager transaction is mapped to a resource transaction over the resource


by the persistence provider. Resource-local entity managers may use server or
local resources to connect to the database and are unaware of the presence of JTA
transactions that may or may not be active.

s a
EntityTransaction Interface ) h a
m x
t
The EntityTransaction interface is used to control resource transactions g ob on
resource-local entity managers. s a de
n a l@ Gui
The EntityManager.getTransaction()
b ermethode t the
returns
n
EntityTransaction interface.
e s to Stud

e rn this iused,
When a resource-local entity manager
( s and the persistence provider
e
runtime throws an exception
d z defined
u s e to cause transaction rollback, the
r n an must
persistence provider
e to the transaction for rollback.
mark
H e ens
If the EntityTransaction.commit operation fails, the persistence
a l l i c
ern able
provider must roll back the transaction.
B
to sfer
e s
E rn -tran
arlos non The following example illustrates the creation of an entity manager factory in a
C Java SE environment, and its use in creating and using a resource-local entity
manager.
1 import javax.persistence.*;
2
3 public class PasswordChanger {
4 public static void main (String[] args) {
5 EntityManagerFactory emf =
6 Persistence.createEntityManagerFactory("Order");
7 EntityManager em = emf.createEntityManager();
8 em.getTransaction().begin();
9 User user = (User)em.createQuery
10 ("SELECT u FROM User u WHERE u.name=:name +
11 AND u.pass=:pass")
12 .setParameter("name", args[0])
13 .setParameter("pass", args[1])

12-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Controlling Java Persistence API Transactions
14 .getSingleResult();
15 if (user!=null)
16 user.setPassword(args[2]);
17 em.getTransaction().commit();
18 em.close();
19 emf.close();
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

20 }
21 }

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Implementing Transactions and Locking 12-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Container-Managed Persistence Contexts

Container-Managed Persistence Contexts


When a container-managed entity manager is used, the life cycle of the
persistence context is always managed automatically, transparently to the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

application. The persistence context is propagated with the Java Transaction API
transaction.

A container-managed persistence context may be defined to have either a lifetime


that is scoped to a single transaction or an extended lifetime that spans multiple
transactions. These persistence contexts are called transaction-scoped persistence
contexts or extended persistence contexts respectively.
s a
) h a
m x
t g ob
Container-Managed Transaction-Scoped Persistence s a de
Context n a l@ Gui
b er dent
e s tocontainer-managed
S tu
A new persistence context begins when
e r n the
invoked in the scope of an active( Java Transactionh i s entity manager is
z e t API transaction, and no
current persistence context
n
e
d to u
is already s
associated with the Java Transaction API
r a
n se
transaction. The persistence context is created and then associated with the Java
e en
H transaction.
Transaction API
a l l i c
eThern persistence
b le context ends when the associated Java Transaction API
B a
er commits or rolls back. All entities that were managed by the
to stransaction
e s f
E rn -tran entity manager become detached.
arlos non Ifentities the entity manager is invoked outside the scope of a transaction, any
C loaded from the database will immediately become detached at the
end of the method call.

The following example demonstrates a container-managed transaction-scoped


stateless session bean.

1 @Stateless
2 public class ShoppingCartImpl implements ShoppingCart {
3 @PersistenceContext EntityManager em;
4
5 public Order getOrder(Long id) {
6 Order order = em.find(Order.class, id);
7 order.getLineItems();
8 return order;
9 }

12-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Container-Managed Persistence Contexts

10
11 public Product getProduct(String name) {
12 return (Product) em.createQuery("select p from Product p +
13 where p.name = :name")
14 .setParameter("name", name)
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

15 .getSingleResult();
16 }
17
18 public LineItem createLineItem(Order order,
19 Product product, int quantity) {
20 LineItem li = new LineItem(order, product, quantity);
21 order.getLineItems().add(li);
22 em.persist(li); s a
23 return li; ) h a
24 } m x
} 25
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
Container-Managed Extended
( e rn thPersistence
is Context
d e z use
A container-managed
r n an extended
e to persistence context can only be initiated within
H e s bean.
the scope ofea statefulnsession
l c
a e li exists from the point at which the stateful session bean that
rn The context
e l
B
o sfer a b
s t declares a dependency on an entity manager of type

E rne -tran PersistenceContextType.EXTENDED is created and is said to be bound


s non to the stateful session bean.

C arlo The persistence context is closed by the container when the @Remove
method of the stateful session bean completes or the stateful session bean
instance is otherwise destroyed.
If a stateful session bean instantiates a stateful session bean executing in the
same EJB container instance that also has an extended persistence context,
the extended persistence context of the first stateful session bean is inherited
by the second stateful session bean and is bound to it. This rule then
recursively applies, independently of whether transactions are active at the
point of the creation of the stateful session beans.
If the persistence context has been inherited by any stateful session beans,
the container does not close the persistence context until all such stateful
session beans have been removed or otherwise destroyed.

The following code demonstrates a container-managed extended-persistence


stateful session bean.

Implementing Transactions and Locking 12-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Container-Managed Persistence Contexts

1 @Stateful
2 @Transaction(REQUIRES_NEW)
3 public class ShoppingCartImpl implements ShoppingCart {
4 @PersistenceContext(type=EXTENDED)
5 EntityManager em;
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

6 private Order order;


7 private Product product;
8
9 public void initOrder(Long id) {
10 order = em.find(Order.class, id);
11 }
12
13 public void initProduct(String name) { s a
14 product = (Product) em.createQuery("select p from Product p + ) h a
m x 15 where p.name = :name")
t g ob 16 .setParameter("name", name)
s a de 17 .getSingleResult();
n a l@ Gui 18 }
b er dent 19
to S{tu
public LineItem createLineItem(int quantity)
e s 20
LineItem li = new LineItem(order,
( e rn product,
t h is quantity); 21
order.getLineItems().add(li);
d e z use 22

an e to
em.persist(li); 23
return li; r n
e ens 24
} l H
a e lic 25
} r n
e abl 26
B
to sfer
e s
E rn -tran
arlos non
C

12-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Optimistic Locking

Optimistic Locking
Optimistic locking is a technique that is used to ensure that updates to the
database data corresponding to the state of an entity are made only when no
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

intervening transaction has updated that data since the entity state was read.
This technique ensures that updates or deletes to that data are consistent
with the current state of the database and that intervening updates are not
lost.
Transactions that would cause this constraint to be violated result in an
OptimisticLockException being thrown and the transaction being
marked for rollback. s a
) h a
m x
Version Attribute
t g ob
s a de
a l@ for i must
uentities
Portable applications that wish to enable optimistic n locking G
r is, persistent
ethat n t properties or
specify Version attributes for those entities,
to S b e
ud in the XML descriptor
s
fields annotated with the Version annotation or tspecified
e
rn this
as version attributes.
( e
z enabled e for optimistic locking if it has a property
d e u s
an withe atVersion
An entity is automatically
r n
or field mapped o mapping.
e n s

n a l HVersion
The l i c efield can be one of the following data types: int, long,
B er short,
a b lejava.lang.Integer, java.lang.Long, java.lang.Short,
e s to sfeorr java.sql.Timestamp.
E rn -tran An entity may access the state of its version field or property or export a
s non
C arlo method for use by the application to access the version, but must not modify
the version value. Only the persistence provider is permitted to set or update
the value of the version attribute in the object.
The version attribute is updated by the persistence provider runtime when
the object is written to the database. All non-relationship fields and
properties and all relationships owned by the entity are included in version
checks.
Applications are strongly encouraged to enable optimistic locking for all
entities that might be concurrently accessed or that might be merged from a
disconnected state.
Failure to use optimistic locking could lead to inconsistent entity state, lost
updates and other state irregularities.

Implementing Transactions and Locking 12-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Optimistic Locking

If optimistic locking is not defined as part of the entity state, the application
must be designed to maintain data consistency.

Code 12-2 Using the @Version Annotation


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

1 @Entity
2 public class Item{
3 @Id
4 private int id;
5 @Version
6 private int version;
7
8 //... s a
9 }
) h a
m x
t g ob
s a de
The persistence providers implementation of the merge a @ Gumust
loperation i examine
n
er anddthrow nt an
the version attribute when an entity is being merged
b
tobeingSmerged e
u is a stale copy of the
OptimisticLockException if the object
e s t
( e rn since
entity, that is, the entity has been updated
t h isthethisentity became detached.
Depending on the implementation
e z s e
strategy used, exception might not be
thrown until flush is called
n a nd or tcommit
o u time, whichever happens first.
H er containe n se
a l
If only certain
n i
entities
l c version attributes, the persistence provider runtime
er atobcheck
is required
B le those entities for which version attributes have been
s t o sfer
specified. The consistency of the object graph is not guaranteed, but the absence

E rne -trofcompleting.
n attributes on some of the entities will not stop operations from
aversion
arlos non
C

12-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Pessimistic Locking

Pessimistic Locking
Optimistic locking is typically appropriate in dealing with moderate contention
among concurrent transactions. However, in some applications it might be useful
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

to immediately obtain long-term database locks for selected entities because of


the often late failure of optimistic transactions. Such immediately obtained long-
term database locks are referred to here as pessimistic locks.

Pessimistic locking guarantees the following once a transaction has obtained a


pessimistic lock on an entity instance:
No other transaction, whether a transaction of an application using the Java
s a
Persistence API or any other transaction using the underlying resource, may
) h a
m x
successfully modify or delete that instance until the transaction holding the
lock has ended.
t g ob
If the pessimistic lock is an exclusive lock, that same s atransaction
d e may
modify or delete that entity instance. al@ t Gu i
r n
e den
o b
n
provider must lock the database rrows esthatt pessimistic
When an entity instance is locked using
is S tu locking, the persistence
correspond to the non-collection-valued
(
z usee
persistent state of that instance. t h
d e
an e tstrategy
If a joinedninheritance
r o is used, or if the entity is otherwise mapped
to aH
l
e etable,
secondary
c ns this entails locking the rows for the entity instance in
l e li tables.
rnathe additional
e
B eEntityab relationships for which the locked entity contains the foreign key will
t o f r
r n es rans also be locked, but not the state of the referenced entities unless those
s E n-t entities are explicitly locked.
ar l o n o
C Element collections and relationships for which the entity does not contain
the foreign key (such as relationships that are mapped to join tables or
unidirectional one-to-many relationships for which the target entity contains
the foreign key) will not be locked by default.
Element collections and relationships owned by the entity that are contained
in join tables will be locked if the javax.persistence.lock.scope
property is specified with a value of
PessimisticLockScope.EXTENDED. This property may be passed as an
argument to the methods of the EntityManager and Query interfaces that
enable lock modes to be specified or used with the NamedQuery
annotation.

Implementing Transactions and Locking 12-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Pessimistic Locking

Note A portable application should not rely on the way that pessimistic locking
is achieved on the database. In particular, a persistence provider or the underlying
database management system might lock more rows than the ones selected by the
application.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

12-18 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Lock Modes

Lock Modes
Lock modes can be specified by means of the EntityManager lock method,
the methods of the EntityManager and Query interfaces that allow lock modes
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

to be specified, and the NamedQuery annotation.

Lock mode values are defined by the LockModeType enum. The six distinct lock
modes are:
OPTIMISTIC
OPTIMISTIC_FORCE_INCREMENT
s a
PESSIMISTIC_READ
) h a
m x PESSIMISTIC_WRITE
PESSIMISTIC_FORCE_INCREMENT t g ob
s a de
NONE
n a l@ Gui
b er dent
Note The lock mode type values e s toand WRITE
S tu are supported for backwards
n READ
is 1.0 applications.
(er API
compatibility with Java Persistence
z e thversion
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer and OPTIMISTIC_FORCE_INCREMENT
OPTIMISTIC
E rn Modes
- t r an
arlos non
C This section describes the semantics of requesting locks of type
LockModeType.OPTIMISTIC and
LockModeType.OPTIMISTIC_FORCE_INCREMENT.

If transaction T1 calls lock(entity, LockModeType.OPTIMISTIC) on a


versioned object, the entity manager must ensure that neither of the following
phenomena can occur:
Dirty read: Transaction T1 modifies a row. Another transaction T2 then
reads that row and obtains the modified value before T1 has committed or
rolled back. Transaction T2 eventually commits successfully. Whether T1
commits or rolls back and whether it does so before or after T2 commits is
immaterial.

Implementing Transactions and Locking 12-19


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Lock Modes

Non-repeatable read: Transaction T1 reads a row. Another transaction T2


then modifies or deletes that row before T1 has committed. Both
transactions eventually commit successfully.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note The persistence implementation is not required to support calling


lock(entity, LockModeType.OPTIMISTIC) or lock(entity,
LockModeType.OPTIMISTIC_FORCE_INCREMENT) on a non-versioned object.
When it cannot support such a lock call, it must throw the
PersistenceException.

s a
) h a
m x
PESSIMISTIC_READ, PESSIMISTIC_WRITE, andgob
PESSIMISTIC_FORCE_INCREMENT Modes sat de

n a l@ Gui
b r ofetype
elocks n t

to Stud
This section describes the semantics of requesting
LockModeType.PESSIMISTIC_READ, e s
LockModeType.PESSIMISTIC_WRITE, ( e rn tand his
z
de to us e
LockModeType.PESSIMISTIC_FORCE_INCREMENT.
a n

If transactionH rn lock(entity,
T1ecalls n se LockModeType.PESSIMISTIC_READ)
l c e
liLockModeType.PESSIMISTIC_WRITE) on an object, the
e na lmust
or lock(entity,
rmanager e
o B
entity
r a b ensure that neither of the following phenomena can occur:
n e st nsDirty
fe read: Transaction T1 modifies a row. Another transaction T2 then
s Er n-tra reads that row and obtains the modified value before T1 has committed or
arlo no rolled back.
C Non-repeatable read: Transaction T1 reads a row. Another transaction T2
then modifies or deletes that row before T1 has committed or rolled back.

Any such lock must be obtained immediately and retained until transaction T1
completes (commits or rolls back).
A lock with LockModeType.PESSIMISTIC_WRITE can be used to query
data when there is a high likelihood of deadlock or update failure among
concurrent updating transactions.
A lock with LockModeType.PESSIMISTIC_READ can be used to query
data using repeatable-read semantics without the need to reread the data at
the end of the transaction to obtain a lock, and without blocking other
transactions reading the data.

12-20 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Lock Modes

A lock with LockModeType.PESSIMISTIC_WRITE_FORCE_INCREMENT


will always update the Version attribute, if it exists.

Note The persistence implementation must support calling lock(entity,


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

LockModeType.PESSIMISTIC_READ) and lock(entity,


LockModeType.PESSIMISTIC_WRITE) on a non-versioned entity as well as on
a versioned entity.

When the lock cannot be obtained and the database locking failure results in
transaction-level rollback, the provider must throw the
PessimisticLockException and ensure that the Java Transaction API
s a
transaction or EntityTransaction has been marked for rollback.
) h a
m x
b in only
When the lock cannot be obtained, and the database locking failureoresults
g
t
a de
s
statement-level rollback, the provider must throw the LockTimeoutException
and must not mark the transaction for rollback.
n a l@ Gui
r ent
iseobtained
b
calculate the amount of the highest e s
Bid.
to Stud on an Auction entity to
In the following example, a pessimistic lock

( e rn this
d e z uLock
Code 12-3 Using a Pessimistic s e
r n an e to
H e ens
l
a e licauctionId){
public void endAuction(int
n
Auction auction r b l
e = aem.find(Auction.class, auctionId);
o B r
n e st nsfe= (Bid) em.createNamedQuery("findHighestBidByAuctionId")
em.lock(auction, LockModeType.PESSIMISTIC_WRITE);

s
Bid
n - tra
Er .setParameter("auctionId",
highestBid
auctionId)
r l o n o
Ca .getSingleResult();
auction.setWinningBid(highestBid);
}

Implementing Transactions and Locking 12-21


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Lock Modes
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

12-22 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Module 13
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Advanced Java Persistence API Concepts

Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
t g ob
Specify composite primary keys
s a de
a
Override mappings with the @AttributeOverride
n l@ and G ui
@AssociationOverride annotations er n t
b e
e
Understand entity listeners and s
callback S tud
to methods
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C

13-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

"JSR 317: Java Persistence, Version 2.0, Java Persistence API,"


[http://jcp.org/en/jsr/detail?id=317], accessed September 15,
2009.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

13-2 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Composite Primary Keys

Composite Primary Keys


Every entity must have a primary key. Without a primary key, the entity cannot
be a part of a persistence context because there is no way to uniquely identify the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

entity.

Up until now, the focus has been on entities that use a single field to represent the
primary key. Entities can, however, use multiple fields as a unique identifier. This
identifier is called a composite primary key.

Note Composite primary keys typically arise when mapping from legacy s a
databases where the database key is comprised of several columns. ) h a
m x
A simple, that is, non-composite, primary key must correspond
t g ob to a single
s
persistent field or property of the entity class. The @Ida annotation
d e or id
XML element must be used to denote a simple @ Gkey.
alprimary u i
r n
e to either t
na single persistent field
A composite primary key must correspond
o b d e
st or properties.
or property or to a set of suchefields
n S tu

z
A primary key class
e his to represent a composite primary
r betdefined
(emust
key.
a n
de to us
e
Thern@EmbeddedId
n se or @IdClass annotation is used to denote a
H
al composite e
r n l e lic primary key.
B e ab
e s t o s f er
E rn -tran
arlos non The following rules apply to composite primary keys:
C The primary key class must be public and must have a public no-arg
constructor.
The access type (field-based or property-based access) of a primary key
class is determined by the access type of the entity for which it is the
primary key unless the primary key is an embedded id and a different
access type is specified.
If property-based access is used, the properties of the primary key class
must be public or protected.
The primary key class must be serializable.
The primary key class must define equals and hashCode methods. The
semantics of value equality for these methods must be consistent with the
database equality for the database types to which the key is mapped.

Advanced Java Persistence API Concepts 13-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Composite Primary Keys

A composite primary key must either be represented and mapped as an


embeddable class or must be represented as an id class and mapped to
multiple fields or properties of the entity class.
If the composite primary key class is represented as an id class, the names
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

of primary key fields or properties in the primary key class and those of the
entity class to which the id class is mapped must correspond and their types
must be the same.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

13-4 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Defining a Composite Primary Key With the @EmbeddedId Annotation

Defining a Composite Primary Key With the @EmbeddedId


Annotation
One way to define a composite primary key is to create a class outside the entity
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

class definition. This class must be marked with the @Embeddable annotation.

Instances of embeddable classes, unlike entity instances, do not have persistent


identity of their own. Instead, they exist only as part of the state of the entity to
which they belong.

Note Embedded classes used to identify a composite primary key must not have s a
) h a
m x a primary key of their own.

t g ob
s
Once the embeddable class is defined, the entity class then adeclaresdea field
of the
embeddable class type and marks it with the @EmbeddedId u i
al@ t Gannotation.
r n
e den
Code 13-1 Using the @Embeddable t o b uto Identify the Composite
Primary Key Class rn e s Annotation
S t
z (e e this
1 package com.acme.entities;de us
a n
t o
2
e rn nse
3
4 n a l H lice
import java.io.Serializable;
import javax.persistence.Embeddable;
5 B er able
6 s to sfer
@Embeddable
e
7 rpublic
E - an EmployeeId implements Serializable{
n trclass
arlos89 nonprivate String firstName;
C private String lastName;
10
11 public EmployeeId(){}
12
13 public EmployeeId(String firstName, String lastName) {
14 this.firstName = firstName;
15 this.lastName = lastName;
16 }
17
18 public String getFirstName() {
19 return firstName;
20 }
21
22 public void setFirstName(String firstName) {
23 this.firstName = firstName;
24 }

Advanced Java Persistence API Concepts 13-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Defining a Composite Primary Key With the @EmbeddedId Annotation

25
26 public String getLastName() {
27 return lastName;
28 }
29
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

30 public void setLastName(String lastName) {


31 this.lastName = lastName;
32 }
33
34 @Override
35 public boolean equals(Object obj) {
36 if (obj == null) {
37 return false; s a
38 } ) h a
39 if (getClass() != obj.getClass()) { m x
40 return false;
t g ob
41 } s a de
42 a l@ Gui
final EmployeeId other = (EmployeeId) obj;
n
43 er dent
if ((this.firstName == null) ? (other.firstName != null) :
b
44 to Stu
!this.firstName.equals(other.firstName)) {
e s
45 rn this
return false;
( e
46 }
d e z use
an e to
47 if ((this.lastName == null) ? (other.lastName != null) :
48 r n
e ens !this.lastName.equals(other.lastName)) {
49 l H
a e lic return false;
r n
e abl
50 }
B
to sfer
51 return true;
e s
rn -tran
52 }
E
s n@Override 53
arlo on 54
C 55
public int hashCode() {
56 int hash = 7;
57 hash = 67 * hash + (this.firstName != null ?
58 this.firstName.hashCode() : 0);
59 hash = 67 * hash + (this.lastName != null ?
60 this.lastName.hashCode() : 0);
61 return hash;
62 }
63 }

13-6 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Defining a Composite Primary Key With the @EmbeddedId Annotation

Once the @Embeddable class is defined, you can use it as a primary key in an
entity class by marking the field with the @EmbeddedId annotation.

Code 13-2 Using the @EmbeddedId Annotation to Identify the Composite


Primary Key
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

1 package com.acme.entities;
2
3 import java.io.Serializable;
4 import javax.persistence.EmbeddedId;
5 import javax.persistence.Entity;
6
7 @Entity
s a
8 public class Employee implements Serializable {
) h a
9
m x
10
@EmbeddedId
t g ob
11
private EmployeeId id;
s a de
12
n a l@ Gui
13
public EmployeeId getId() {
b er dent
14
return id;
e s to Stu
} 15
16 ( e rn this
17
public void setId(EmployeeId d e z id) u s e{
this.id = id;nan
18 to
r
e ens e
} 19
l H
a e lic
r n
20
e abl
B
// ... 21
er
} sto s f
22
e
rn -tran
E
s non
C arlo Note All of the attributes of the Embedded Id class will be persisted as columns
in the table that corresponds to the entity.

Finding Entities With an Embedded ID Using an Entity


Manager
You can use the entity manager find() method to find entity classes with
composite keys by creating an instance of the Embedded ID class and passing it
to the find() method.

Code 13-3 Finding an Entity With an Embedded ID Composite Primary Key

Advanced Java Persistence API Concepts 13-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Defining a Composite Primary Key With the @EmbeddedId Annotation

1 EmployeeId id = new EmployeeId(Jane, Doe);


2 Employee employee = em.find(Employee.class, id);
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

13-8 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Defining a Composite Primary Key With the @IdClass Annotation

Defining a Composite Primary Key With the @IdClass


Annotation
The second way of defining a composite primary key in an entity is to use the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

@IdClass annotation. While you still must define an external class as you did
when using an Embedded ID class, the key differences between the two methods
are:
The ID class is not annotated
The fields of the Entity class that comprise the composite primary key must
be annotated with the @Id annotation
s a
The fields of the ID class must match the name and data type of the Entitys
) h a
composite primary key fields exactly
m x
t g ob
s aPrimary
Code 13-4 Creating an ID Class to Identify the Composite
d e of an
Key
Entity
al@ t Gu i
r n
e den
1 package com.acme.entities;
o b
2
n e st S tu
3 import java.io.Serializable; (er
z e t his
4
5 a n
de to us
import javax.persistence.Embeddable;

6 public class EmployeeId e rn implements


n se Serializable{
7 private String l H
a e li c e
firstName;
e rnString
b l lastName;
8 private
B
to sfer a
9
e s
10 rn public
E - t r an EmployeeId(){}
s11 n
C arlo 12 no public EmployeeId(String firstName, String lastName) {
13 this.firstName = firstName;
14 this.lastName = lastName;
15 }
16
17 public String getFirstName() {
18 return firstName;
19 }
20
21 public void setFirstName(String firstName) {
22 this.firstName = firstName;
23 }
24
25 public String getLastName() {
26 return lastName;
27 }

Advanced Java Persistence API Concepts 13-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Defining a Composite Primary Key With the @IdClass Annotation

28
29 public void setLastName(String lastName) {
30 this.lastName = lastName;
31 }
32
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

33 @Override
34 public boolean equals(Object obj) {
35 if (obj == null) {
36 return false;
37 }
38 if (getClass() != obj.getClass()) {
39 return false;
40 } s a
41 final EmployeeId other = (EmployeeId) obj; ) h a
42 m x
if ((this.firstName == null) ? (other.firstName != null) :
43
g ob
!this.firstName.equals(other.firstName)) {
t
44 return false; s a de
45 }
n a l@ Gui
46 er dent
if ((this.lastName == null) ? (other.lastName != null) :
b
47 to Stu
!this.lastName.equals(other.lastName)) {
e s
48 rn this
return false;
( e
49 }
d e z use
an e to
50 return true;
51 } r n
e ens
52 l H
@Override rna
53 l e lic
public B
e ab
s t o 54
f e r= 7;
int hashCode() {

rne -hash
int 55s
an= 67 * hash + (this.firstName != null ?
hash
E t r 56
s non this.firstName.hashCode() : 0);
C arlo 57
58
hash = 67 * hash + (this.lastName != null ?
59 this.lastName.hashCode() : 0);
60 return hash;
61 }
62 }

Once the ID class is defined, you can use it as a primary key in an entity class. To
do so, mark the entity class with the @IdClass annotation and mark each entity
field with the @Id annotation.

Code 13-5 Using the @IdClass Annotation and @Id Annotations to Identify
the Composite Primary Key
1 package com.acme.entities;

13-10 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Defining a Composite Primary Key With the @IdClass Annotation
2
3 import java.io.Serializable;
4 import javax.persistence.EmbeddedId;
5 import javax.persistence.Entity;
6
7 @Entity
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

8 @IdClass(EmployeeId.class)
9 public class Employee implements Serializable {
10
11 @Id
12 private String firstName;
13 @Id
14 private String lastName;
s a
15
) h a
16 // ...
m x
17 }
t g ob
s a de
n a l@ Gui
b er dent
Finding Entities With an IDeClass s to S tu an Entity
Using
n
Manager z (er e this
a n
de to us
e rn find()
The entity manager
n se method can be used to find entity classes with
H
al method. e
composite
r n l e l c do so, create an instance of the ID class and pass it to the
keys. iTo
B e ab
find()

e s t o s f er
E rn -tranCode 13-6 Finding an Entity With an ID Class Composite Primary Key
s non
C arlo 1 EmployeeId 2
id = new EmployeeId(Jane, Doe);
Employee employee = em.find(Employee.class, id);

Advanced Java Persistence API Concepts 13-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Overriding Mappings With the @AttributeOverride Annotation

Overriding Mappings With the @AttributeOverride


Annotation
The @AttributeOverride annotation is used to override the mapping of a field
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

to a table column.
The @AttributeOverride annotation is applied to either an entity or an
attribute.
To override the mapping of an attribute in an embeddable class, apply the
@AttributeOverride to the entity, not the embeddable class.

s a
The @AttributeOverride annotation has two elements that can be used to
) h a
m x further refine the mapping of the entity attribute to the column in the table.

Table 13-1 Elements of the @AttributeOverride Annotationtg


ob
s a de
Name Type Required Description nal
@ Gui
b er dent
column Column yes to that
The column
e s S t uis being mapped
( e rnto the persistent
t h is attribute.
String yes ez s ename of the property whose
name
d uThe
an e to mapping is being overridden if
r n
e ens
l H c
property-based access is being

e rna ble li used, or the name of the field if

o B r a field-based access is used.

n e st nsfe
Er n-trFora example, the following class definition needs to be extended but column a
rlo s no name needs to be remapped.
C a
Code 13-7 The Employee Class
@MappedSuperclass
public class Employee {
@Id protected Integer id;
@Version protected Integer version;
protected String address;

public Integer getId() { ... }


public void setId(Integer id) { ... }
public String getAddress() { ... }
public void setAddress(String address) { ... }
}

13-12 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Overriding Mappings With the @AttributeOverride Annotation

To remap the address field, add a @AttributeOverride annotation.

Code 13-8 Overriding the address Field with the @AttributeOverride


Annotation
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

@Entity
@AttributeOverride(name="address", column=@Column(name="ADDR"))
public class PartTimeEmployee extends Employee {
// address field mapping overridden to ADDR
protected Float wage();
public Float getHourlyWage() { ... }
public void setHourlyWage(Float wage) { ... }
}
s a
) h a
m x
Overriding Multiple Mappings With the
t g ob
@AttributeOverrides Annotation s a de
n a l@ Gui
b er dent
To override multiple mappings, use the @AttributeOverrides annotation.
t o t u
r n es is S
(e ande id
Code 13-9 Overriding address
Annotationez
thwith the @AttributeOverrides
a n
d to us
@Entity e rn nse
@AttributeOverrides({
n a l H lice
B er able
@AttributeOverride(name="address", column=@Column(name="ADDR"))

}) nes
to sfer
@AttributeOverride(name="id", column=@Column(name="SSN"))
r class t r n
aPartTimeEmployee
s E
public
n - extends Employee {
r l o o
n address field mapping overridden to ADDR
Ca
//
// id field mapping overridden to SSN
protected Float wage();
public Float getHourlyWage() { ... }
public void setHourlyWage(Float wage) { ... }
}

Advanced Java Persistence API Concepts 13-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Overriding the Default Mapping of Collections

Overriding the Default Mapping of Collections


The @AttributeOverride annotation may be applied to an element collection
containing instances of an embeddable class or to a map collection whose key or
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

value is an embeddable class.

When the @AttributeOverride annotation is applied to a map, key. or


value. must be used to prefix the name of the attribute that is being overridden
in order to specify it as part of the map key or map value.

Code 13-10 Overriding Multiple Column Mapping of a Map Collection


s a
) h a
@Entity
m x
public class PropertyRecord {
t g ob
@EmbeddedId
s a de
PropertyOwner owner;
n a l@ Gui
@AttributeOverrides({
b er dent
e s to Stu
@AttributeOverride(name="key.street",

( e rn this
column=@Column(name="STREET_NAME")),
@AttributeOverride(name="value.size",
d e z use
column=@Column(name="SQUARE_FEET")),
n an e to
@AttributeOverride(name="value.tax",
r
H e ens column=@Column(name="ASSESSMENT"))
n
}) l
a e lic
r
e abl
B
to sfer
@ElementCollection
e s Map<Address, PropertyInfo> parcels;
E rn -tran }
s non
arlo
@Embeddable
C public class PropertyInfo {
Integer parcelNumber;
Integer size;
BigDecimal tax;
}

13-14 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Overriding Mappings for Entity Relationships With the @AssociationOverride

Overriding Mappings for Entity Relationships With the


@AssociationOverride Annotation
The @AssociationOverride annotation is used to override a mapping of
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

property or field for an entity relationship.

The @AssociationOverride annotation may be applied to an entity that


extends a mapped superclass to override a relationship mapping defined by the
mapped superclass.

The @AssociationOverride annotation may be used to override a


s a
relationship mapping from an embeddable class within an entity to another entity
) h a
m x when the embeddable class is on the owning side of the relationship.

t g ob element
of the @AssociationOverride annotation is used.l@ sarelationship
If the relationship mapping is a foreign key mapping, the joinColumns
If the i d e mapping
uses a join table, the joinTable element of the r n a t Gu
@AssociationOverride
annotation must be specified to overrideothe b e deofnthe join table or its join
mapping
columns.
n e st S tu
z (er e this
further refine a n a ndefor tano entity
The @AssociationOverride
mapping
us
annotation has three elements that can be used to
relationship: name, joinColumns, and
joinTable.H er ense
r n al e lic
B e abl
e s to Note
s f erEither the joinColumns element or the joinTable element of the
E rn -tran@AssociationOverride annotation is specified for overriding a given
arlos non relationship, but never both.
C

Table 13-2 Elements of the @AssociationOverride Annotation

Name Type Required Description

joinColumns JoinColumn[] Yes if The column or columns that are


joinTable being mapped to the persistent
is not used attribute.
joinTable JoinTable Yes if The table that is used to map the
joinColumn relationship.
is not used

Advanced Java Persistence API Concepts 13-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Overriding Mappings for Entity Relationships With the @AssociationOverride

Table 13-2 Elements of the @AssociationOverride Annotation

Name Type Required Description

name String Yes The name of the relationship


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

property whose mapping is being


overridden if property-based
access is being used, or the name
of the relationship field if field-
based access is used.

Code 13-11 Overriding the Relationship Mapping With the


@AssociationOverride Annotation s a
) h a
m x
@MappedSuperclass
t g ob
public class Employee {
s a de
...
n a l@ Gui
@ManyToOne
b er dent
protected Address address;
e s to Stu
}
...
( e rn this
d e z use
@Entity
r n an e to
H e ens
@AssociationOverride(name="address",
n l
a e lic
joinColumns=@JoinColumn(name="ADDR_ID"))
// address B
r
e mapping b l overridden to ADDR_ID fk
field
er a
to PartTimeEmployee
publicsclass f
n e n s extends Employee {

s Er ...n-tra
arlo no
}
C

13-16 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Entity Listeners and Callback Methods

Entity Listeners and Callback Methods


Entity listeners and callback methods enable you to define special behavior that
should happen when certain life-cycle events occur on an entity, or whenever a
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

life-cycle event occurs on any entity.


A method may be designated as a life-cycle callback method to receive
notification of entity life-cycle events.
A life-cycle callback method can be defined on an entity class, a mapped
superclass, or an entity listener class associated with an entity or mapped
superclass.
s a
An entity listener class is a class whose methods are invoked in response to
) h a
life-cycle events on an entity.
m x
Any number of entity listener classes can be defined for an o
g b class or
entity
t
a de
mapped superclass. s
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

Advanced Java Persistence API Concepts 13-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life-Cycle Callback Methods

Life-Cycle Callback Methods


Life-cycle callback methods correspond to the basic life-cycle events of an entity:
Persist
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Remove
Update
Load

Each life-cycle event has a Pre and Post hook that can be triggered when the
event occurs. Life-cycle callback methods are designated with Pre and Post s a
annotations. ) h a
m x
t g ob
s a de
Table 13-3 Life-Cycle Callback Annotations
n a l@ Gui
b e r ent
Annotation Description
to Stud
e s
n hmethods
@PrePersist PrePersist ( e rcallbackt is are invoked for a given
entity e
d z s e
before the EntityManager.persist()
u method
n
o
e rnais executed.
s e t
l
@PostPersist
a l en
H icPostPersist callback methods are invoked for a given
n
er able entity after the database INSERT is executed.
B er
to @PreRemove
e s n s f PreRemove callback methods are invoked for a given
n
Er n-tra entity before the EntityManager.remove() method
rlo s no is executed.
C a @PostRemove PostRemove callback methods are invoked for a given
entity after the database DELETE is executed.
@PreUpdate PreUpdate callback methods are invoked for a given
entity when an update to the state of entity instance
occurs.
@PostUpdate PostUpdate callback methods are invoked for a given
entity after the database UPDATE is executed.
@PostLoad PostLoad callback methods are invoked after an entity
is loaded, either by a query or when the
EntityManager.find() method is executed.

13-18 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life-Cycle Callback Methods

Note There is no life-cycle annotation for @PreLoad.

Code 13-12 Using the Life-Cycle Annotations to Trigger Lifecycle Callback


Events
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

@Entity
public class Account {
@Id
Long accountId;
Integer balance;
@Transient // because status depends upon non-persistent context s a
boolean preferred; ) h a
m x
@PrePersist
t g ob
protected void validateCreate() { s a de
if (getBalance() < MIN_REQUIRED_BALANCE)
n a l@ Gui
throw new AccountException("Insufficient
b erbalance
e n t +
e s S tud
to opentoan account");
}
( e rn this
@PostLoad
d e z use {
an e to
protected void adjustPreferredStatus()
preferred = r n
l H
(getBalance()
c ns
e >=eAccountManager.getPreferredStatusLevel());
}
e rna ble li
t o B era
s nsf
//e...
n
} Er
s n - tra
arlo no
C
The following rules apply to life-cycle callbacks:
The callback methods can have public, private, protected, or package level
access, but must not be static or final.
A single method may be annotated with multiple life-cycle events, but only
one callback method per life-cycle event should be used in a given entity.
For example, an entity cannot have two different callback methods
annotated with @PostLoad.
Life-cycle callback methods may throw unchecked or runtime exceptions.
A runtime exception thrown by a callback method that executes within a
transaction causes that transaction to be marked for rollback.
Life-cycle callbacks can invoke JNDI, JDBC, JMS, and enterprise beans.

Advanced Java Persistence API Concepts 13-19


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Life-Cycle Callback Methods

The life-cycle method of a portable application should not invoke


EntityManager or Query operations, access other entity instances, or
modify relationships within the same persistence context.
A life-cycle callback method may modify the non-relationship state of the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

entity on which it is invoked.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

13-20 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Creating an Entity Listener Class

Creating an Entity Listener Class


In addition to setting up callbacks to internal entity methods, you can specify one
or more external entity listener classes that react accordingly to life-cycle events.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

An entity listener class must have a public no-arg constructor.


Entity listeners are stateless. The life cycle of an entity listener is
unspecified.
All life-cycle methods must accept the entity as the first and only argument.
One or more entity listener classes can be denoted using the
@EntityListeners annotation on the entity class. If more than one
s a
listener class is specified, the list of classes is comma-delimited.
) h a
m x

t g ob
If multiple entity listeners are defined, the order in which they are invoked
is determined by the order in which they are specified in the
s a de
@EntityListeners annotation.
n a l@ Gui
b er dent
e s to Stu
When invoked from within a(e JavarnEE environment,
this the callback listeners for an
d
entity share the enterprisee znaming u s e
context of the invoking component. The entity
n
o
e rnaareat nthe
callback methods
etimet inat which
invoked
s
the transaction and security contexts of the
l H
calling component
c e the callback method is invoked.

e r na le li
t o f ab Using an Entity Listener Class
B Codee13-13
r
r n es rans
s E n-t
@Entity
l o no
ar @EntityListeners({com.acme.AlertMonitor.class,
C com.acme.PreferredStatusMonitor.class})
public class Account {
// ...
}

public class AlertMonitor {


@PostPersist
public void newAccountAlert(Account acct) {
Alerts.sendMarketingInfo(acct.getAccountId(),
acct.getBalance());
}
}

public class PreferredStatusMonitor {


@PostLoad
public void logActivity(Account acct) {

Advanced Java Persistence API Concepts 13-21


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Creating an Entity Listener Class

if(acct.isPreferred()){
log.info(acct.getAccountId() +
accessed on + new Date());
}
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

The rules for entity listener class callback methods are the same as those for
internal entity callback methods, with two important exceptions:
Only unchecked exceptions are allowed to be thrown. If an exception is
thrown by an entity class listener, the remaining listeners will not be called.
s a
Also, the transaction, if any, will be rolled back after the first exception is
) h a
m x thrown.
g
Superclass listeners are called before subclass listeners. Youtcan
b
ooverride
this behavior by using the @ExcludeSuperclassListeners s a dannotation.
e
al@ t Gu i
r n
e den
o b
n e st S tu
z (er e this
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C

13-22 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Creating an Entity Listener Class

Using Validation
JSR 303 defines an API for validating JavaBean components. The Java
Persistence API does not require a validation implementation to be present. If a
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

validation implementation is present, it can take advantage the basic life-cycle


events of an entity to provide validation.

The validation API defines a standard set of annotations that can be used to
validate an entity.

Code 13-14 Using the Validation Annotations


s a
) h a
@Entity
m x
public class Account {
t g ob
@Id
s a de
@NotNull
n a l@ Gui
Long accountId;
b er dent
@NotNull(message = Description must be provided)
@Size(max=100) e s to Stu
String description; ( e rn this
d e z use
// ...
r n an e to
}
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo Table 13-4 Validation Constraints

Constraint Description

@AssertFalse The field must be false


@AssertTrue The field must be true
@DecimalMax(value=0.0) The field must be less than or
equal to the value
@DecimalMin(value=0.0) The field must be greater than
or equal to the value
@Digits(integer=5) The field must be a number
within the integer range
@Future The field must be a date in the
future

Advanced Java Persistence API Concepts 13-23


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Creating an Entity Listener Class

Table 13-4 Validation Constraints

Constraint Description
@Max(value=0) The field must be less than or
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

equal to the value


@Min(value=0) The field must be greater than
or equal to the value
@NotNull The field must not be null
@Null The field must be null
@Past The field must be a date in the s a
past
) h a
m x
@Pattern(regexpr=...)
t g ob
The field must match the
regular expression
s a de
@Size(min=0, max=100) The field must beaal@ string thatui
n
has a lengthethat
b n tG
r fallsebetween
t
the min
s oand maxtuvalues.
d
e
rn this S
( e
z use
d e
r n an e to
l c e ns
ofea javax.validation.Validator
If an instanceH is present on the classpath,
a e liAPI will use it for validation. A Validator can also be
the JavanPersistence
r
B e
obtained a
frombal javax.validation.ValidatorFactory.
e s to sfer
E rn -trTheanvalidation mode is specified by the
s non javax.validation.ValidationMode. This value can be set either by adding
C arlo a validation-mode element to the persistence.xml file or by passing it
into the constructor of the EntityManagerFactory. The validation mode can
be one of the following values:
Auto - if a validation provider is present, then validation should occur. This
is the default value.
Callback - validation is required. If a validation provider is not present,
then a PersistenceException must be thrown.
None - no validation should occur.

If any of the constraints on an entity fail, a


javax.validation.ConstraintViolationException is thrown.

13-24 Building Database-Driven Applications With the Java Persistence API


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Appendix A
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Java DB

This appendix is an introduction to the Java DB database.

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

A-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Sun Microsystems, Java DB,


[http://developers.sun.com/javadb/], accessed September 15,
2009
John OConner, Using Java DB in Desktop Applications,
[http://java.sun.com/developer/technicalArticles/
J2SE/Desktop/javadb/], accessed September 15, 2009.
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

A-2 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?

What Is Java DB?


Java DB is the Sun supported distribution of the open-source Apache Derby
database. Java DB is written in Java, providing "write once, run anywhere"
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

portability. The language offers standards compliance, a full feature set, and a
small footprint. It can be embedded in Java applications, requiring no
administration by the developer or user. It can also be used in client/server mode.
Java DB is fully transactional and provides a standard SQL interface as well as a
JDBC 4.0 compliant driver. Java DB is available at no cost under the Apache
license.

s a
Installing Java DB ) h a
m x
Java DB is bundled with many Sun products, including the Java t g ob
Development Kit
s aalso download

(JDKTM) 6, NetBeansTM, and GlassFish products. You can
install Java DB separately from a l @ Guide and

b e rn ent
http://developers.sun.com/javadb/downloads/index.jsp.
s t o tud
e r ne his S
Note Running an external z (instanceeoftJava DB for testing and experimentation
n

purposes best simulates
e us environment where an external database
d a realtoproduction
a
rnor MySQL eTM will most likely be used.
e
such as Oracle
n s
n a l H lice
r le Java DB installers are available for the Solaris, Linux, and
ePlatform-specific
b
B
to Windows a
er platforms, but a basic platform independent zip archive is available for
e s s f
E rn -tranunpacking onto any system by any user. On UNIX-like systems, the command
arlos non would typically be unzip javadb-version.zip. Windows system utilities or
C third-party utilities like WinZip can extract zip archives when they are double-
clicked. The zip archive will extract into a javadb directory. To uninstall Java
DB, remove the javadb directory.

After you install Java DB, the following subdirectories are placed in the javadb
directory:
The bin subdirectory contains scripts for starting and stopping Java DB in
client/server configuration, as well as other utility scripts.
The demo subdirectory contains demonstration programs.
The docs subdirectory contains setup, administrator, and reference guides
for the Java DB product.
The javadoc subdirectory contains API documentation. This directory is
particularly useful if you configure your integrated development
environment (IDE) to point to it as the Java DB API Javadoc.

Java DB A-3
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?

The lib subdirectory contains the Java DB libraries packaged as Java


Archive (JAR) files.

Note If you have a full installation of the JDK, you will find JavaDB at
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

JAVA_HOME/db.

Java DB Configurations
Java DB offers two configurations:
Embedded s a
) h a
Client/Server
m x
t g ob
Embedded Configuration s a de
n a l@ Gui
In the embedded configuration, the database is b
er accessible
only e n t from the Java
TM
s
Virtual Machine (JVM ) in which the application
e tud This configuration
to Sexecutes.
provides:
( e rn this
d e z use
Fast access to the database
r n an e to
e ens
Ease of use
H
Non l lic
aadministration
r
e ab l e
o B er DB with the embedded configuration, use the Derby Embedded
t To runsfJava
e s
E rn -trJDBCan driver found in derby.jar. Loading the JDBC driver starts the embedded
s non engine. Making a connection request to a database starts the database if it was not
C arlo already running. No other startup code is needed.

A-4 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?

Figure 13-1 shows Java DB running using the embedded configuration


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
a l@ Gui
Figure 13-1 Java DB Using the Embedded Configuration
n
b er dent
e
Load the JDBC driver by referencings to StuClass.forName method. The
it using the
( e rn this
embedded driver name is org.apache.derby.jdbc.EmbeddedDriver.
d e z use
an to
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection dbConnectioner=nnull;se
a l H icen
String url = "jdbc:derby:auction;user=dbuser;password=dbuserpwd";
try { e rn ble l
t o
dbConnectionB e= rDriverManager.getConnection(url);
a
s s f
E ne (SQLException
} catch
t r a n
rsqle.printStackTrace(); sqle) {

r l o s} non-
C a

Note When running in embedded mode, if the database or credentials dont


exist, they will automatically be created.

Client / Server Configuration

In the client/server configuration, multiple connections from external clients can


be made to the database. The standard Distributed Relational Database
Architecture (DRDA) protocol is used by the JDBC client driver to connect to the
Java DB Network Server across the network.

Java DB A-5
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?

Figure 13-2 shows Java DB running using the client/server configuration


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
Figure 13-2 Java DB Using the Client/Server Configuration
n a l@ Gui
b er dent
On the server, start the Network Serverewith s tothe provided
S tu scripts.
n
javadb\bin > startNetworkServer z (er e this
Apache Derby Network Server - 10.5.1.1
a n
de to- ustarted
s and ready to accept
connections on port 1527 er n se
l H e n
r n aclient
l e lic use the Derby network client driver, found in
From
B e ab
the application,

e s t o f er
derbyclient.jar.
s
The client driver name is

E rn -tran org.apache.derby.jdbc.ClientDriver.
s non
C arlo If you include create=true in the JDBC connection string, the database will be
created by the first client to connect to the database if the database doesnt
already exist. All subsequent connections will connect to the existing database.
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection dbConnection = null;
String url = "jdbc:derby://localhost:1527/auction;create=true";
String user = "dbuser";
String password = "dbuserpwd";
try {
dbConnection = DriverManager.getConnection(url, user, password);
} catch (SQLException sqle) {
sqle.printStackTrace();
}

A-6 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Appendix B
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Introduction to the JavaTM Platform,


Enterprise Edition 6

This appendix is an introduction to the JavaTM Platform, Enterprise Edition 6. a


h a s
x )
m
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

B-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources

Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Sun Microsystems, Java EE 6 Technologies


[http://java.sun.com/javaee/technologies/
javaee6.jsp], accessed September 1, 2009
Sun Microsystems, JSR 316: Java, Platform Enterprise Edition
Specification, v6.0 [http://jcp.org/en/jsr/detail?id=316],
accessed September 1, 2009.
s a
Sun Microsystems, JSR 317: Java Persistence, Version 2.0
) h a
m x [http://www.jcp.org/en/jsr/detail?id=317], accessed

t g ob September 1, 2009.
Sun Microsystems, JSR 318: Enterprise JavaBeans, s a d3.1
Version e
[http://jcp.org/en/jsr/detail?id=318], al@accessed i
u September
1, 2009. r n
e den t G
o b
n e st S tu
z (er e this
an
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C

B-2 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the JavaTM Platform, Enterprise Edition (Java EE)

Introducing the JavaTM Platform, Enterprise Edition (Java


EE)
The Java EE platform consists of the following elements.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

A set of specifications
The primary specification for the Java EE platform is Java Platform,
Enterprise Edition 6 (Java EE 6) Java Specification Request 316 (JSR 316).
Secondary specifications for the Java EE 6 platform cover specific
technology areas of the platform, such as:
s a
Web services technologies
) h a
m x Web application technologies
Enterprise application technologies
t g ob
Management and security technologies l@s
a de

n a G ui
r entechnology
Table 13-5 lists the specifications for theedifferent
b t areas of the
o d
Java EE 6 platform.
n e st S tu
Table 13-5 Java EE 6 Technology Specifications
z (er e this
a n
de to us
Technology Area
e rn Specification
n s e Name JSR

n a l H licJava
Web services technologies
e Application Programming Interface (API) for JSR 311
B er able RESTful Web Services (JAX-RS) 1.1
e s to sfer
E rn -tran Implementing Enterprise Web Services 1.3 JSR 109

arlos non Java API for XML-Based Web Services (JAX-WS) JSR 224
C 2.2
Java Architecture for XML Binding (JAXB) 2.2 JSR 222
Web Service Metadata for the Java Platform JSR 181
Java API for XML-Based RPC (JAX-RPC) 1.1 JSR 101
Java APIs for XML Messaging 1.3 JSR 67
Java APIs for XML Registries (JAXR) 1.0 JSR 93
Web application technologies Java Servlet 3.0 JSR 315
JavaServer TM Faces (JSF) 2.0 JSR 314
JavaServer PagesTM (JSPTM) 2.2/Expression JSR 245
Language (EL) 1.1
A Standard Tag Library for JavaServer Pages 1.2 JSR 52

Introduction to the JavaTM Platform, Enterprise Edition 6 B-3


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the JavaTM Platform, Enterprise Edition (Java EE)

Table 13-5 Java EE 6 Technology Specifications

Technology Area Specification Name JSR


Debugging Support for Other Languages 1.0 JSR 45
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Enterprise Application Bean Validation 1.0 JSR 303


Technologies
Enterprise JavaBeans 3.1 JSR 318
Contexts and Dependency Injection for Java (Web JSR 299
Beans 1.0)
Java EE Connector Architecture 1.6 JSR 322 s a
) h a
Java Persistence API 2.0
m x JSR 317
Common Annotations for the Java Platform 1.1 gob
a t JSR 250
Java Message Service (JMS) API 1.1 l@s e 914
idJSR
a u
Java Transaction API (JTA) 1.1 b e rn ent G JSR 907
t o tud
TM
JavaMail 1.4 s
ne his S JSR 919
e r
( Service t Provider Interface for JSR 196
Management and Security
e z
Java Authentication
s e
Technologies
a nd to u
Containers
n
H e se Contract for Containers 1.3
erJava Authorization
n JSR 115
a l l i c
B ern ableJava EE Application Deployment 1.2 JSR 88

e s to sfer J2EETM Management 1.1


r n r a n JSR 77

o s
Java
o n -tSpecs in Java Java API for XML Processing (JAXP) 1.3
EEE-related JSR 206
l
ar SE n
C
Java Database Connectivity 4.0 JSR 221
Java Management Extensions (JMX) 2.0 JSR 255
JavaBeans Activation Framework (JAF) 1.1 JSR 925
Streaming API for XML (StAX) 1.0 JSR 173

Java EE 6 Software Development Kit (Java EE 6 SDK)


The Java EE 6 SDK consists of the following items:
GlassFishTM
The GlassFish server is the free implementation of the Java EE
Application Server defined in the Java EE 6 specification.
Java EE 6 Samples

B-4 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the JavaTM Platform, Enterprise Edition (Java EE)

Java EE 6 samples contains example code that demonstrates the use of


Java EE 6 technologies.
Java Platform, Standard Edition 6.0 (Java SE 6)
The Java EE 6 classes and interfaces use the Java SE 6 classes and
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

interfaces.
Java BluePrints
The Java BluePrints provide guidelines and best practice information
on the application of Java EE 6 technologies.
API documentation (JavadocTM)
The API documents the Java EE 6 technology classes, interfaces,
s a
annotations and exceptions.
) h a
m x
t g ob Commercial and open-source Java EE application servers and tools
Commercial and open-source Java EE servers are available
s a asdealternatives

a l@ Gu
to GlassFish. The availability of these commercial or i
open-source servers
n
r entdeveloped to the
prevents vendor exclusivity. That is, anyeapplication
b
o executetuonda different application
specification can be easily portedtto
server. e s
n his S
e r
( applications
t
Java EE components e zand s e
n a ndof providing
t o u
The end purpose
e r s e the Java EE 6 platform is to enable the
n components that can be packaged to create enterprise
a l H ofisoftware
creation
c e
l
B ern applications.
a b le
s to sfeTher pool of available third-party commercial and open-source Java EE
e
rn -tran applications and component libraries is increasing.
E
arlos non
C

Introduction to the JavaTM Platform, Enterprise Edition 6 B-5


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture

Examining the Java EE Application Architecture


This section describes the Java EE application architecture.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Examining the Component-Container Architecture


The underlying architecture of Java EE applications is the component-container
architecture. Figure 13-3 illustrates the component-container architecture.
Containers provide:
- Services to components
Container - Execution environment
s a
Components
- House application
- Lifecycle managment
) h a
m x specific functionality
of components

t g ob - Use services provided


by container

s a de - Are managed by the


container
l@ Gui
Components

n a
b er dent
Figure 13-3 Generic Component-Container
e s to Architecture
S tu
n is
z (er e tharchitecture
d e u s
The key features of the component-container are:
r
The separation n aofnapplication-specific
e to functionality and application generic
e n s
n a l H lice
functionality.
r
eComponentsb le house application-specific functionality.
B a
er house the generic functionality common to all enterprise
to sContainers
e s f
E rn -tran applications.
arlos non Containers provide:
C An execution environment for components
Services for components

B-6 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture

Examining the Java EE Implementation of the


Container-Component Architecture
Figure 13-4 shows the Java EE containers associated with the Java EE platform.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Applet
Container

Java EE
Server
EJB Container

s a
h a
m x)
Database

Browser
t g ob
Web Container s a de
n a l@ Gui
b er dent
e s to Stu
Application ( e rn this
Client
d e z use
Container
r n an e to
Figure 13-4e Java EE
l H c e nsApplication Architecture: Generic Elements
e r na le li
t o f ablists the containers used by Java EE applications, the components
B Tablee13-6
r
r n es ranhosted
s by each container, and the machines (client or server) that host the
s E n-t containers.

ar l o no
C Table 13-6 Java EE Platform Containers

Container Component Type Container Host

EJB container EJB beans EJB container is part of the Java EE


application server.
Web container Servlets and JavaServer Web container is part of the Java EE
Pages application server.
Applet container Applets Applet container can be a web browser or
other application that supports the applet
programming model. The applet container is
hosted on a client machine.
Application client Application client Application client container is hosted by the
container component client machine.

Introduction to the JavaTM Platform, Enterprise Edition 6 B-7


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture

Table 13-6 Java EE Platform Containers

Container Component Type Container Host

Web browser Web pages Web browser is hosted by the client machine.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Note Although web browsers are not a Java EE specification-mandated


container, the web browser-to-web page relationship is a container-to- component
relationship,

s a
Figure 13-5 shows the Java EE application architecture with the inclusion of the
) h a
application function-specific components.
m x
Applet
Container t g ob
s a de
n a l@ Gui
Java EE b er dent
ServerApplet
e s to EJB S tuContainer
n
z (er e this
an
de to us
e rn nse Database

n a l H lice Web Page


Web Components EJB Components

er able
Browser

o B r Web Container

n e st nsfe
s Er n-tra
C arlo no Application Client

Application
Client
Container

Figure 13-5 Complete EJB Application Architecture

B-8 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture

The application-specific parts of a Java EE application are embedded in Java EE


application components. Table 13-7 lists the components used in Java EE
applications.

Table 13-7 Java EE Platform Components


Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Component Container Primary Application Functionality

Session bean EJB container Session beans model business processes.


Stateful session beans maintain client session state.
Stateless session beans do not maintain client
session state.
Message-driven EJB container Message-driven beans model message system queue s a
bean ) h
event listeners. That is, message-driven beans model
a
m x
asynchronous message receivers.
t g ob
Servlet Web container Servlets are Java programminga that
language classes
s i d e
construct responsesrn
l@ on
dynamically process requests from
foradisplay G ubrowser. and
web clients

b e dent a
JSP Web container JSP pagess o text-based
tare tu documents that embed Java
r n e S
is execute as servlets to create
( e
technology
z dynamic tcode
h and
econtent for display on a browser.
n d e u s
Application client r
Applicationn aclient e o
tApplication client components model client code
component e s
H icen and execute in an application client container.
container
a l l
Applet e rn Applet
b l e
container Applets model client code and execute in an applet
B
to sfer a container.
e s
E rn -tran
s non
C arlo Examining Java EE Container Services
The Java EE component model relies on both container-based and platform
services for ancillary functionality that is not directly related to the application
business logic. The Java EE platform goes beyond the traditional middleware
server in terms of the range of services that it offers and the generality of
applications that can be supported.

Introduction to the JavaTM Platform, Enterprise Edition 6 B-9


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture

Java EE services can be grouped into the following categories.


Deployment-based services You request deployment-based services
declaratively, using either metadata annotations embedded in code or
Extensible Markup Language (XML) in a file called a deployment
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

descriptor. Deployment-based services might include:


Persistence
Transaction
Security
Injection
Inherent services The container automatically supplies inherent services to s a
components on an as-needed basis. Inherent services include: ) h a
m x
Life-cycle
t g ob
Threading s a de
a l@Method i
uInvocation
n
Remote object communication, such as Remote
er dent G
(RMI) and CORBA b
Vendor-specific functionality n e sto Stufunctionality is added to
Vendor-specific
the Java EE specification, (and
z thisdependent. Vendor-specific
erit isevendor
a de clustering,
functionality can include
n t o us which addresses:
e rn nse
Scalability
lH
rna Failoverlic
e
B e Loada b le
s t o sfer balancing
E rne -tran
s non Note You should consider vendor-specific functionality, such as scalability and
C arlo load balancing, more as a feature of the server than as a service.

API-based services You request API-based services programmatically.


You must include code in the component to request these services. The
following list identifies the most important supporting services and APIs
that are included in the Java EE platform:
Java DataBase Connectivity (JDBCTM) API for database connectivity
This API provides a vendor-neutral way for applications to complete
relational database operations in the Java programming language, with
Structured Query Language (SQL) as the query medium.
Java Naming and Directory Interface (JNDI) API

B-10 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture

This API is used for vendor-neutral access to directory services, such


as Network Information Service Plus (NIS+) and Lightweight
Directory Access Protocol (LDAP). Java EE applications also make
use of the JNDI API to locate components and services using a central
lookup service.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Java RMI over Internet Inter-Object Request Broker (ORB) Protocol


(IIOP) and the interface definition language (IDL) for the Java
application
Together, these services form a CORBA-compliant remote method
invocation strategy. The strength of this strategy over Java RMI
schemes is that it is programming language-independent, so not all
s a
clients of a particular enterprise application need to be written in the
) h a
m x Java programming language.
JavaMail API and JavaBeans Application Framework o
g b
API
t
a to send email
These APIs enable a Java EE software application s i d e
messages in a vendor-independent way.al@ Gu
b e rn ent
Java EE Connector Architecture
s t o tud
This API enables therprovision S
ne hofisintegration modules, called resource
z
adapters, for legacy( e e
systems t in a way that is independent of the
application e s
ndservertovendor.
u
n a

H er Messaging
Java
e n se Service API
r n al This
e lisican API for sending and receiving asynchronous messages.
B e ab l
e s t o s f er Java Transaction API
E rn -tran This API enables software components to initiate and monitor
rlo s no n distributed transactions. Java Transaction Service (JTS) specifies the
C a implementation of a transaction manager, which supports the JTA
Specification at the high-level, and implements the Java programming
language mapping of the Object Management Group (OMG) Object
Transaction Service (OTS) Specification at the low-level.
Java Authentication and Authorization Service (JAAS)
On the Java EE platform, JAAS might be used to integrate an
application server with an external security infrastructure.
Java for XML Processing API
This API provides access to XML parsers. The parsers themselves
might be vendor-specific but as long as they implement the JAXP
interfaces, vendor distinctions should be invisible to the application
programmer.
Web services integration features

Introduction to the JavaTM Platform, Enterprise Edition 6 B-11


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture

These services include Simple Object Access Protocol (SOAP) for the
Java application, SOAP with Attachments API for Java (SAAJ),
JAXR, and JAX-RPC. Together these services enable Java EE
software applications to respond to and to initiate XML-based RPC
and messaging operations, which provides a full web services
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

platform.
Java Management Extensions API
This API exposes the internal operation of the application server and
its components for control and monitoring vendor-neutral
management tools.
Timer services
s a
h a
m x)
These services provide the ability to run scheduled background tasks.

t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

B-12 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examine the EJB Application Creation Process

Examine the EJB Application Creation Process


The following steps provide a high-level overview of a process you could follow
to create an EJB application. This process assumes that you have already selected
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

the Java EE application server that will host your application.


1. Use your preferred object-oriented methodology to analyze the business
problem. The analysis should identify the following:
The functional requirements of the application, that is, the business
use cases
The non-functional requirements of the application, such as scalability
s a
requirements
) h a
The business logic that services the use cases
m x
Persistence data required by the application t g ob
s a de
n a l@ Guiexpressed as
This is a design step. The outputs of this step are normally
UML notations.
b er dent
s
2. Analyze the inter-tier communications
e to requirements.
S tu
n
Identify the synchronous
z this
(er ecommunication requirements of the
applicationde us
a n
t o

e rn thensasynchronous
Identify e communication requirements of the
H
al e lic e
application
r n l classes to model the persistence data.
e3. Useabentity
B
to sfeThis r
n e s n is an implementation step. The output of this step is a set of Java
r
E n-t r a technology classes and associated configuration data, such as object-
l o s o
C ar n relational mapping information.

Note As of EJB 3.0 specification, the configuration data is usually included in


the entity classes using metadata annotations. This design is true for both session
beans and message-driven beans. Before the EJB 3.0 specification, configuration
data was contained in an XML file. This file was referred to as a deployment
descriptor file.

Introduction to the JavaTM Platform, Enterprise Edition 6 B-13


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examine the EJB Application Creation Process

4. Use session beans to model the server-side business logic and synchronous
service faade for the server-side components.
In practice, this step requires an in-depth analysis of the server-side
business logic requirements. This step includes the application of Java EE
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

patterns to meet the non-functional requirements of the application.


This is an implementation step. The output of this step is a set of session
bean components and associated helper classes. Session bean components
consist of session bean business interfaces, corresponding implementation
cases, and associated configuration data. With EJB 3.0, the configuration
data is usually included in the enterprise bean classes using metadata
annotations.
s a
5. Use the JMS API and message-driven beans to model the asynchronous
) h a
communication requirements of the application.
m x
This is an implementation step. The output of this step is a set
t g obmessage-
of
driven bean components and associated helper classes. sa e
al@ t Gu i d
6. Create the client. r n
e den
o b
t ofSthis
This is an implementation step. The output
e s tu step is the client code.
( e rn this
7. Assemble and package the application.
d e z useof configuring the individual Java EE
an ebeans)
Application assembly is the process
n
components r(enterprise to created in the previous steps to work
l
together H c e ns
asean application.
rna bleis the li process of combining individual enterprise beans and their
ePackaging
B associated
s t o f e ra classes into one or more Java EE modules. A Java EE module
s
rne -tran represents the basic unit of composition of a Java EE application. In some
E
s non circumstances, a single Java EE module can constitute a complete
ar l o application. A Java EE module is also the smallest unit you can deploy in
C an application server.
8. Deploy the server-side components.
Deployment is the process of configuring Java EE modules to execute in a
specific application server.
9. Package and distribute the client.
The objective of this step is to produce a client in a format that is ready for
distribution and deployment. The actual activities performed depend on the
type of client produced, for example stand-alone Java SE client, application
client, web client, or web service client.

B-14 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examine the EJB Application Creation Process

In practice, enterprise bean components are combined with other Java EE


components such as servlets and JSPs to form a Java EE application. Figure 13-6
illustrates the creation of Java EE components and their assembly into Java EE
modules that are then deployed as a Java EE application in an application server.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

Application Application
Component Provider Assembler

Assemble
TM
- Client Module
Application - EJB Component
Components Module
TM - Web Module
s a
- Resource Module
) h a
m x
ob
Application
t
a de g Server
s
Deployer Deployment
n a l@ Gui
Applications
Tool
b e r ent R
RAR JAR t o t u d EA
<ejb-
s
ne his S
WAR
( e r t
TM
TM
e z s e
n a nd to u
e
erJavaeEEnsApplication
a H
Figure l13-6
i c Development Process
l
B ern able
s t o sfeTher roles shown in Figure 13-6 are described in Table 13-8.
r n e ran
E t EE Platform Roles
Table 13-8n-Java
s
ar l o n o
C Role Primary Function

Application Component The multiple roles for Application Component Providers include
Provider HTML document designers, document programmers, and enterprise
bean developers. These roles use tools to produce Java EE
applications and components.
Application Assembler The Application Assembler takes a set of components developed by
Application Component Providers and assembles them into a
complete Java EE application delivered in the form of an Enterprise
Archive (EAR) file.
Deployer The Deployer is responsible for deploying application clients, web
applications, and EJB components into a specific operational
environment.
The Deployers primary tasks are installation into a specific server,
configuration, and application execution startup.

Introduction to the JavaTM Platform, Enterprise Edition 6 B-15


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examine the EJB Application Creation Process

Table 13-8 Java EE Platform Roles

Role Primary Function

System Administrator The System Administrator is responsible for the configuration and
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

administration of the enterprises computing and networking


infrastructure.
The System Administrator is also responsible for overseeing the
runtime well-being of the deployed Java EE applications.
Java EE Product Provider A Java EE Product Provider is the implementer and supplier of a Java
EE product that includes the component containers, Java EE platform
APIs, and other features defined in this specification.
s a
Tool Provider A Tool Provider provides tools used for the development and
) h a
m x
packaging of application components.

t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

B-16 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Comparing Java EE Application Development With Traditional Enterprise

Comparing Java EE Application Development With


Traditional Enterprise Application Development
A key feature of the Java EE platform is the strict separation of the application
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

components from the general services and infrastructure. One of the main
benefits of the Java EE platform for the application developer is that developers
can focus on the application business logic while leveraging the supporting
services and platform infrastructure provided by the container and application
server vendor. For example, in an online banking application, the application
component developers need to code the logic that underlies the transfer of funds
from one account to another, but they do not need to be concerned about
s a
managing database concurrency or data integrity in the event of a failure. The
) h a
m x application server infrastructure and services are responsible for these functions.

g b
odeveloper
a t
Figure 13-7 contrasts the tasks that are required of an application who
s
builds all aspects of an application and supporting services to those
@for G ideand
of a
developer who relies on an application component n a l
server u
service platform
e r n t
level functions.
t o b tude
Build From the Ground Up
r n es is Developers
S Checklist
(
z usee t h
n d e Business services

n a t o Persistence

H er ense Transaction management

r n al e lic Multi-threading

B e abl Security management

to sfer
Networking

n e s n Service publishing
Er n-tra
TM

rlo s no
C a Use Application Component Server Developers Checklist
Business services

Services Provided
by Server
Persistence
Transaction management
Multi-threading
TM
Security management
Networking
Service publishing

Figure 13-7 Advantages of Using Server-Provided Services

Introduction to the JavaTM Platform, Enterprise Edition 6 B-17


Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Comparing Java EE Application Development With Traditional Enterprise Application

As you can see, relying on a component server for application support services
dramatically reduces the amount of coding required of the application component
developer.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates

s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo

B-18 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A

You might also like