Вы находитесь на странице: 1из 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