D65187GC11 SG
D65187GC11 SG
D65187GC11 SG
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.
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
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
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
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
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
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
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?
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
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
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
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
( 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.
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.
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
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
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
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
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/.
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
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
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
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.
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 }
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;
//...
}
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
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;
Persistent Properties
@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
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
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
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
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
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
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
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.
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-4
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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
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.
(/ ) 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
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.
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">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>trader.Stock</class>
<class>trader.Customer</class>
<class>trader.CustomerShare</class>
<properties>
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.
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
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
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
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
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
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.
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
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
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.
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
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.
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
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
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.
Figure 2-9 illustrates the persistence entities used by the auction application.
Business Core
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
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
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
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.
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
Bid Table
s a
) h a
m x
t g ob
s a de Item Table
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
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
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.
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
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 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.
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.
11 </persistence-unit>
12
13 </persistence>
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
Note The persistent fields and properties of an entity class are generically
referred to as the attributes of the class.
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.
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
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
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
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.
13 }
The @Column annotation has many elements that can be used to further refine the
attribute mapping to the underlying 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
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.
Value Description
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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.
Value Description
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
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)
@Id Annotation
The @Id annotation specifies the primary key property or field of an entity.
arlo
GenerationType.TABLE are specified, the generator element should be used
C to identify the corresponding sequence or table name.
Value Description
Value Description
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
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
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
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
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.
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
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
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.
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).
are targeted for validation upon the pre-remove event (overrides the default
behavior).
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>
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.
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.
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 If you name the object / relational mapping XML file something other
than orm.xml, you must include the mapping-file element in
persistence.xml.
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
Note A list of all named managed persistence classes must be specified in Java
SE environments. This is required for portability.
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
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.
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
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.
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 }
7 }
8 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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.
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
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
l e li
rna is ba corresponding
Managed
B eThere database row and data in the row is kept synchronized
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.
Table 4-6 shows the entity manager methods or events required to change an
entitys life cycle 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.
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
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
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:
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.
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.
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) {
n a l@ Gui 15 }
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
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);
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
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.
t g ob 14 return item;
s a de 15 }
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
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) {
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
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
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
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
Figure 5-1 Partial View of Relationships Within the Auction Systems Data
Model
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
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
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.
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
Cardinality Direction
7 Many-to-many Unidirectional
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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
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
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
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
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
<<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;
//. . .
}
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
<<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.
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.
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.
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;
//. . .
}
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.
Use the name attribute on the OrderColumn annotation to specify the name of
the order column.
Code 5-11 Using The OrderColumn Annotation With The Name Attribute
@Entity
public class Contact {
@Id
private int id;
Modeling Entity Relationships 5-18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Implementing One-to-Many/Many-to-One Bidirectional Association
@OneToMany(mappedBy=contact)
@OrderColumn(name=CallOrder)
private List <PhoneNumber> preferredPhoneNumbers;
//. . .
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Note You cannot use both the OrderBy and OrderColumn annotations on the
same attribute.
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
entity that is orphaned by that operation will also be removed. For example, in the
following code all related PhoneNumber entities will be deleted when the
Contact entity is deleted.
For example, suppose that you decided to store PhoneNumber entities related to
a Contact entity in a Map. A descriptive string such as Home, Work, or
Mobile can be used at the map key. The PhoneNumber entity is stored as the
map value.
} e s to Stu
( e rn this
The MapKeyColumn d e z uspecifies
annotation s e the name of the column that stores the
map key in the n
r an e totable.
PHONENUMBER
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
<<entity>> <<entity>>
Worker Project
* *
id : int pId : int
projects : Set<Project> workers : Set<Workers>
... ...
s a
) h a
Figure 5-16 m x
ob
Many-to-Many Bidirectional Association
t g
aa many-to-many
@ Gu
The following steps outline a process you can follow to ldefine s i d e
bidirectional association between two entity classes.rna
b e dent
1. Define the two entity classes.
e s to Stu
(
2. Identify the entity that is the e rn ofththeisrelationship.
owner
d e z a relationship
u s e property or field to represent the
3. In the owning entity,
n n hastwith
create
aentity o the other entity.
relationship rthis
e ens e
4. In the l H
a e lientity,
owning c annotate the relationship field or property with the
r n
eManyToMany l
o B r a b annotations.
n e st 5. nsInfethe inverse entity, annotate the relationship field or property with the
s Er n-tra ManyToMany annotation. Set the value of the mappedBy attribute of the
C arlo no ManyToMany annotation to the value of the relationship field or property in
the owning entity.
//. . .
}
<<entity>> <<entity>>
s a
Worker Project
) h a
* m x*
id : int pId : int go
b
projects : Set<Project> workers s t
: aSet<Workers>
e
... ... l@
a t Gu i d
r n
e den
o b
n e st S tu
WORKER Table
z (er e this PROJECT Table
ID ...
an
de to us PID ...
r n
e ens e
l H
a e lic
r n
e abl
B
to sfer
n e s n WORKER_PROJECT Join Table
r
E n-t r a
l o s no
C ar WORKERS_ID PROJECTS_PID
r n an e to
define their primary key.
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
In addition to association annotations, you can also specify the fetch mode for the
Basic and LOB annotation. Table 5-2 contains the default values for annotations.
Annotation Default
Basic EAGER
Annotation Default
OneToOne EAGER
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
ManyToOne EAGER
OneToMany LAZY
ManyToMany LAZY
ElementCollection LAZY
s a
The Lob annotation does not have a fetch mode attribute. To override the default,
) h a
follow the LOB annotation with a Basic annotation. For example:
m x
@Lob @Basic(fetch=LAZY)
t g ob
private Image photo; s a de
n a l@ Gui
The default fetch mode for the Basic annotation
b eisr EAGER.
e n t
e s to Stud
( e rn this
Cascade Mode Attribute e z use
d
an e to
r n
e mode s you can also specify cascade mode settings for
In addition to fetch
l H c e nsettings,
r n a e li
all association mapping annotations. For example:
B ab l
e@OneToOne(cascade=PERSIST)
t o f e r
r n es ransprivate Customer customer;
s E n-t
ar l o no
C
Cascade mode settings can cause specific entity instance life-cycle events to
cascade across relationships. Cascade mode settings are used when the
EntityManager API is invoked. The default is for no cascading to occur.
Table 5-3 contains the possible values for the cascade attribute.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Value Comment
b e den
REFRESH Causes the refresh o
st operation tuto cascade to the target entity
r n e is S
( e
of the association
z is invoked
when
t h the entity managers refresh
e on the source entity.
e
operation
d u s
ALL r n anCausese alltothe entity state change operations (persist,
l H e emerge,
c ns remove, refresh, and detach) to cascade to the
e rna ble li target entity of the association.
t o B DETACH
e ra
e s s f Causes the detach operation to cascade to the target entities
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
s a
Objectives ) h a
m x
Upon completion of this module, you should be able to: atg
ob
s d e
Examine entity inheritance al@ t Gu i
r n
ehierarchy n
Examining object/relational inheritance
t o b u d emapping strategies
Inherit from an entity classrne
s S t
e
(superclass t h i s
Inherit using a mappede z
d to u s e
n a nnon-entity
r nse class
Inherit from
e a
n a l H inheritance
Examine l i c e mapping strategies
r leembeddable class
Be Use a b
e s to sfer an
E rn -tran
arlos non
C
6-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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
t g ob 9
// Direct child of hierarchy root
s a de 10
@Entity public class CarInsurance extends InsurancePolicy
n a l@ G{ui 11
protected int vin; er dnumber
// vehicle identification
b e nt 12
protected boolean comprehensive;
e s to Stu 13
}
//
( e rn this 14
15
d e z use 16
// Another direct child n
r of anhierarchy
e to root 17
@Entity public class H e ens
HouseInsurance extends InsurancePolicy { 18
a l l i c
ern aaddress;
protected String dwellingType; 19
protectedBString b le 20
s
protected
e s f er flood;
to boolean 21
E r//n -tran 22
arlos } non 23
C
Code 6-1 Entity Class Hierarchy
To map the inheritance hierarchy to a relational database, you must use one of the
following strategies.
Single-table-per-class hierarchy strategy
Joined-subclass strategy
Table-per-class strategy
The object relational mapping strategy for entity inheritance is specified using the
strategy attribute of the Inheritance annotation or the inheritance
element in the deployment descriptor.
Figure 6-1 n a nd to u
Single-Table-Per-Hierarchy Example
e r nse
n a l H lice
B er Thisa b le strategy provides good support for polymorphic relationships
mapping
s t o sfer between entities and for queries that range over the class hierarchy.
Note The single-table-per-class strategy is the default strategy. If you use this
strategy, you do not need to annotate the root class with the Inheritance
annotation.
a n
Figure 6-2 e rn nTables
Example: se for Joined-Subclass Mapping Strategy
H
al e lic e
r n l a joined-subclass object/relational mapping strategy is this
ebenefitaofbusing
B
The
tostrategy r
eprovides
e s n s f support for polymorphic relationships between entities. Another
n a
Er n-tradvantage is the database schema is normalized.
rlo s no The drawback of using a joined-subclass object/relational mapping strategy it that
C a
it requires that one or more join operations be performed to instantiate instances
of a subclass. In deep class hierarchies, this can lead to unacceptable
performance. Queries that range over the class hierarchy likewise require joins.
t
a de g
POLICYID CLIENT PREMIUM
s
n a l@ Gui
b er dent
e s to Stu
CAR_INSURANCE
( e rn this
e z usPREMIUM
POLICYID CLIENT
d e VIN COMPREHENSIVE
r n an e to
H e ens
n l
a e lic
r
e abl HOUSE_INSURANCE
B
to sfer
n e s n
POLICYID CLIENT PREMIUM ADDRESS FLOOD
s Er n-tra
C arlo no Figure 6-3 Table-Per_Class Example
Note The Java Persistence API does not require persistence providers to
support the table-per-class mapping strategy.
The following steps outline a process you can follow to create an inheritance
hierarchy of entity classes.
1. Declare the root entity class of the inheritance hierarchy.
The root class can be an abstract entity class.
2. Choose the object/relational strategy you plan to use for the inheritance
s a
hierarchy you are about to create.
) h a
3. m x
Use the strategy attribute of the Inheritance annotation to specify
g ob
your selected object/relational mapping strategy on the root entity class.
t
a de
Some persistence providers might allow you to overridesthe strategy
a
specified in the root entity by permitting you tonspecify ui
l@ anGoverriding
strategy in the child class. b er dent
e s tothe hierarchy.
S tu
n
thiskeyword to extend the parent
4. Declare the remaining entity classes of
z
Each child entity classeuses
(ether extends
e
entity class. and t o us
e rn nse
H iceClass Example
Code 6-2al Root Entity
r n l e l
e
B erab
1 o
@Entity t@Table(name="EMP")
s nsf
2 n e
@Inheritance(strategy=InheritanceType.JOINED)
3
s public tra class Employee {
Er nabstract
-
C arl4o no
@Id
5 protected Integer empId;
6 @Version
7 protected Integer version;
8 @ManyToOne
9 protected Address address;
10 // ...
11 }
12 return salary;
13 }
14 // ...
15 }
C a protected
7 // ...
hourlyWage;
8 }
15 }
2 @Entity
3 public class FTEmployee extends Employee {
4 // Inherited empId field mapped to FTEMPLOYEE.EMPID
5 // Inherited version field mapped to FTEMPLOYEE.VERSION
6 // Inherited address field mapped to FTEMPLOYEE.ADDR fk
7 protected Integer salary; // Defaults to FTEMPLOYEE.SALARY
8
9 public FTEmployee() {}
s a
10 public Integer getSalary() { ... }
) h a
m x 11 public void setSalary(Integer salary) { ... }
}
t g ob 12
s a de
Code 6-7 Second Example of an Entity Extending
a l@ i
a MappeduSuperclass
n
er dent G
1 @Entity b
to Stu
2 @Table(name="PT_EMP") e s
3 @AssociationOverride(name="address", ( e rn this
4 e z use
joinColumns=@JoinColumn(name="ADDR_ID"))
d
5 public class PartTimeEmployee
r n an e extends
to Employee {
6 // Inherited empId e
H icfield
field s
en mapped to PT_EMP.VERSION
mapped to PT_EMP.EMPID
// Inheritedalversion l
ernfield
7
8 // addressB a b lemapping overridden to PT_EMP.ADDR_ID fk
9
e s to sfer
@Column(name="WAGE")
10 rn protected
E - t r an Float hourlyWage;
rlos12 nopublic
n
11
C a PartTimeEmployee() {}
13 public Float getHourlyWage() { ... }
14 public void setHourlyWage(Float wage) { ... }
15 }
6 super();
7 }
8 //...
9
10 @Id
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
t o B erFor
a example, a Person class could have an embedded Address class
s s f
E rne -tran which contains an embedded PhoneNumber class.
s non
C arlo Defining Entity Classes by Using an Embeddable Class
The rules for defining an embeddable class are the same as those used for defining
an entity class with one important exception: embeddable classes do not support
inheritance. Annotate the embeddable class with the Embeddable annotation
instead of the Entity annotation.
10 }
r n anmoreeinformation
embeddable classes. For to on collections, see Persisting Enums
e ens
and Collections.
H
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
t g ob
Persist entities that contain enums with @Enumerated
s a de
a l@ Gui
Persist entities that contain lists with @ElementCollection
n
Persist entities that contain maps with b er dent
@ElementCollection
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C
7-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
Introduction
Up to this point, the focus has been on persisting entities and describing
relationships between entities. For example, recall the one-to-many relationship
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
<<entity>> 1 * <<entity>>
Auction Bid
s a
) h a
m x
1 1 <<entity>>
t g ob
Item
s a de
n a l@ Gui
b r entRelationships
eAssociation
Figure 7-1
to Stud
Object Model Showing Object
e s
( e rn tAssociation
Code 7-1 Bidirectional One-to-Many his Example
e z s e
@Entity
n a nd to u
public class Auction { er
H e n se
@Id
r n al e lic
private int e
B b
auctionId;
a l
s to sfer
@OneToMany(mappedBy=auction)
e
E r an
rn -tCollection
private <Bid> bids;
s..// n
C arlo } no
Code 7-2 Bidirectional Many-to-One Association Example
@Entity
public class Bid {
@Id
private int bidId;
@ManyToOne
private Auction auction;
..//
}
This module explores persisting entities that have fields that contain non-entity
values such as enums and collections of primitives and simple Strings.
The Auction domain object represents a single online auction within the auction
application. The Auction domain object contains the following attributes:
auctionID attribute A unique identity for the Auction object.
startAmount attribute The start amount specified by the seller.
increment attribute The minimum bid increment.
s a
status attribute The auction status. Status values are OPEN, CLOSED,
) h a
m x CANCELLED.
openTime attribute The start time of the auction. t g ob
s a de
l@ Gui
closeTime attribute The close time of the auction.
n a
b er dent
e s to Stu
( e rn thsupport
is for enumerated types via the
enum keyword. Prior tonthat,
z
Java Standard Edition 5 introduced
e
language
de thetostandard
us way to represent an enumerated type
was the int enumrn a e example, the following code represents the status
pattern. For
e n s
H ice enum pattern.
a l
of an Auction using the int
e rn ble l
t o B 7-3eraint Enum Pattern (Used Prior to Java SE 5)
Code
n e s nsf
Erclass
public
s n - ra
tAuction{
arlo public
no static final int STATUS_OPEN = 0;
C public static final int STATUS_CLOSED = 1;
public static final int STATUS_CANCELLED = 2;
//...
}
in this case, STATUS_, to avoid collisions with other int enum types.
Brittleness - Because int enums are compile-time constants, they are
compiled into clients that use them. If a new constant is added between two
existing constants or the order is changed, clients must be recompiled. If the
clients are not recompiled, they will still run, but their behavior will be
undefined.
Printed values are uninformative - If you print one of the constant values, s a
all you get is a number, which tells you nothing about what the value ) h a
m x
ob
represents or even what type it is.
t
a de g
s
n a l@ Gui
Declaring a new enum type for Status solves these shortcomings.
b r values
Typesafe - The status field now acceptseonly
e n tof the Status type.
tud Status.OPEN,
to namespaced:
e s
Namespace - All enums are implicitly
S
e rn this
Status.CLOSED, Status.CANCELLED.
(
Non-Brittle - Enumd e zvaluesuhave
s e an internal ordinal value but because you
n n by value
aenum to name, reordering the definition of enum values
r
refer to the
e enOPEN, e
s CLOSED) has no effect on compiled code.
l H
(CANCELLED,
c
a evalues
rn Printedl li are informative - Printing the value of an enum displays
e
B ethe b text, not the ordinal value.
aenum
t o f r
r n es rans
s E n-t Code 7-4 Declaring an Enum (Used Starting With Java SE 5)
ar l o no
C public enum Status{
OPEN, CLOSED, CANCELLED
}
@Entity
public class Auction{
//...
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Note Only a class can be an Entity. Enums and interfaces may not be annotated
with the @Entity annotation.
By default, the Java Persistence API will map the Status enum to an integer
column. The column value is result of the ordinal() call on the enum.
Persisting the ordinal instead of the enum value can introduce brittleness back
s a
into the code if the order of the enum values change. To avoid this problem, use
) h a
m x the @Enumerated annotation on the Status field.
t g ob
The @Enumerated annotation accepts a value of EnumTypesenum. a Code d e 7-5
demonstrates the use of the @Enumerated annotation. l@
a t Gu i
r n
e den
Table 7-1 Acceptable Values for the @Enumerated Annotationo b
n e st S tu
Value Default
z (er e this Description
e us
EnumType.ORDINAL yes and t o Persist enumerated type
r
e ensn e property or field as an integer
l H c
EnumType.STRING rna l e li Persist enumerated type
B e b
s t o sfera property or field as a string
E rne -tran
rlos non
Code 7-5 Using the @Enumerated Annotation to Persist the Status enum as
C a a String
public enum Status{
OPEN, CLOSED, CANCELLED
}
@Entity
public class Auction{
@Enumerated(EnumType.STRING)
private Status status;
this.status = status;
}
//...
}
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
Figure 7-2 s a de
Item Domain Object
n a l@ Gui
b er fordesale
ntin an auction. The
The Item domain object represents the article
e s toattributes:
offered
S tu
r n
Item domain object contains the following
histhe item.
itemID attribute Ae z (eidentity
e tfor
a n
d to us
unique
description
e rn nse The items description.
attribute
a
image
n lHattributeiceThe location of an image of the item.
l
e r l e
t o B ethat
Suppose f r abafter the customer sees the initial design, you are tasked with
r n es rmodifying
a n s Item so that it can store a list of keywords. Since the keywords are
s E n-t simple strings, do not add unnecessary complexity to the application by creating
ar l o no a Keyword entity.
C
If you annotate the list with the @ElementCollection annotation, the Java
Persistence API will create a separate collection table to store the values of the
list.
Note You may also use the @ElementCollection annotation with a set,
collection, or map. An @ElementCollection can also contain embeddables.
The collection table name is the name of the entity concatenated with the
name of the field separated with an underscore.
In this case, a new table will be created named ITEM_KEYWORDS.
Code 7-6 Item Entity With a List of Keywords Annotated With the
@ElementCollection Annotation
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
@Entity
public class Item{
@Id
private int itemId;
private String description;
s a
private String image;
) h a
@ElementCollection
m x
private List<String> keywords;
t g ob
s a de
//...
n a l@ Gui
}
b er dent
e s to Stu
( e rn this
d e z use
Overriding theaDefault
n n to
Collection Table Name
r
e ens e
l H
a the ic collection table name, use the @CollectionTable
To override
r n l e ldefault
B eannotation
a bwith the name attribute.
o
st nThe fe r
r n e s
a @CollectionTable annotation has many elements that can be used to
E
s non - t r
arlo
further refine the mapping to the default collection table.
C Table 7-2 Elements of the @Column Annotation
Code 7-7 Overriding the Default Collection Table Name With the
@CollectionTable Annotation.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
@Entity
public class Item{
@Id
private int itemId;
private String description;
private String image;
s a
@ElementCollection
) h a
@CollectionTable(name = TAGS)
m x
private List<String> keywords;
t g ob
s a de
//...
n a l@ Gui
}
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
t g ob annotation.
s a de
Only use the Map type on one side of a bidirectional relationship.
n a l@ Gui
If the Map key is the primary key, or a persistent
b er fielde t
ornproperty of the entity
e s to Stud
that is the Map value, use the javax.persistence.MapKey annotation. The
@MapKeyClass and @MapKey annotations
e r n his cannot be used on the same field or
property. z ( e t
e
nd to u s
If Map value isrn aa s e
Java programming language basic type or an embeddable class,
e n
lH
it will be
a mappedcasea collection table in the underlying database. If generic types
i
earer n
not l
used, ethel @ElementCollection annotation's targetClass attribute
t o B musteberasetb to the type of the Map value.
n e s nsf
s Er n-tra If the entity is part of a one-to-many/many-to-one bidirectional relationship, it
arlo no will be mapped in the table of the entity that represents the value of the Map. If
C generic types are not used, the targetEntity attribute of the @OneToMany and
@ManyToMany annotations must be set to the type of the Map value.
Suppose that the customer would like to have the ability to store an arbitrary
number of additional key/value pairs of information about the Item in a Map
field named miscInfo. These values are not consistently used from Item to
Item, so an enum or formal entity cannot be used.
The following lists some possible values that might be stored for an Item:
Warranty : yes
Manufacturer : Acme
Condition : Slightly used
If you annotate the map with the @ElementCollection annotation, the Java
Persistence API will create separate collection table to store the values of the
map.
The collection table name is the name of the entity concatenated with the
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Code 7-9 Overriding the Default Collection Table Name With the
@CollectionTable Annotation
@Entity
public class Item{
@Id
private int itemId;
private String description;
private String image;
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
@ElementCollection
@CollectionTable( name = additional_info)
private Map<String, String> miscInfo;
//...
}
s a
) h a
m x
Overriding the Map Key Column Name
t g ob
s a de
n a l@ Guiannotation with
To override the Map key column name, use the @MapKeyColumn
the name attribute.
b er dent
Code 7-10 Overriding the Map n e to SName
sColumn tu With the @MapKeyColumn
(er e this
Key
Annotation
z
de to us
a n
@Entity e rn nse
public class Item{al H l i c e
n
er able
@Id to
B er
e s s f
n itemId;
E n traint
rprivate
o s non -
private String description;
r l
Ca private String image;
@ElementCollection
@CollectionTable( name = additional_info)
@MapKeyColumn( name = name)
private Map<String, String> miscInfo;
//...
}
To override the Map value column name, use the @Column annotation with the
name attribute.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Code 7-11 Overriding the Map Value Column Name With the @Column
Annotation
@Entity
public class Item{
@Id s a
private int itemId;
) h a
private String description; m x
private String image;
t g ob
@ElementCollection s a de
n a l@ Gui
@CollectionTable( name = additional_info)
@MapKeyColumn( name = name)
b er dent
@Column( name = value)
e s to Stu
( e rn this
private Map<String, String> miscInfo;
//... d e z use
} r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
Introduction to Querying
Objectives a
h a s
x )
Upon completion of this module, you should be able to: m
t g ob
Find an Entity by its primary key
s a de
Understand basic Java Persistence API querya
n language ui
l@ Gqueries
Understand native SQL queries b er dent
e s to Stu
( e rn this
Understand basic Criteria API queries
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
8-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
instance.
query string or a native SQL query string. This section provides a brief
introduction to query objects.
Dynamic Queries
A dynamic query is an ad hoc query that is created at the point and then executed.
s a
Dynamic queries are not as performant as static queries if they are called
) h a
m x
repeatedly, therefore, they should only be used in situations where the query is
ob
not known at the time you are writing the code.
t g
a in JDBC.
A dynamic query is analogous to a java.sql.Statement s i d e
r n al@ t Gu
A dynamic query object is created by callingb ethe createQuery()
d e n method of an
t o t u
r n es is S
entity manager instance. For example:
z (e e th
Query query = entityManager.createQuery(queryString);
a n
de to us
e rn nse
Named Queries
n a l H lice
B er able
e s f er query is declared on an entity using the @NamedQuery annotation. A
to Asnamed
E rn -trannamed query is precompiled, and therefore is appropriate for queries that will be
Query Execution
The getResultList() method executes the equivalent of a SQL select query
and returns the result as a list object. To return a single object, use the
getSingleResult() method. For update or delete queries, use the
executeUpdate() method. For example:
// Returns a List of Items
The Query interface offers two methods to facilitate paging through multiple
pages of results. The setMaxResults() method sets the maximum number of
results to retrieve. The setFirstResult() method sets the position of the first
result to retrieve. For example, to return the third page of results with 10 results s a
to a page: ) h a
m x
int resultsPerPage = 10;
t g ob
query.setFirstResult(3 * resultsPerPage);
s a de
query.setMaxResults(resultsPerPage);
n a l@ Gui
List page3 = query.getResultList();
b er dent
e s to Stu
Note Java Persistence API version( e rn2.0 introduces
this the
javax.persistence.TypedQueryd e z u e
sinterface. The TypedQuery interface
n n
a For
enables the use of generics. o
tmore information on the TypedQuery interface,
e r n s e
a l HCriteria
see Using the
i c eAPI.
l
B ern able
e s to sfer
E rn -tran
s non
C arlo
Value Description
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
LockModeType.NONE No locking
LockModeType.OPTIMISTIC Causes the persistence provider
to verify that the entity data has
not been changed by another
transaction since it was read
from the database.
s a
LockModeType.OPTIMISTIC_FORCE_INCREMENT Equivalent to OPTIMISTIC, and
) h a
m x additionally increments the
t g ob version attribute.
LockModeType.READ The same as s a de
n a l@ Gui
LockModeType.OPTIMISTIC
b e r ent
LockModeType.WRITE toThe t asd
same u
e s S
( e rn tFORCE_INCREMENT
his
LockModeType.OPTIMISTIC_
e z e
us Causes the persistence provider
LockModeType.PESSIMISTIC_READand t o
e rn nse to lock the underlying database
l H
a e li c e records for duration of a
r
e abn l transation.
B
to sfer
e s n
LockModeType.PESSIMISTIC_WRITE
n Causes the persistence provider
r
E n-t r a to lock the underlying database
s
C arlo no records when they are read until
the write transaction completes.
LockModeType.PESSIMISTIC_FORCE_INCREMENT Equivalent to
PESSIMISTIC_READ or
PESSIMISTIC_WRITE and
additionally increments the
version attribute.
query.setLockMode(LockModeType.OPTIMISTIC);
Setting Hints s a
) h a
m x
The setHint() method sets a standard query property, a standard b hint, or
goquery
an implementation-specific hint. It accepts two arguments: a thethint
name and the
s
ignored. id
value. If the hint name is not recognized, it is silentlyl@ e
n a G u
b r
e properties:
e n t
o d
n e st
The Java Persistence API defines the following
S tu
(er e this
javax.persistence.cache.retrieveMode
z
a n
de to us
javax.persistence.cache.storeMode
e rn nse
n a l H limust
These properties
c e be observed by the persistence provider.
B eTher JavaabPersistence
le
s t o sfer API defines the following hint:
eclipselink.refresh
eclipselink.refresh.cascade
eclipselink.batch
eclipselink.join-fetch
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
eclipselink.read-only
eclipselink.jdbc.timeout
eclipselink.jdbc.fetch-size
eclipselink.jdbc.max-rows
eclipselink.result-collection-type
s a
) h a
m x Code 8-4 Setting an EclipseLink-Specific Hint on a Query Object
import org.eclipse.persistence.config.HintValues; t g ob
s a de
import org.eclipse.persistence.config.QueryHints;
n a l@ Gui
er dent
query.setHint(QueryHints.READ_ONLY, HintValues.TRUE);
b
to Stu
e s
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C
The following steps outline the process required to use Java Persistence API
query language statements and query objects. In particular, note the requirement
to wrap Java Persistence API query language statement strings using query
objects of type javax.persistence.Query, shown in Step 2. s a
) h a
m x 1. Create Java Persistence API query language statement string.
String queryString = SELECT o FROM Order o +
t g ob
WHERE o.shippingAddress.state = CA;
s a de
This select statement returns Order objects
n a G ui address in
@ a shipping
lwith
the state of California.
b er dent
2. Create a query object wrapperefor s tothe JavaStPersistence
u API query language
e r n h i s
z ( e t
string, of type javax.persistence.Query interface.
// Assume entityManager references e
nd tan s
uEntityManager object
n a
r nse o
Query query = entityManager.createQuery(queryString); // create Query
e
3. a
n l H thelicquery
Execute e object.
List orders B=e
r b le
t o f e r a
query.getResultList(); // execute Query
r n es rans
s E n-t
ar l o no
C
The SQL query facility enables you to use the native SQL of the target database
when the Java Persistence API query language cannot be used. Native SQL
queries are not expected to be portable across databases.
The following steps outline the process required to use SQL statements and query
objects. In particular, note the requirement to wrap SQL statement strings using s a
query objects of type javax.persistence.Query, shown in Step 2. ) h a
m x
1. Create SQL statement string.
t g ob
String queryString = SELECT * FROM ORDER WHERE STATE = CA; s a de
This select statement returns Order objects n a
withl@ G
a shippinguiaddress in
the state of California. b er dent
e s toSQL string,
S tu of type
2. Create a query object wrapper for n the
is that you must pass in the
javax.persistence.Query
z (erinterface.
e thNotice
a n
de to us
class type for the results.
// Assume entityManager references e rn nsean EntityManager object
a l H lice
Query query = entityManager.createNativeQuery(queryString,
n
Order.class);
r
eExecute b lequery object.
B
3.
er a the
t=o query.getResultList();
List orderse s n s f // execute Query
r n
E n-t r a
r l o s no Note When an entity is being returned, the SQL statement should select all of
C a
the columns that are mapped to the entity object, including foreign key columns
to related entities. The results obtained when insufficient data is available are
undefined.
approach of the Java Persistence query language. However, strings can be used to
specify joins and path navigation in the Criteria API.
The syntax of the Criteria API is designed to allow the construction of an object-
based query graph, whose nodes correspond to the semantic query elements.
Java Persistence criteria queries are based on a metamodel of the managed classes
of the persistence unit. This metamodel can be accessed dynamically. In s a
addition, static metamodel classes that capture the state of this metamodel can be ) h a
m x generated at development time.
t g ob
The Java Persistence API specification defines a canonical s arepresentation
d e of the
l@ Gu
metamodel in terms of static metamodel classes asafollows.
i
r n
e dent
b
to unit,Satcorresponding
u
n e s
For every managed class in the persistence metamodel class
is produced as follows:
z (er e this
For each managed
a n
declasstoX uinspackage p, a metamodel class X_ in package
rn nse
p is created.
e
n a l Hnameloficthe
The e metamodel class is derived from the name of the managed
B er classa b leappending "_" to the name of the managed class.
by
s to sfeTher metamodel class X must be annotated with the
e
rn -tran javax.persistence.StaticMetamodel annotation.
E
arlos non If class X extends another class S, then class X_ must extend S_.
C
For every persistent attribute Y of class X, the metamodel class must
contain a declaration like public static volatile
SingularAttribute<X,Y> y.
For every persistent collection attribute of class X, the metamodel class must
contain declarations like public static volatile
CollectionAttribute, SetAttribute, ListAttribute, or
MapAttribute.
Note The software developer typically creates the static metamodel using the
tools provided by the persistence provider.
The following steps outline the process required to use Criteria API objects and
query objects. In particular, note the requirement to wrap criteria objects using
query objects of type javax.persistence.TypedQuery, shown in Step 2.
1. Create the criteria object.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> criteria = cb.createQuery(Person.class);
Root<Person> person= criteria.from(Person.class);
Predicate condition = cb.gt(person.get(Person_.age), 40);
criteria.where(condition);
This criteria object returns Person objects with an age greater than 40.
2. Create a TypedQuery object wrapper for the criteria object, of type
s a
javax.persistence.TypedQuery interface.
) h a
// Assume entityManager references an EntityManager object m x
TypedQuery<Person> query = entityManager.createQuery(criteria);
t g ob
s a de
3. Execute the query object.
n a l@ Gui
List<Person> orders = query.getResultList();
b er dent
e s to Stu
Note The Criteria API enables(youe rnto avoid is use of strings, enabling the use
ththe
of strongly typed criteria d
z
e instead.
objects e
us Typos can accidentally occur in a Java
a n
n sstring. t o
Persistence query rlanguage
e n e However, the Criteria API allows the use of
a l H ice
strings as well. For more information, see Chapter 6, Criteria API of the Java
l
ern aAPI,
Persistence
B b leVersion 2.0 specification.
e s to sfer
E rn -tran
s non
C arlo
For example, the following example defines a query with a named parameter:
Query query = entityManager.createQuery
(select o from Order o where customer.id = :id);
s a
You use the named format of the setParameter() method to set the parameter
) h a
m x
value for the query, as shown in the following code snippet:
int id = 24;
t g ob
query.setParameter(id, id) s a de
List orders = query.getResultList();
n a l@ Gui
b er dent
e s to Stu
Note Named parameters cannot bern is
used in conjunction with native SQL
queries. ( e
z use t h
d e
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
For example, the following example defines a query with a positional parameter:
Query query = entityManager.createQuery
(select o from Order o where customer.id = ?1);
You use the positional format of the setParameter method to set the parameter
value for the query, as shown in the following code snippet:
s a
int id = 24; ) h a
query.setParameter(1, id) m x
List orders = query.getResultList();
t g ob
s a de
n a l@ Gui
r enaccess
Note Only positional parameter binding andepositional
b t to result items
to Stud
may be portably used for native queries.
e s
( e rn this
Positional parametersd e
are znot supported
u s e by the Criteria API.
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
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
Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
Examine the Java Persistence API query language atg
ob
s d e
Create and use the SELECT statement al@ t Gu i
r n
Create and use the UPDATE statementbe e n
st o tu d
Create and use the DELETEn e S
(er e this
statement
z
de to us
a n
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C
9-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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
Note For easy identification, all Java Persistence API query language keywords
s a
used in this module are capitalized. However, Java Persistence API query
) h a
language keywords are not case sensitive.
m x
t g ob
s astatement
d e types.
Java Persistence API query language supports the following
al@ t Gu i
SELECT statement r n
e den
t o b
The Java Persistence API querye slanguage S tu statement returns row
SELECT
n
eras entity
data stored in the database is It can also be used to return
hobjects.
z ( e t
scalar data.
a n
de to us
e n se
UPDATErstatement
a l
The l i c en API query language UPDATE statement updates one or
HJava Persistence
B ern more
a b le instances. Behind the scenes, the updates to the entity instances
entity
s to sfeare r reflected in updates to rows of a specific table in the database.
e
rn -tran DELETE statement
E
s non
C arlo The Java Persistence API query language DELETE statement deletes one or
more entity instances. Behind the scenes, the deletion of entity instances are
reflected in the deletion of one or more rows from a specific table in the
database.
Java Persistence API query language statements consist of Java Persistence API
query language keywords, entity class names, and entity field identifiers.
SELECT o FROM Order AS o
SELECT c.id, c.status FROM Customer c
JOIN c.orders o WHERE o.quantity > 100
query capabilities.
Inner joins, also known as relationship joins
An inner join returns all records that meet the join condition.
Left outer joins
A left outer join returns all records that meet the join condition as well
as those that have no matching values.
s a
Fetch joins
) h a
m x
t ob
Fetch joins are variations of the inner and outer joins. A fetch join
g
enables the prefetching of related data items as a side effect of a query.
s a de
The syntax for the inner join operation is:
n a l@ Gui
[INNER]JOIN join_association_path_expression [AS]be r ent
identification_variable
d
toover Stheturelationship
For example, the following queryejoins
n s between
customers and orders. This(type r i s
e ofejointhtypically equates to a join over a
foreign key relationship
d e zin the s
database.
u
a n
t o
SELECT c FROM Customer c JOIN
e rn c.orders
n s e o WHERE c.status = 1
l H lINNER
Theakeyword
n i c e is optional. For example:
B er acbINNER
SELECT c FROM Customer le JOIN c.orders o WHERE c.status = 1
e s to sThe f erfollowing equivalent but less clear form of query omits the JOIN
E rn -tran keyword but keeps the IN keyword. The query selects those customers of
s non
C arlo status 1 for which at least one order exists.
SELECT OBJECT(c) FROM Customer c, IN(c.orders) o WHERE c.status = 1
The syntax for a left outer join is:
LEFT [OUTER]JOIN join_association_path_expression [AS]
identification_variable
For example:
SELECT c FROM Customer c LEFT JOIN c.orders o WHERE c.status = 1
The keyword OUTER is optional. For example:
SELECT c FROM Customer c LEFT OUTER JOIN c.orders o WHERE c.status = 1
The syntax for a fetch join is:
[LEFT [OUTER] |INNER]JOIN FETCH join_association_path_expression
For example, the following query results in the fetching of all employees in
the department that satisfies the join condition.
the query. You cannot specify an identification variable for the entities
referenced by the right side of the FETCH JOIN clause. Therefore,
references to the implicitly fetched entities cannot appear elsewhere in the
query.
Note Entities that are prefetched as a result of a fetch join are not part of the
explicit query result.
s a
) h a
m x
t g ob
Collection Member Path Expressions s a de
n a l@ Gui
A collection member path expression is e
b r expression
a path
e n t that evaluates to a
member of a collection. Collection t o
value u
path
t d
expressions are used when a
n s
e anisentity
path expression involves evaluating S field that returns a collection.
( e r
For example, in the following h
patht expression, the state field lineItems
d e z
evaluates to a collection of u s e instances. The variable l evaluates to
LineItem
a specificrn an e instance
LineItem to within that collection.
l HeOrder c e nsIN(o.lineItems) l WHERE
SELECT DISTINCT o aFROM
li o,
rn b=leofficeSupplies
e
l.product.productType
B era
t o
s nsf Note the declaration of the range variable o and the useof the keyword IN
n e
s Er n-tra in the declaration of the collection member variable.
e rn nse
n a l H licExpression
e
Table 9-1 WHERE Clause
B er able
Conditional Types
Note The LIKE operator operates on a string expression. The string expression
must have a string value. The pattern value is a string literal or a string-valued
input parameter in which an underscore (_) stands for any single character, a
percent (%) character stands for any sequence of characters including an empty
sequence, and all other characters stand for themselves.
s a
The syntax for a complex conditional expression is: ) h a
m x
Simple_Cond_Expr_1 Binary_Relational_Operator Simple_Cond_Expr_2
t g ob
s a de
The binary relational operator can be one of the following:
AND n a l@ Gui
b er dent
OR
e s to Stu
For example:
( e rn this
SELECT DISTINCT o1 FROM Order o1,
d e zOrderuso2
e WHERE o1.quantity >o2.quantity
r n an e to
AND o2.customer.lastname = Smith
H e ens
AND o2.customer.firstname= John
rna
l c
li the following types of literals in conditional expressions.
e You can
l euse
B erabString literals like Stephen
t o
s nsf
n e
s Er n-tra Numeric literals like 52 or 3.55
Java Persistence API query language defines several functions for use in
expressions in the WHERE clause. Functions are classified as either string
functions or arithmetic functions.
Using Subqueries
Subqueries can be used in the WHERE clause of a query. Subqueries are queries
whose results are used by the outer query. For example, the following query finds
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
SELECT b
FROM Bid b
WHERE b.amount = (SELECT MAX(bid.amount) from Bid bid)
You can use one of the following two conventions to specify query method s a
parameters: ) h a
m x
t g ob Positional specification of parameters
s a ofdthe
Positional specification is based on using the position e parameter
in the query method. For example, suppose al@yout have i
ua query method
with the following signature: r n
e den G
o b
public List findAuctionsWithBidsGreaterThan(Double
n e st S tuamount);
(er from
To reference parameters is Persistence API query language
thJava
queries, you z
dewould e
usthe ?1 syntax for the first parameter as shown
use
a n
t o
e rn nse
in the following query:
a H Auction
SELECT DISTINCT aucl FROM
i c e auc, IN(auc.bids) AS b
n l
B er able
WHERE b.amount > ?1
e s to sfer For methods with multiple parameters, you would use ?2 for the
E rn -tran second parameter and ?3 for the third parameter.
Note You cannot mix the use of the positional parameter convention with the
named parameter convention in the same Java Persistence API query language
query string.
operators, and functions, the SELECT clause can contain one or more of the
following elements:
A single identification variable that ranges over an entity abstract schema
type, for example:
SELECT o FROM Order o WHERE o.quantity > 500
An aggregate select expression, for example:
s a
SELECT AVG(o.quantity) FROM Order o
) h a
m x A constructor expression, for example:
SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count)
t g ob FROM
Customer c JOIN c.orders o WHERE o.count > 100 s a de
n a l@ Gui
The optional DISTINCT keyword is used to specify
b erthatdduplicate
e nt values must be
s
eliminated from the query result. For example:
e to Stu
SELECT DISTINCT l.product FROM Order AS ( e ro,n IN(o.lineItems)
this l
z
de to us e
a n
Examining the e rn nsBY
GROUP e and HAVING Clauses
H
al e lic e
r n
eGROUPaBYblconstruct enables the aggregation of values according to the
B
toproperties
The
erof an entity class. The HAVING construct enables conditions to be
e s s f
E an that further restrict the query result as restrictions upon the groups. The
rn -trspecified
arlos non GROUP BY and HAVING clauses are often used in combination. The following
C SELECT statements contain examples of the use of the GROUP BY and HAVING
clauses.
SELECT c.country, COUNT(c) FROM Customer c GROUP BY c.country HAVING
COUNT(c) > 3
This section provides more details about the GROUP BY and HAVING clauses.
If a query contains both a WHERE clause and a GROUP BY clause, the effect
is that of first applying the where clause, and then forming the groups and
filtering them according to the HAVING clause.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Any item that appears in the SELECT clause other than as an argument to an
aggregate function must also appear in the GROUP BY clause.
If no GROUP BY clause is included and the HAVING clause is used, the result
is treated as a single group, and the SELECT list can only consist of
aggregate functions. The use of HAVING in the absence of GROUP BY is not
required to be supported by an implementation of Java Persistence
specification.
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
For example:
UPDATE customer c SET c.status = outstanding WHERE c.balance < 10000
s a
You can update multiple fields, for example,
) h a
UPDATE Product p SET p.discount = '10', p.shippingAmount = '0'
m x
t g ob
s
UPDATE statements apply only to entity instances of a single aentitydclass
e type. For
example, you cannot create a single UPDATE statement i
al@thatt applies
u to both the
Customer and Order entity class types. r n
e den G
o b
n e st need toSupdate
tu multiple entity instances.
this programatically using the UPDATE
r instance
An UPDATE statement is used when you
z
While you can update a single (eentitye
n
deis nottorecommended.
statement, this practice
a us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
s non
C arlo
For example:
DELETE FROM Customer c WHERE c.status = inactive
s a
DELETE statements apply only to entities of a single entity class type. For
) h a
m x example, you cannot create a single DELETE statement that deletes rows from
ob
both the Customer and Order tables.
t g
aentity dinstances.
A DELETE statement is used when you need to delete multiple s i e
n al@ t G
While you can delete a single entity instance programmatically
r
u a DELETE
using
statement, this practice is not recommended. be e n
st o tu d
n e S
Caution Caution should be used
z ( ewhen e t his bulk update or delete
r executing
operations because they may
n
d e result inusinconsistencies between the database and
r n a e to context. In general, bulk update and delete
the entities in the active persistence
operations should
H s
e only ebenperformed within a transaction in a new persistence
l c
li or accessing entities whose state might be affected by
contextnorabefore fetching
e r l e
t o B erab
such operations.
n e s nsf
s Er n-tra
arlo no
C
Objectives a
h a s
x )
Upon completion of this module, you should be able to: m
t
Contrast queries that use the Criteria API with queriesathat
obthe Java
guse
s d e
Persistence query language
al@ t Gu i
r n
Describe the metamodel object approacheto querying n
o b d e
Create Criteria API queries est S tu
n
z (er e this
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
s non
C arlo
10-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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
language and SQL are mature and robust, they share a common problem: the Java
compiler cannot find syntax errors in string-based queries. For example, notice
the misspelled words in the following query:
1 String queryString = slect i from Itme i;
2 Query query = entityManager.createQuery(queryString);
3 List<Item> items = query.getResultList();
s a
The Criteria API was introduced in Java Persistence API version 2.0 to overcome
) h a
m x this problem. The Criteria API provides a strongly-typed way to create queries
t g ob using a CriteriaBuilder class. Since the queries are strongly typed, they can
s a de be validated by the Java compiler. For example, the following query uses the
statement.
Note The Criteria API does not support UPDATE or DELETE statements.
Table 10-1 Relating Java Persistence API Query Language Clauses to Criteria s a
) h a
m x API Interfaces
Java
t g ob
Persistence s a de
API Query Criteria API Interface
n a l@ Gui
Language
b er dent
Clause
e s to Stu
select ( e rn this
CriteriaQuery<T>,
d e z use
Selection<T>
r n an e to
from
H e ens
Root<T>
n l ic
a e lPredicate
r
where
e ab l
t o B r
eby
e s group
n s f Expression<T>
E rn -trahaving Predicate
r l o s n o n
Ca order by Order
The Criteria API interfaces will be explored in greater detail throughout this
module.
For example:
s a
EntityManagerFactory emf = Persistence.getEntityManagerFactory();
) h a
m x CriteriaBuilder cb = emf.getCriteriaBuilder();
t g ob
a dtypically
The Java Persistence API query language conditional expressions
s e used
in a WHERE clause are provided by the Criteria API as l@ Gu
methods
aexpression i
of the
r n
e object.
CriteriaBuilder class. Calling the conditional
n t methods on the
b
to Stud
CriteriaBuilder class returns a Predicate e
e s
( e rn this
d e z use
anWHEREe Clause
Table 10-2 Relating Java Persistence
r n to Conditional Expressions to Methods of the
CriteriaBuilder
H e ens
Class
n l
a e lJava ic Persistence API Query
r
e aType l
b Language Conditional
t B
ConditionaloExpression
e r CriteriaBuilder Methods
s s f
E rne -tran Expression Operators
arlos Comparison
non expression =, >, >=, <, <=, <> equal, greaterThan,
C greaterThanOrEqualTo,
lessThan,
lessThanOrEqualTo,
notEqual, gt, ge, lt,
le
Between expression [NOT] BETWEEN between, notbetween
Like expression [NOT] LIKE like, notlike
In expression [NOT] IN in, not(in)
Null comparison expression IS [NOT] NULL isNull, isNotNull
Empty collection comparison IS [NOT] EMPTY isEmpty, isNotEmpty
expression
Collection member expression [NOT] MEMBER OF isMember, isNotMember
Table 10-2 Relating Java Persistence WHERE Clause Conditional Expressions to Methods of the
CriteriaBuilder Class
Expression Operators
s a
The following example returns all Bid entities that have an amount greater than
) h a
m x 100.0:
b
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder(); tgo
s a de
2
3
CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
Root<Bid> bid = cq.from(Bid.class); n a l@ Gui
4 Predicate condition = cb.gt(bid.get(Bid_.amount), b er 100.0);
e n t
5 cq.where(condition);
e s to Stud
6 e rn this
TypedQuery<Bid> query = entityManager.createQuery(cq);
(
7 e
List<Bid> bids = query.getResultList();
d z use
r n an e to
CriteriaBuilder
complex a l e ns theexpression
HeForicconditional methods can be combined to form
r n queries.
l e l example, following example returns all Bid entities that
haveean amountb greater than 100.0 and an approval value of pending:
o B r a
1 e st nsfecb = entityManager.getCriteriaBuilder();
CriteriaBuilder
n
2
s Er n-tra
CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
r l
3 o n o
Root<Bid> bid = cq.from(Bid.class);
Ca 4 Predicate condition = cb.and(
5 cb.greaterThan(bid.get(Bid_.amount), 100.0),
6 cb.equal(bid.get(Bid_.approval), pending)
7 );
8 cq.where(condition);
9 TypedQuery<Bid> query = entityManager.createQuery(cq);
10 List<Bid> bids = query.getResultList();
class.
The metamodel class name is the same as the entity class name plus a trailing
underscore character. For example, the Bid entity has a metamodel class named
Bid_.
The software developer creates the metamodel using the tools provided by the
persistence provider. The resulting metamodel is the canonical metamodel class s a
for the entity class. The metamodel class is canonical if it provides public static ) h a
m x
fields for each persistent field in the entity. The persistence provider is
g ob
responsible for initializing the metamodel class when the persistence unit is
t
deployed. s a de
n a l@ Gui
For example, the following is the Bid entity
b er dethat
definition nt the developer creates:
e s to Stu
1
2
@Entity
public class Bid{ ( e rn this
3 @Id d e z use
4 private long bidId;
r n an e to
5 e ens
private doubleHamount;
n l
a approval;lic
6
r
private String
e ab l e
7 B
t ... sfer
o
8
e s
//
n tran
9 Er}
r l o s non-
C a The following is the corresponding metamodel class:
1 @StaticMetamodel(Bid.class)
2 public class Bid_{
3 public static volatile SingularAttribute<Bid, Long> bidId;
4 public static volatile SingularAttribute<Bid, Double> amount;
5 public static volatile SingularAttribute<Bid, String> approval;
6
7 // ...
8 }
Since the metamodel class provides an easy way to supply both the field name
and the datatype for the criteria, the Java compiler can guard against misspelled
field names and mismatched datatypes. In the following example, both the invalid
field name amt and the incorrect boolean value supplied for a string field will be
caught by the compiler or the IDE as you write the code:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
3 Root<Bid> bid = cq.from(Bid.class);
4 Predicate condition = cb.and(
5 cb.gt(bid.get(Bid_.amt), 100.0),
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
6 cb.equal(bid.get(Bid_.approval), true)
7 );
8 cq.where(condition);
9 TypedQuery<Bid> query = entityManager.createQuery(cq);
10 List<Bid> bids = query.getResultList();
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
Note If you use the string-based methods, misspelled class names and fields
names can appear once again in the queries.
The following example uses string-based methods to return all Bid entities with
an amount greater than 100.0:
s a
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
) h a
2 CriteriaQuery<Bid> cq = cb.createQuery(Bid.class);
m x
3 Root<Bid> bid = cq.from(Bid.class);
t g ob
4
s a de
Path<Double> amount = bid.<Double>get(amount);
5 l@ Gui
Predicate condition = cb.gt(amount, 100.0);
n a
6 cq.where(condition);
b er dent
7 to Stu
TypedQuery<Bid> query = entityManager.createQuery(cq);
e s
8
rn this
List<Bid> bids = query.getResultList();
( e
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
Parameter Expressions
A ParameterExpression instance is an expression that corresponds to a
parameter whose value will be supplied before the query is executed. Parameter
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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
Joins
The join methods of the From interface extend the query domain by creating a
join with a related class that can be navigated to or that is an element of the given
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
class of the query domain. The join methods may be applied to instances of the
Root and Join types.
For example, given the Order entity and corresponding Order_ metamodel
class, a join to the line items of the order would be expressed as follows:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<Order> cq = cb.createQuery(Order.class);
s a
3 Root<Order> order = cq.from(Order.class);
) h a
4 Join<Order, Item> item = order.join(Order_.lineitems);
m x
5 cq.select(order);
t g ob
6
a de
TypedQuery<Order> query = entityManager.createQuery(cq);
s
7 List<Order> orders = query.getResultList();
n a l@ Gui
b er dent
e s to Stu
e
The join methods have the (samernsemantics
thisas the corresponding Java
z
de operations.
Persistence query language us e
a n
t o
e rn nse
n a l H lice
For example:
1
B er acbble= entityManager.getCriteriaBuilder();
CriteriaBuilder
2 s to sfer
CriteriaQuery<String>
e
cq = qb.createQuery(String.class);
n tran customer = cq.from(Customer.class);
3 rRoot<Customer>
E
r l o s non-
4 Join<Customer, Order> order = customer.join(Customer_.orders);
C a 5 Join<Order, Item> item = order.join(Order_.lineitems);
6 cq.select(customer.get(Customer_.name))
7 .where(qb.equal(item.get(Item_.product).get(Product_.productType),
8 "printer"));
9 TypedQuery<String> query = entityManager.createQuery(cq);
10 List<String> names = query.getResultList();
11
This query is equivalent to the following Java Persistence query language query:
SELECT c.name
FROM Customer c JOIN c.orders o JOIN o.lineitems i
WHERE i.product.productType = 'printer'
Chaining Joins
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Joins can be chained, which enables you to write queries more concisely:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2 CriteriaQuery<String> cq = qb.createQuery(String.class);
3 Root<Customer> customer = cq.from(Customer.class);
4 Join<Order, Item> item =
5 customer.join(Customer_.orders).join(Order_.lineitems);
6 cq.select(customer.get(Customer_.name)) s a
7 .where(qb.equal(item.get(Item_.product).get(Product_.productType), ) h a
8 "printer")); m x
9 TypedQuery<String> query = entityManager.createQuery(cq);
t g ob
10 List<String> names = query.getResultList(); s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
Outer Joins e z use
d
an e to
r n
l H e method
By default, the join
c e ns defines an inner join. Outer joins are defined by
e rna ble li
specifying a JoinType argument.
t o B era
n e s NotensfOnly left outer joins are required to be supported in Java Persistence API
Er n-tr2.0.a
r l o s n o Applications that use right outer joins or right outer fetch joins are not
C a portable.
This query is equivalent to the following Java Persistence query language query:
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
Query Modification
A CriteriaQuery object may be modified either before or after TypedQuery
objects have been created and executed from it. For example, such modification
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
might entail replacement of the where predicate or the select list. Query
modifications could thus result in the same CriteriaQuery base being reused
for several query instances.
For example, the user might create and execute a query from the following
CriteriaQuery object:
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
s a
2 CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
) h a
3 Root<Customer> c = cq.from(Customer.class);
m x
4 Predicate pred =
t g ob
5
a de
cb.equal(c.get(Customer_.address).get(Address_.city),"Chicago");
s
6 cq.select(c);
n a l@ Gui
7
8
cq.where(pred);
b er dent
TypedQuery<Customer> chicagoQuery = entityManager.createQuery(cq);
9 e s to Stu
List<Customer> chicagoCustomers = chicagoQuery.getResultList();
( e rn this
The CriteriaQuery object d e zmight uthen
s ebe modified to reflect a different
anexample:
predicate condition,nfor
r e to
10 Predicate pred2 = l H
e ens
r n a e lic
11 e abl
cb.gt(c.get(Customer_.balancedOwed),
B
1000);
e s to sfer chicagoPastDueQuery =
12 cq.where(pred2);
n tran
13 TypedQuery<Customer>
14 Er entityManager.createQuery(cq);
r l o n o n-
s List<Customer> chicagoPastDueCustomers =
C a 15
16 chicagoPastDueQuery.getResultList();
Note that query elements are dependent on the CriteriaQuery instance, and
are thus not portably reusable with different CriteriaQuery instances.
Order instances.
An Order instance is created by means of the asc and desc methods of the
QueryBuilder interface. If more than one Order instance is specified, the order
in which they appear in the argument list of the orderBy method determines the
precedence, whereby the first item has highest precedence.
For example: s a
) h a
1 CriteriaBuilder cb = entityManager.getCriteriaBuilder();
m x
2 CriteriaQuery<Order> cq = cb.createQuery(Order.class);
t g ob
3 Root<Customer> c = cq.from(Customer.class);
s a de
4 l@ Gui
Join<Customer,Order> o = c.join(Customer_.orders);
n a
5
er dent
Join<Customer,Address> a = c.join(Customer_.address);
b
6
7 cq.select(o); e s to Stu
cq.where(cb.equal(a.get(Address_.state), "CA"));
8 ( e rn this
cq.orderBy(cb.desc(o.get(Order_.quantity)),
9 d e z use
cb.asc(o.get(Order_.totalCost)));
10 n an e to
TypedQuery<Order> query = entityManager.createQuery(cq);
r
11 H e ens
List<Order> orders = query.getResultList();
12 n l
a e lic
r
e abl
B
to This r corresponds to the following Java Persistence query language query:
equery
e s s f
E rn o -tran
sSELECT
on
C arlo FROM nCustomer c JOIN c.orders o JOIN c.address a
WHERE a.state = 'CA
ORDER BY o.quantity DESC, o.totalcost
For example:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<Customer> c = cq.from(Customer.class);
s a
Join<Customer, Order> o = cq.join(Customer_.orders);
) h a
Join<Customer, Address> a = cq.join(Customer_.address);
m x
cq.where(cb.equal(cq.get(Customer_.id), 97510));
t g ob
cq.multiselect(o.get(Order_.quantity).alias("quantity"),
s a de
n a l@ Gui
cb.prod(o.get(Order_.totalCost), 1.08).alias("taxedCost"),
a.get(Address_.zipcode).alias("zipcode"));
b er dent
TypedQuery<Tuple> typedQuery = em.createQuery(cq);
e s to Stu
Tuple result = typedQuery.getSingleResult();
( e rn this
Double cost = result.get("taxedCost", Double.class);
e z use
Integer quantity = result.get("quantity", Integer.class);
d
r n an e to
String zip = result.get("zipcode", String.class);
H e ens
n l licbe retrieved by position. For example:
a canealso
Tuple values
r
e ab l
Tuple resultto= B er
typedQuery.getSingleResult();
e s n=sfresult.get(0,
Integernquantity Integer.class);
E a
rcost -=trresult.get(1,
os zipnon= result.get(2, String.class);
Double Double.class);
C arlString
s a
Objectives ) h a
m x
Upon completion of this module, you should be able to: atg
ob
s d e
Use the Java Persistence API from a servlet al@ Gu
i
b e rn ent
Use the Java Persistence API fromoastateless session
d bean
s t t u
e r ne his S
z ( e t
e
nd to u s
n a
H er ense
r n al e lic
B e abl
e s to sfer
E rn -tran
s non
C arlo
11-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
version 6.0. In this module, you will learn how to use the Java Persistence API
from various components, including:
Servlets
Stateless session beans
Java Servlets
A Java Servlet responds to HTTP requests. Servlets run within the Java EE
component container architecture. This container is called the web container, also
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
The web container performs initial processing and selects the intended servlet to
handle the request. The container also controls the life cycle of the servlet.
HTTP request
User Workstation Web Server
s a
Web Container
) h a
Browser HTTP
m x
Servlet
t g ob
s a dDatabase
e
al@ t Gu i
HTTP response
r n
e den
o b <HTML>
n e st S tu
z (er e this </HTML>
a n
de to us
Figure 11-1 Sample
e rn nsServer
Web
e Architecture With Java Servlets
n a l H lice
B
Noteer In some
a b learchitectures, the web container acts as a stand-alone HTTP
e s toservice.
s f eInrother architectures, the HTTP service forwards requests to be
E an by the web container.
rn -trprocessed
s non
C arlo
The method in the servlet that is invoked depends on the type of HTTP request.
For example, an HTTP GET request will invoke the doGet method in the servlet.
The doGet method takes two parameters, one that carries information related to
the original request and another that controls the response.
s a
h a
x)
The servlets job is two-fold. First, it must perform the required computation.
Second, it must present the results in a well-formed HTML page. bm
a t go
Code 11-1 Simple Servlet
@ s ide
n a l G u
1 package sl351.m1;
b r
e den t
o
2
n e st S tu
r this
3 import java.io.IOException;
4 import java.io.PrintWriter; z (e e
5 n
de to us
import javax.servlet.ServletException;
a
6 rn nse
import javax.servlet.annotation.WebServlet;
e
7 l H lice
import javax.servlet.http.HttpServlet;
n a
8
er able
import javax.servlet.http.HttpServletRequest;
B
9
to sfer
import javax.servlet.http.HttpServletResponse;
e s
an
10
11Ern - t r
arlos12 n on
@WebServlet(name="ListServlet", urlPatterns={"/ListServlet"})
C 13 public class ListServlet extends HttpServlet {
14
15 @Override
16 protected void doGet(HttpServletRequest request,
17 HttpServletResponse response)
18 throws ServletException, IOException {
19 response.setContentType("text/html;charset=UTF-8");
20 PrintWriter out = response.getWriter();
21 try {
22 out.println("<html>");
23 out.println("<head>");
24 out.println("<title>HelloServlet</title>");
25 out.println("</head>");
26 out.println("<body>");
27 out.println("<h1>HelloServlet says \"Hello,
World!\"</h1>");
28 out.println("</body>");
29 out.println("</html>");
30 } finally {
31 out.close();
32 }
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
33 }
34 }
Once the entity manager factory is injected into the servlet, method calls like
getEntityManager and createQuery return the results to the servlet. The
results are then rendered as HTML.
e s to Stu 6
@Override
( e rn this request,
protected void doGet(HttpServletRequest
7
8
HttpServletResponse response)d e z use 9
n an eIOException
throws ServletException,
r to { 10
e
H iem s
en= emf.getEntityManager(); 11
a l l c
ern ablelist = em.createQuery("select i from Item i")
EntityManager 12
B
List<Item>
to sfer
13
n e s n
.getResultList(); 14
s Er n-traresponse.setContentType("text/html;charset=UTF-8"); 15
arlo no 16
C PrintWriter out = response.getWriter(); 17
18 try {
19 out.println("<html>");
20 out.println("<head>");
21 out.println("<title>HelloServlet</title>");
22 out.println("</head>");
23 out.println("<body>");
24
25 out.println("<table border='1'>");
26 out.println("<tr><th>Name</th> +
27 <th>Description</th></tr>");
28 for(Item item: list){
29 out.println("<tr>");
30 out.println("<td>" + item.getName() + "</td>");
31 out.println("<td>" + item.getDescription() +
32 "</td>");
33 out.println("</tr>");
34 }
35 out.println("</table>");
36
37 out.println("</body>");
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
38 out.println("</html>");
39 } finally {
40 out.close();
41 }
42 }
43 }
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non Figure 11-2 Output of the ListServlet Servlet Response
C arlo
Note the following additional information regarding persistence contexts and
entity managers:
A persistence context is a set of managed entity instances in which for any
persistent entity identity (primary key) there is a unique entity instance.
Within the persistence context, the entity instances and their lifecycle are
managed by the entity manager.
You do not create a persistence context directly. Instead, you use the
persistence context that is created when the entity manager is created.
An entity manager must not be shared among multiple concurrently
executing threads, as the entity manager and persistence context are not
required to be threadsafe. Entity managers must only be accessed in a
single-threaded manner.
For queries that require a transaction (typically statements that involve a SQL
INSERT, UPDATE, or DELETE), you have two transaction management options:
user-managed or container-managed.
If you choose to perform queries that require transactions in a servlet, you must
manage the all of the transaction handling yourself. These user-managed
transactions are controlled by obtaining a
javax.transaction.UserTransaction object from the entity manager. s a
) h a
m x
ob
To take advantage of container-managed transactions, you should move the Java
t g
Persistence API queries into an enterprise bean.
a de
s
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
s a
From an architectural perspective, session beans encapsulate business logic in a
) h a
m x
centralized, reusable fashion, accessible by any number and styles of clients.
t g ob
s a de
From a developers perspective, a session bean is a Java object that adheres to a
small set of coding conventions and executes in a managed
n a l@ Gui
environment.
b er asda eserver-side
nt
s o oftua server.
From a clients perspective, a session bean functions
tcontext extension
e r n his S
that performs the business logic withinethe
z ( e t
e
nd to u s
Types of Session n a
Beans
H er ense
n l licdescribes three different types of session beans:
aspecification
r
The EJB
e ab l e
t o B ferStateless session beans (SLSB) - Generic business processing
e s s
E rn -tran Stateful session beans (SFSB) - User-specific business processing
s non
C arlo Singleton session beans (SSB) - Shared data access
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
No-Interface Implementation
Starting with EJB 3.1, Enterprise JavaBeans components can be developed
without the creation of a separate business interface. This implementation
strategy, known as a no-interface implementation, delivers a less cumbersome
s a
development process.
) h a
m x
t ob
To create a no-interface implementation of a session bean, apply the
g
@LocalBean annotation directly to the bean class.
s a de
n
Code 11-3 A No-Interface Stateless Session Beana l@ Gui
b er dent
1 @Stateless
e s to Stu
2 @LocalBean rn this
3 public class CalculatorBean {z (e e
d e u s
4 public CalculatorBean()
r n aton illustrate
{
e to requirements
5
e ens
//added explicitly
H
6 }
n l
a e lic
7 r
e add(int
b l
8 public
t Bint a
o safe+rb; a, int b) {
9
ne s n
return
10Er } -tra
s n
C arlo 11 no 12 public int subtract(int a, int b) {
13 return a - b;
14 }
15 }
Note When using the no-interface representation of a session bean, all of the
public methods defined within the bean are considered part of the local interface.
While no-interface implementation strategy requires less development overhead,
fine-grained control over the mode of method access is lost.
Once the entity manager is injected into the stateless session bean, method calls
like createQuery return the results to the stateless session bean. The results are
s a
then returned to the client that created the method class.
) h a
m x
t g ob
Code 11-4 Stateless Session Bean Using an Injected Entity Manager
1 package com.acme.ejb; s a de
2
n a l@ Gui
3 import com.acme.entities.Item;
b er dent
4 import javax.ejb.LocalBean;
e s to Stu
5 import javax.ejb.Stateless;
( e rn this
6 z use
import javax.persistence.EntityManager;
d e
7
an e to
import javax.persistence.PersistenceContext;
r n
8
H e ens
9 @Stateless l
a e lic
10 @LocalBean ern l
11 public class B
o sfer a b
ItemDaoBean {
s t
e ran
12
r n@PersistenceContext(unitName = "JPA1-warPU")
13 E private
o s o n -t EntityManager em;
l
ar14 n
C 15 public void save(Item item) {
16 em.persist(item);
17 }
18 }
19
Because stateless session beans are single threaded, it is perfectly safe to use an
entity manager from a stateless session bean.
38 out.println("<td>" + item.getDescription() +
"</td></tr>");
39 out.println("<tr><td>Photo</td>");
40 out.println("<td>" + item.getPhoto() + "</td></tr>");
41 out.println("</table>");
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
42
43 out.println("</body>");
44 out.println("</html>");
45 } finally {
46 out.close();
47 }
48 }
49 } s a
) h a
m x
t g ob
To test AddServlet, pass in the id, name, description, s aand photo
d e
al@intot the i
ubrowser:
attributes in the query string by typing the followingnURL
r
e den G
o b
http://localhost:8080/JPA1-war/AddServlet?
n e st S tu
(er e this
id=99&
name=New+Book&
description=New+Description&
z
de to us
a n
photo=New+Photo
e rn nse
n a l H lice
B
Noteer TheaURLb leshould be typed as a single line.
e s to sfer
E an
rn -trAddServlet
r l o s non does the following:
Ca Parses the query string using request.getParameter()
Builds a well-formed Item object
Passes the Item to the ItemDaoBean for persistence
Displays the results as HTML
s a
) h a
m x
Figure 11-3 Output of the AddServlet Servlet Response gob
s at de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
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
Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
Describe the transaction demarcation management atg
ob
s d e
al@ t Gu
Implement container-managed transactions (CMT) i
r n
e CMT n
b
Interact programmatically with an ongoing
o d etransaction
n e st (BMT) S tu
this API
(er Persistence
Implement bean-managed transactions
z
Apply transactionseto the Javase
n a nd to u
H er ense
r n al e lic
B e abl
e s to sfer
E rn -tran
arlos non
C
12-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
t g ob
index.html], accessed September 15, 2009.
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
What Is a Transaction?
A typical enterprise application accesses and stores information in one or more
databases. Because this information is critical for business operations, it must be
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
accurate, current, and reliable. Data integrity would be lost if multiple programs
were allowed to update the same information simultaneously. Data integrity
would also be lost if a system that failed while processing a business transaction
were to leave the affected data only partially updated.
s Er n-tra
arlo no A transaction can end in two ways: with a commit or with a rollback. When a
C transaction commits, the data modifications made by its statements are saved. If a
statement within a transaction fails, the transaction rolls back, undoing the effects
of all statements in the transaction.
In the pseudocode, for example, if a disk drive were to crash during the credit
step, the transaction would roll back and undo the data modifications made by the
debit statement. Although the transaction fails, data integrity would be intact
because the accounts still balance.
In the preceding pseudocode, the begin and commit statements mark the
boundaries of the transaction. When designing an enterprise bean, you determine
how the boundaries are set by specifying either container-managed or bean-
managed transactions.
Container-Managed Transactions
In an enterprise bean with container-managed transaction (CMT) demarcation,
the EJB container sets the boundaries of the transactions. You can use container-
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
b er dent
s
Container-managed transactions do noterequire to allSmethods
tu to be associated with
n
er you
transactions. When developing a(bean, hisspecify which of the beans
z
methods are associated withetransactions e tcan
n
d u s by setting the transaction attributes.
o
rnausencontainer-managed
et
H
Enterprise beans e that
e s transaction demarcation must not
l i c
e r a demarcation
use anyntransaction
b l e lmanagement methods that interfere with the containers
o B
transaction
r a boundaries. Examples of such methods are the commit,
n e st setAutoCommit,
n s fe and rollback methods of java.sql.Connection or the
E r - t r a
commit and rollback methods of javax.jms.Session. If you require
s non control over the transaction demarcation, you must use application-managed
C arlo transaction demarcation.
beans with container-managed transactions require less coding, they have one
limitation: When a method is executing, it can be associated with either a single
transaction or no transaction at all. If this limitation will make coding your bean
difficult, you should consider using bean-managed transactions.
The following pseudocode illustrates the kind of fine-grained control you can
obtain with application-managed transactions. By checking various conditions,
the pseudocode decides whether to start or stop different transactions within the s a
business method. ) h a
m x
begin transaction
t g ob
...
s a de
update table-a
n a l@ Gui
...
if (condition-x) b er dent
e s
commit transactionto Stu
( e rn this
else if (condition-y)
e z use
update table-b
d
r n an e to
commit transaction
H e ens else
n l
a e lic rollback transaction
r
e abl
B
to sfer
begin transaction
e s update table-c
E rn -tran commit transaction
s non
C arlo When coding a application-managed transaction for session beans that use the
Java Persistence API, you must use either Java Transaction API transactions or
Java Persistence API EntityTransaction API transactions.
b er dent
Name Type e s to StuDescription
Default
( e rn this
name String
d e z use The name by which the entity
n n
a et o manager is to be accessed in the
r
e ens environment referencing context.
l H
a e li c The name is not needed when
r
e abn l dependency injection is used.
B er
to PersistenceProperty[]
e s
properties
n s f Used to specify properties for the
r n
E n-t r a container or persistence provider.
s
C arlo no Vendor-specific properties may be
included in this set of properties.
Properties that are not recognized
by a vendor are ignored.
type PersistenceContextType TRANSACTION Specifies whether this is a
transaction-scoped persistence
context (TRANSACTION) or an
extended persistence context
(EXTENDED).
unitName String The name of the persistence unit.
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
s a
EntityTransaction Interface ) h a
m x
t
The EntityTransaction interface is used to control resource transactions g ob on
resource-local entity managers. s a de
n a l@ Gui
The EntityManager.getTransaction()
b ermethode t the
returns
n
EntityTransaction interface.
e s to Stud
e rn this iused,
When a resource-local entity manager
( s and the persistence provider
e
runtime throws an exception
d z defined
u s e to cause transaction rollback, the
r n an must
persistence provider
e to the transaction for rollback.
mark
H e ens
If the EntityTransaction.commit operation fails, the persistence
a l l i c
ern able
provider must roll back the transaction.
B
to sfer
e s
E rn -tran
arlos non The following example illustrates the creation of an entity manager factory in a
C Java SE environment, and its use in creating and using a resource-local entity
manager.
1 import javax.persistence.*;
2
3 public class PasswordChanger {
4 public static void main (String[] args) {
5 EntityManagerFactory emf =
6 Persistence.createEntityManagerFactory("Order");
7 EntityManager em = emf.createEntityManager();
8 em.getTransaction().begin();
9 User user = (User)em.createQuery
10 ("SELECT u FROM User u WHERE u.name=:name +
11 AND u.pass=:pass")
12 .setParameter("name", args[0])
13 .setParameter("pass", args[1])
20 }
21 }
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
application. The persistence context is propagated with the Java Transaction API
transaction.
1 @Stateless
2 public class ShoppingCartImpl implements ShoppingCart {
3 @PersistenceContext EntityManager em;
4
5 public Order getOrder(Long id) {
6 Order order = em.find(Order.class, id);
7 order.getLineItems();
8 return order;
9 }
10
11 public Product getProduct(String name) {
12 return (Product) em.createQuery("select p from Product p +
13 where p.name = :name")
14 .setParameter("name", name)
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
15 .getSingleResult();
16 }
17
18 public LineItem createLineItem(Order order,
19 Product product, int quantity) {
20 LineItem li = new LineItem(order, product, quantity);
21 order.getLineItems().add(li);
22 em.persist(li); s a
23 return li; ) h a
24 } m x
} 25
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
Container-Managed Extended
( e rn thPersistence
is Context
d e z use
A container-managed
r n an extended
e to persistence context can only be initiated within
H e s bean.
the scope ofea statefulnsession
l c
a e li exists from the point at which the stateful session bean that
rn The context
e l
B
o sfer a b
s t declares a dependency on an entity manager of type
C arlo The persistence context is closed by the container when the @Remove
method of the stateful session bean completes or the stateful session bean
instance is otherwise destroyed.
If a stateful session bean instantiates a stateful session bean executing in the
same EJB container instance that also has an extended persistence context,
the extended persistence context of the first stateful session bean is inherited
by the second stateful session bean and is bound to it. This rule then
recursively applies, independently of whether transactions are active at the
point of the creation of the stateful session beans.
If the persistence context has been inherited by any stateful session beans,
the container does not close the persistence context until all such stateful
session beans have been removed or otherwise destroyed.
1 @Stateful
2 @Transaction(REQUIRES_NEW)
3 public class ShoppingCartImpl implements ShoppingCart {
4 @PersistenceContext(type=EXTENDED)
5 EntityManager em;
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
an e to
em.persist(li); 23
return li; r n
e ens 24
} l H
a e lic 25
} r n
e abl 26
B
to sfer
e s
E rn -tran
arlos non
C
Optimistic Locking
Optimistic locking is a technique that is used to ensure that updates to the
database data corresponding to the state of an entity are made only when no
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
intervening transaction has updated that data since the entity state was read.
This technique ensures that updates or deletes to that data are consistent
with the current state of the database and that intervening updates are not
lost.
Transactions that would cause this constraint to be violated result in an
OptimisticLockException being thrown and the transaction being
marked for rollback. s a
) h a
m x
Version Attribute
t g ob
s a de
a l@ for i must
uentities
Portable applications that wish to enable optimistic n locking G
r is, persistent
ethat n t properties or
specify Version attributes for those entities,
to S b e
ud in the XML descriptor
s
fields annotated with the Version annotation or tspecified
e
rn this
as version attributes.
( e
z enabled e for optimistic locking if it has a property
d e u s
an withe atVersion
An entity is automatically
r n
or field mapped o mapping.
e n s
n a l HVersion
The l i c efield can be one of the following data types: int, long,
B er short,
a b lejava.lang.Integer, java.lang.Long, java.lang.Short,
e s to sfeorr java.sql.Timestamp.
E rn -tran An entity may access the state of its version field or property or export a
s non
C arlo method for use by the application to access the version, but must not modify
the version value. Only the persistence provider is permitted to set or update
the value of the version attribute in the object.
The version attribute is updated by the persistence provider runtime when
the object is written to the database. All non-relationship fields and
properties and all relationships owned by the entity are included in version
checks.
Applications are strongly encouraged to enable optimistic locking for all
entities that might be concurrently accessed or that might be merged from a
disconnected state.
Failure to use optimistic locking could lead to inconsistent entity state, lost
updates and other state irregularities.
If optimistic locking is not defined as part of the entity state, the application
must be designed to maintain data consistency.
1 @Entity
2 public class Item{
3 @Id
4 private int id;
5 @Version
6 private int version;
7
8 //... s a
9 }
) h a
m x
t g ob
s a de
The persistence providers implementation of the merge a @ Gumust
loperation i examine
n
er anddthrow nt an
the version attribute when an entity is being merged
b
tobeingSmerged e
u is a stale copy of the
OptimisticLockException if the object
e s t
( e rn since
entity, that is, the entity has been updated
t h isthethisentity became detached.
Depending on the implementation
e z s e
strategy used, exception might not be
thrown until flush is called
n a nd or tcommit
o u time, whichever happens first.
H er containe n se
a l
If only certain
n i
entities
l c version attributes, the persistence provider runtime
er atobcheck
is required
B le those entities for which version attributes have been
s t o sfer
specified. The consistency of the object graph is not guaranteed, but the absence
E rne -trofcompleting.
n attributes on some of the entities will not stop operations from
aversion
arlos non
C
Pessimistic Locking
Optimistic locking is typically appropriate in dealing with moderate contention
among concurrent transactions. However, in some applications it might be useful
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Note A portable application should not rely on the way that pessimistic locking
is achieved on the database. In particular, a persistence provider or the underlying
database management system might lock more rows than the ones selected by the
application.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
Lock Modes
Lock modes can be specified by means of the EntityManager lock method,
the methods of the EntityManager and Query interfaces that allow lock modes
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Lock mode values are defined by the LockModeType enum. The six distinct lock
modes are:
OPTIMISTIC
OPTIMISTIC_FORCE_INCREMENT
s a
PESSIMISTIC_READ
) h a
m x PESSIMISTIC_WRITE
PESSIMISTIC_FORCE_INCREMENT t g ob
s a de
NONE
n a l@ Gui
b er dent
Note The lock mode type values e s toand WRITE
S tu are supported for backwards
n READ
is 1.0 applications.
(er API
compatibility with Java Persistence
z e thversion
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer and OPTIMISTIC_FORCE_INCREMENT
OPTIMISTIC
E rn Modes
- t r an
arlos non
C This section describes the semantics of requesting locks of type
LockModeType.OPTIMISTIC and
LockModeType.OPTIMISTIC_FORCE_INCREMENT.
s a
) h a
m x
PESSIMISTIC_READ, PESSIMISTIC_WRITE, andgob
PESSIMISTIC_FORCE_INCREMENT Modes sat de
n a l@ Gui
b r ofetype
elocks n t
to Stud
This section describes the semantics of requesting
LockModeType.PESSIMISTIC_READ, e s
LockModeType.PESSIMISTIC_WRITE, ( e rn tand his
z
de to us e
LockModeType.PESSIMISTIC_FORCE_INCREMENT.
a n
If transactionH rn lock(entity,
T1ecalls n se LockModeType.PESSIMISTIC_READ)
l c e
liLockModeType.PESSIMISTIC_WRITE) on an object, the
e na lmust
or lock(entity,
rmanager e
o B
entity
r a b ensure that neither of the following phenomena can occur:
n e st nsDirty
fe read: Transaction T1 modifies a row. Another transaction T2 then
s Er n-tra reads that row and obtains the modified value before T1 has committed or
arlo no rolled back.
C Non-repeatable read: Transaction T1 reads a row. Another transaction T2
then modifies or deletes that row before T1 has committed or rolled back.
Any such lock must be obtained immediately and retained until transaction T1
completes (commits or rolls back).
A lock with LockModeType.PESSIMISTIC_WRITE can be used to query
data when there is a high likelihood of deadlock or update failure among
concurrent updating transactions.
A lock with LockModeType.PESSIMISTIC_READ can be used to query
data using repeatable-read semantics without the need to reread the data at
the end of the transaction to obtain a lock, and without blocking other
transactions reading the data.
When the lock cannot be obtained and the database locking failure results in
transaction-level rollback, the provider must throw the
PessimisticLockException and ensure that the Java Transaction API
s a
transaction or EntityTransaction has been marked for rollback.
) h a
m x
b in only
When the lock cannot be obtained, and the database locking failureoresults
g
t
a de
s
statement-level rollback, the provider must throw the LockTimeoutException
and must not mark the transaction for rollback.
n a l@ Gui
r ent
iseobtained
b
calculate the amount of the highest e s
Bid.
to Stud on an Auction entity to
In the following example, a pessimistic lock
( e rn this
d e z uLock
Code 12-3 Using a Pessimistic s e
r n an e to
H e ens
l
a e licauctionId){
public void endAuction(int
n
Auction auction r b l
e = aem.find(Auction.class, auctionId);
o B r
n e st nsfe= (Bid) em.createNamedQuery("findHighestBidByAuctionId")
em.lock(auction, LockModeType.PESSIMISTIC_WRITE);
s
Bid
n - tra
Er .setParameter("auctionId",
highestBid
auctionId)
r l o n o
Ca .getSingleResult();
auction.setWinningBid(highestBid);
}
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
Objectives a
h a s
x )
m Upon completion of this module, you should be able to:
t g ob
Specify composite primary keys
s a de
a
Override mappings with the @AttributeOverride
n l@ and G ui
@AssociationOverride annotations er n t
b e
e
Understand entity listeners and s
callback S tud
to methods
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
arlos non
C
13-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following reference provides additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
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
entity.
Up until now, the focus has been on entities that use a single field to represent the
primary key. Entities can, however, use multiple fields as a unique identifier. This
identifier is called a composite primary key.
Note Composite primary keys typically arise when mapping from legacy s a
databases where the database key is comprised of several columns. ) h a
m x
A simple, that is, non-composite, primary key must correspond
t g ob to a single
s
persistent field or property of the entity class. The @Ida annotation
d e or id
XML element must be used to denote a simple @ Gkey.
alprimary u i
r n
e to either t
na single persistent field
A composite primary key must correspond
o b d e
st or properties.
or property or to a set of suchefields
n S tu
z
A primary key class
e his to represent a composite primary
r betdefined
(emust
key.
a n
de to us
e
Thern@EmbeddedId
n se or @IdClass annotation is used to denote a
H
al composite e
r n l e lic primary key.
B e ab
e s t o s f er
E rn -tran
arlos non The following rules apply to composite primary keys:
C The primary key class must be public and must have a public no-arg
constructor.
The access type (field-based or property-based access) of a primary key
class is determined by the access type of the entity for which it is the
primary key unless the primary key is an embedded id and a different
access type is specified.
If property-based access is used, the properties of the primary key class
must be public or protected.
The primary key class must be serializable.
The primary key class must define equals and hashCode methods. The
semantics of value equality for these methods must be consistent with the
database equality for the database types to which the key is mapped.
of primary key fields or properties in the primary key class and those of the
entity class to which the id class is mapped must correspond and their types
must be the same.
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
class definition. This class must be marked with the @Embeddable annotation.
Note Embedded classes used to identify a composite primary key must not have s a
) h a
m x a primary key of their own.
t g ob
s
Once the embeddable class is defined, the entity class then adeclaresdea field
of the
embeddable class type and marks it with the @EmbeddedId u i
al@ t Gannotation.
r n
e den
Code 13-1 Using the @Embeddable t o b uto Identify the Composite
Primary Key Class rn e s Annotation
S t
z (e e this
1 package com.acme.entities;de us
a n
t o
2
e rn nse
3
4 n a l H lice
import java.io.Serializable;
import javax.persistence.Embeddable;
5 B er able
6 s to sfer
@Embeddable
e
7 rpublic
E - an EmployeeId implements Serializable{
n trclass
arlos89 nonprivate String firstName;
C private String lastName;
10
11 public EmployeeId(){}
12
13 public EmployeeId(String firstName, String lastName) {
14 this.firstName = firstName;
15 this.lastName = lastName;
16 }
17
18 public String getFirstName() {
19 return firstName;
20 }
21
22 public void setFirstName(String firstName) {
23 this.firstName = firstName;
24 }
25
26 public String getLastName() {
27 return lastName;
28 }
29
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Once the @Embeddable class is defined, you can use it as a primary key in an
entity class by marking the field with the @EmbeddedId annotation.
1 package com.acme.entities;
2
3 import java.io.Serializable;
4 import javax.persistence.EmbeddedId;
5 import javax.persistence.Entity;
6
7 @Entity
s a
8 public class Employee implements Serializable {
) h a
9
m x
10
@EmbeddedId
t g ob
11
private EmployeeId id;
s a de
12
n a l@ Gui
13
public EmployeeId getId() {
b er dent
14
return id;
e s to Stu
} 15
16 ( e rn this
17
public void setId(EmployeeId d e z id) u s e{
this.id = id;nan
18 to
r
e ens e
} 19
l H
a e lic
r n
20
e abl
B
// ... 21
er
} sto s f
22
e
rn -tran
E
s non
C arlo Note All of the attributes of the Embedded Id class will be persisted as columns
in the table that corresponds to the entity.
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
@IdClass annotation. While you still must define an external class as you did
when using an Embedded ID class, the key differences between the two methods
are:
The ID class is not annotated
The fields of the Entity class that comprise the composite primary key must
be annotated with the @Id annotation
s a
The fields of the ID class must match the name and data type of the Entitys
) h a
composite primary key fields exactly
m x
t g ob
s aPrimary
Code 13-4 Creating an ID Class to Identify the Composite
d e of an
Key
Entity
al@ t Gu i
r n
e den
1 package com.acme.entities;
o b
2
n e st S tu
3 import java.io.Serializable; (er
z e t his
4
5 a n
de to us
import javax.persistence.Embeddable;
28
29 public void setLastName(String lastName) {
30 this.lastName = lastName;
31 }
32
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
33 @Override
34 public boolean equals(Object obj) {
35 if (obj == null) {
36 return false;
37 }
38 if (getClass() != obj.getClass()) {
39 return false;
40 } s a
41 final EmployeeId other = (EmployeeId) obj; ) h a
42 m x
if ((this.firstName == null) ? (other.firstName != null) :
43
g ob
!this.firstName.equals(other.firstName)) {
t
44 return false; s a de
45 }
n a l@ Gui
46 er dent
if ((this.lastName == null) ? (other.lastName != null) :
b
47 to Stu
!this.lastName.equals(other.lastName)) {
e s
48 rn this
return false;
( e
49 }
d e z use
an e to
50 return true;
51 } r n
e ens
52 l H
@Override rna
53 l e lic
public B
e ab
s t o 54
f e r= 7;
int hashCode() {
rne -hash
int 55s
an= 67 * hash + (this.firstName != null ?
hash
E t r 56
s non this.firstName.hashCode() : 0);
C arlo 57
58
hash = 67 * hash + (this.lastName != null ?
59 this.lastName.hashCode() : 0);
60 return hash;
61 }
62 }
Once the ID class is defined, you can use it as a primary key in an entity class. To
do so, mark the entity class with the @IdClass annotation and mark each entity
field with the @Id annotation.
Code 13-5 Using the @IdClass Annotation and @Id Annotations to Identify
the Composite Primary Key
1 package com.acme.entities;
8 @IdClass(EmployeeId.class)
9 public class Employee implements Serializable {
10
11 @Id
12 private String firstName;
13 @Id
14 private String lastName;
s a
15
) h a
16 // ...
m x
17 }
t g ob
s a de
n a l@ Gui
b er dent
Finding Entities With an IDeClass s to S tu an Entity
Using
n
Manager z (er e this
a n
de to us
e rn find()
The entity manager
n se method can be used to find entity classes with
H
al method. e
composite
r n l e l c do so, create an instance of the ID class and pass it to the
keys. iTo
B e ab
find()
e s t o s f er
E rn -tranCode 13-6 Finding an Entity With an ID Class Composite Primary Key
s non
C arlo 1 EmployeeId 2
id = new EmployeeId(Jane, Doe);
Employee employee = em.find(Employee.class, id);
to a table column.
The @AttributeOverride annotation is applied to either an entity or an
attribute.
To override the mapping of an attribute in an embeddable class, apply the
@AttributeOverride to the entity, not the embeddable class.
s a
The @AttributeOverride annotation has two elements that can be used to
) h a
m x further refine the mapping of the entity attribute to the column in the table.
n e st nsfe
Er n-trFora example, the following class definition needs to be extended but column a
rlo s no name needs to be remapped.
C a
Code 13-7 The Employee Class
@MappedSuperclass
public class Employee {
@Id protected Integer id;
@Version protected Integer version;
protected String address;
@Entity
@AttributeOverride(name="address", column=@Column(name="ADDR"))
public class PartTimeEmployee extends Employee {
// address field mapping overridden to ADDR
protected Float wage();
public Float getHourlyWage() { ... }
public void setHourlyWage(Float wage) { ... }
}
s a
) h a
m x
Overriding Multiple Mappings With the
t g ob
@AttributeOverrides Annotation s a de
n a l@ Gui
b er dent
To override multiple mappings, use the @AttributeOverrides annotation.
t o t u
r n es is S
(e ande id
Code 13-9 Overriding address
Annotationez
thwith the @AttributeOverrides
a n
d to us
@Entity e rn nse
@AttributeOverrides({
n a l H lice
B er able
@AttributeOverride(name="address", column=@Column(name="ADDR"))
}) nes
to sfer
@AttributeOverride(name="id", column=@Column(name="SSN"))
r class t r n
aPartTimeEmployee
s E
public
n - extends Employee {
r l o o
n address field mapping overridden to ADDR
Ca
//
// id field mapping overridden to SSN
protected Float wage();
public Float getHourlyWage() { ... }
public void setHourlyWage(Float wage) { ... }
}
( e rn this
column=@Column(name="STREET_NAME")),
@AttributeOverride(name="value.size",
d e z use
column=@Column(name="SQUARE_FEET")),
n an e to
@AttributeOverride(name="value.tax",
r
H e ens column=@Column(name="ASSESSMENT"))
n
}) l
a e lic
r
e abl
B
to sfer
@ElementCollection
e s Map<Address, PropertyInfo> parcels;
E rn -tran }
s non
arlo
@Embeddable
C public class PropertyInfo {
Integer parcelNumber;
Integer size;
BigDecimal tax;
}
t g ob element
of the @AssociationOverride annotation is used.l@ sarelationship
If the relationship mapping is a foreign key mapping, the joinColumns
If the i d e mapping
uses a join table, the joinTable element of the r n a t Gu
@AssociationOverride
annotation must be specified to overrideothe b e deofnthe join table or its join
mapping
columns.
n e st S tu
z (er e this
further refine a n a ndefor tano entity
The @AssociationOverride
mapping
us
annotation has three elements that can be used to
relationship: name, joinColumns, and
joinTable.H er ense
r n al e lic
B e abl
e s to Note
s f erEither the joinColumns element or the joinTable element of the
E rn -tran@AssociationOverride annotation is specified for overriding a given
arlos non relationship, but never both.
C
s Er ...n-tra
arlo no
}
C
Remove
Update
Load
Each life-cycle event has a Pre and Post hook that can be triggered when the
event occurs. Life-cycle callback methods are designated with Pre and Post s a
annotations. ) h a
m x
t g ob
s a de
Table 13-3 Life-Cycle Callback Annotations
n a l@ Gui
b e r ent
Annotation Description
to Stud
e s
n hmethods
@PrePersist PrePersist ( e rcallbackt is are invoked for a given
entity e
d z s e
before the EntityManager.persist()
u method
n
o
e rnais executed.
s e t
l
@PostPersist
a l en
H icPostPersist callback methods are invoked for a given
n
er able entity after the database INSERT is executed.
B er
to @PreRemove
e s n s f PreRemove callback methods are invoked for a given
n
Er n-tra entity before the EntityManager.remove() method
rlo s no is executed.
C a @PostRemove PostRemove callback methods are invoked for a given
entity after the database DELETE is executed.
@PreUpdate PreUpdate callback methods are invoked for a given
entity when an update to the state of entity instance
occurs.
@PostUpdate PostUpdate callback methods are invoked for a given
entity after the database UPDATE is executed.
@PostLoad PostLoad callback methods are invoked after an entity
is loaded, either by a query or when the
EntityManager.find() method is executed.
@Entity
public class Account {
@Id
Long accountId;
Integer balance;
@Transient // because status depends upon non-persistent context s a
boolean preferred; ) h a
m x
@PrePersist
t g ob
protected void validateCreate() { s a de
if (getBalance() < MIN_REQUIRED_BALANCE)
n a l@ Gui
throw new AccountException("Insufficient
b erbalance
e n t +
e s S tud
to opentoan account");
}
( e rn this
@PostLoad
d e z use {
an e to
protected void adjustPreferredStatus()
preferred = r n
l H
(getBalance()
c ns
e >=eAccountManager.getPreferredStatusLevel());
}
e rna ble li
t o B era
s nsf
//e...
n
} Er
s n - tra
arlo no
C
The following rules apply to life-cycle callbacks:
The callback methods can have public, private, protected, or package level
access, but must not be static or final.
A single method may be annotated with multiple life-cycle events, but only
one callback method per life-cycle event should be used in a given entity.
For example, an entity cannot have two different callback methods
annotated with @PostLoad.
Life-cycle callback methods may throw unchecked or runtime exceptions.
A runtime exception thrown by a callback method that executes within a
transaction causes that transaction to be marked for rollback.
Life-cycle callbacks can invoke JNDI, JDBC, JMS, and enterprise beans.
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
e r na le li
t o f ab Using an Entity Listener Class
B Codee13-13
r
r n es rans
s E n-t
@Entity
l o no
ar @EntityListeners({com.acme.AlertMonitor.class,
C com.acme.PreferredStatusMonitor.class})
public class Account {
// ...
}
if(acct.isPreferred()){
log.info(acct.getAccountId() +
accessed on + new Date());
}
}
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
The rules for entity listener class callback methods are the same as those for
internal entity callback methods, with two important exceptions:
Only unchecked exceptions are allowed to be thrown. If an exception is
thrown by an entity class listener, the remaining listeners will not be called.
s a
Also, the transaction, if any, will be rolled back after the first exception is
) h a
m x thrown.
g
Superclass listeners are called before subclass listeners. Youtcan
b
ooverride
this behavior by using the @ExcludeSuperclassListeners s a dannotation.
e
al@ t Gu i
r n
e den
o b
n e st S tu
z (er e this
a n
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C
Using Validation
JSR 303 defines an API for validating JavaBean components. The Java
Persistence API does not require a validation implementation to be present. If a
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
The validation API defines a standard set of annotations that can be used to
validate an entity.
Constraint Description
Constraint Description
@Max(value=0) The field must be less than or
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
Java DB
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
A-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
A-2 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?
portability. The language offers standards compliance, a full feature set, and a
small footprint. It can be embedded in Java applications, requiring no
administration by the developer or user. It can also be used in client/server mode.
Java DB is fully transactional and provides a standard SQL interface as well as a
JDBC 4.0 compliant driver. Java DB is available at no cost under the Apache
license.
s a
Installing Java DB ) h a
m x
Java DB is bundled with many Sun products, including the Java t g ob
Development Kit
s aalso download
(JDKTM) 6, NetBeansTM, and GlassFish products. You can
install Java DB separately from a l @ Guide and
b e rn ent
http://developers.sun.com/javadb/downloads/index.jsp.
s t o tud
e r ne his S
Note Running an external z (instanceeoftJava DB for testing and experimentation
n
purposes best simulates
e us environment where an external database
d a realtoproduction
a
rnor MySQL eTM will most likely be used.
e
such as Oracle
n s
n a l H lice
r le Java DB installers are available for the Solaris, Linux, and
ePlatform-specific
b
B
to Windows a
er platforms, but a basic platform independent zip archive is available for
e s s f
E rn -tranunpacking onto any system by any user. On UNIX-like systems, the command
arlos non would typically be unzip javadb-version.zip. Windows system utilities or
C third-party utilities like WinZip can extract zip archives when they are double-
clicked. The zip archive will extract into a javadb directory. To uninstall Java
DB, remove the javadb directory.
After you install Java DB, the following subdirectories are placed in the javadb
directory:
The bin subdirectory contains scripts for starting and stopping Java DB in
client/server configuration, as well as other utility scripts.
The demo subdirectory contains demonstration programs.
The docs subdirectory contains setup, administrator, and reference guides
for the Java DB product.
The javadoc subdirectory contains API documentation. This directory is
particularly useful if you configure your integrated development
environment (IDE) to point to it as the Java DB API Javadoc.
Java DB A-3
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?
Note If you have a full installation of the JDK, you will find JavaDB at
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
JAVA_HOME/db.
Java DB Configurations
Java DB offers two configurations:
Embedded s a
) h a
Client/Server
m x
t g ob
Embedded Configuration s a de
n a l@ Gui
In the embedded configuration, the database is b
er accessible
only e n t from the Java
TM
s
Virtual Machine (JVM ) in which the application
e tud This configuration
to Sexecutes.
provides:
( e rn this
d e z use
Fast access to the database
r n an e to
e ens
Ease of use
H
Non l lic
aadministration
r
e ab l e
o B er DB with the embedded configuration, use the Derby Embedded
t To runsfJava
e s
E rn -trJDBCan driver found in derby.jar. Loading the JDBC driver starts the embedded
s non engine. Making a connection request to a database starts the database if it was not
C arlo already running. No other startup code is needed.
A-4 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?
s a
) h a
m x
t g ob
s a de
a l@ Gui
Figure 13-1 Java DB Using the Embedded Configuration
n
b er dent
e
Load the JDBC driver by referencings to StuClass.forName method. The
it using the
( e rn this
embedded driver name is org.apache.derby.jdbc.EmbeddedDriver.
d e z use
an to
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection dbConnectioner=nnull;se
a l H icen
String url = "jdbc:derby:auction;user=dbuser;password=dbuserpwd";
try { e rn ble l
t o
dbConnectionB e= rDriverManager.getConnection(url);
a
s s f
E ne (SQLException
} catch
t r a n
rsqle.printStackTrace(); sqle) {
r l o s} non-
C a
Java DB A-5
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
What Is Java DB?
s a
) h a
m x
t g ob
s a de
Figure 13-2 Java DB Using the Client/Server Configuration
n a l@ Gui
b er dent
On the server, start the Network Serverewith s tothe provided
S tu scripts.
n
javadb\bin > startNetworkServer z (er e this
Apache Derby Network Server - 10.5.1.1
a n
de to- ustarted
s and ready to accept
connections on port 1527 er n se
l H e n
r n aclient
l e lic use the Derby network client driver, found in
From
B e ab
the application,
e s t o f er
derbyclient.jar.
s
The client driver name is
E rn -tran org.apache.derby.jdbc.ClientDriver.
s non
C arlo If you include create=true in the JDBC connection string, the database will be
created by the first client to connect to the database if the database doesnt
already exist. All subsequent connections will connect to the existing database.
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection dbConnection = null;
String url = "jdbc:derby://localhost:1527/auction;create=true";
String user = "dbuser";
String password = "dbuserpwd";
try {
dbConnection = DriverManager.getConnection(url, user, password);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
A-6 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Appendix B
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
B-1
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Additional Resources
Additional Resources
The following references provide additional information on the topics described
in this module:
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
t g ob September 1, 2009.
Sun Microsystems, JSR 318: Enterprise JavaBeans, s a d3.1
Version e
[http://jcp.org/en/jsr/detail?id=318], al@accessed i
u September
1, 2009. r n
e den t G
o b
n e st S tu
z (er e this
an
de to us
e rn nse
n a l H lice
B er able
e s to sfer
E rn -tran
arlos non
C
B-2 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the JavaTM Platform, Enterprise Edition (Java EE)
A set of specifications
The primary specification for the Java EE platform is Java Platform,
Enterprise Edition 6 (Java EE 6) Java Specification Request 316 (JSR 316).
Secondary specifications for the Java EE 6 platform cover specific
technology areas of the platform, such as:
s a
Web services technologies
) h a
m x Web application technologies
Enterprise application technologies
t g ob
Management and security technologies l@s
a de
n a G ui
r entechnology
Table 13-5 lists the specifications for theedifferent
b t areas of the
o d
Java EE 6 platform.
n e st S tu
Table 13-5 Java EE 6 Technology Specifications
z (er e this
a n
de to us
Technology Area
e rn Specification
n s e Name JSR
n a l H licJava
Web services technologies
e Application Programming Interface (API) for JSR 311
B er able RESTful Web Services (JAX-RS) 1.1
e s to sfer
E rn -tran Implementing Enterprise Web Services 1.3 JSR 109
arlos non Java API for XML-Based Web Services (JAX-WS) JSR 224
C 2.2
Java Architecture for XML Binding (JAXB) 2.2 JSR 222
Web Service Metadata for the Java Platform JSR 181
Java API for XML-Based RPC (JAX-RPC) 1.1 JSR 101
Java APIs for XML Messaging 1.3 JSR 67
Java APIs for XML Registries (JAXR) 1.0 JSR 93
Web application technologies Java Servlet 3.0 JSR 315
JavaServer TM Faces (JSF) 2.0 JSR 314
JavaServer PagesTM (JSPTM) 2.2/Expression JSR 245
Language (EL) 1.1
A Standard Tag Library for JavaServer Pages 1.2 JSR 52
o s
Java
o n -tSpecs in Java Java API for XML Processing (JAXP) 1.3
EEE-related JSR 206
l
ar SE n
C
Java Database Connectivity 4.0 JSR 221
Java Management Extensions (JMX) 2.0 JSR 255
JavaBeans Activation Framework (JAF) 1.1 JSR 925
Streaming API for XML (StAX) 1.0 JSR 173
B-4 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Introducing the JavaTM Platform, Enterprise Edition (Java EE)
interfaces.
Java BluePrints
The Java BluePrints provide guidelines and best practice information
on the application of Java EE 6 technologies.
API documentation (JavadocTM)
The API documents the Java EE 6 technology classes, interfaces,
s a
annotations and exceptions.
) h a
m x
t g ob Commercial and open-source Java EE application servers and tools
Commercial and open-source Java EE servers are available
s a asdealternatives
a l@ Gu
to GlassFish. The availability of these commercial or i
open-source servers
n
r entdeveloped to the
prevents vendor exclusivity. That is, anyeapplication
b
o executetuonda different application
specification can be easily portedtto
server. e s
n his S
e r
( applications
t
Java EE components e zand s e
n a ndof providing
t o u
The end purpose
e r s e the Java EE 6 platform is to enable the
n components that can be packaged to create enterprise
a l H ofisoftware
creation
c e
l
B ern applications.
a b le
s to sfeTher pool of available third-party commercial and open-source Java EE
e
rn -tran applications and component libraries is increasing.
E
arlos non
C
n a
b er dent
Figure 13-3 Generic Component-Container
e s to Architecture
S tu
n is
z (er e tharchitecture
d e u s
The key features of the component-container are:
r
The separation n aofnapplication-specific
e to functionality and application generic
e n s
n a l H lice
functionality.
r
eComponentsb le house application-specific functionality.
B a
er house the generic functionality common to all enterprise
to sContainers
e s f
E rn -tran applications.
arlos non Containers provide:
C An execution environment for components
Services for components
B-6 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture
Applet
Container
Java EE
Server
EJB Container
s a
h a
m x)
Database
Browser
t g ob
Web Container s a de
n a l@ Gui
b er dent
e s to Stu
Application ( e rn this
Client
d e z use
Container
r n an e to
Figure 13-4e Java EE
l H c e nsApplication Architecture: Generic Elements
e r na le li
t o f ablists the containers used by Java EE applications, the components
B Tablee13-6
r
r n es ranhosted
s by each container, and the machines (client or server) that host the
s E n-t containers.
ar l o no
C Table 13-6 Java EE Platform Containers
Web browser Web pages Web browser is hosted by the client machine.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
s a
Figure 13-5 shows the Java EE application architecture with the inclusion of the
) h a
application function-specific components.
m x
Applet
Container t g ob
s a de
n a l@ Gui
Java EE b er dent
ServerApplet
e s to EJB S tuContainer
n
z (er e this
an
de to us
e rn nse Database
er able
Browser
o B r Web Container
n e st nsfe
s Er n-tra
C arlo no Application Client
Application
Client
Container
B-8 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture
b e dent a
JSP Web container JSP pagess o text-based
tare tu documents that embed Java
r n e S
is execute as servlets to create
( e
technology
z dynamic tcode
h and
econtent for display on a browser.
n d e u s
Application client r
Applicationn aclient e o
tApplication client components model client code
component e s
H icen and execute in an application client container.
container
a l l
Applet e rn Applet
b l e
container Applets model client code and execute in an applet
B
to sfer a container.
e s
E rn -tran
s non
C arlo Examining Java EE Container Services
The Java EE component model relies on both container-based and platform
services for ancillary functionality that is not directly related to the application
business logic. The Java EE platform goes beyond the traditional middleware
server in terms of the range of services that it offers and the generality of
applications that can be supported.
B-10 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examining the Java EE Application Architecture
These services include Simple Object Access Protocol (SOAP) for the
Java application, SOAP with Attachments API for Java (SAAJ),
JAXR, and JAX-RPC. Together these services enable Java EE
software applications to respond to and to initiate XML-based RPC
and messaging operations, which provides a full web services
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
platform.
Java Management Extensions API
This API exposes the internal operation of the application server and
its components for control and monitoring vendor-neutral
management tools.
Timer services
s a
h a
m x)
These services provide the ability to run scheduled background tasks.
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
B-12 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examine the EJB Application Creation Process
4. Use session beans to model the server-side business logic and synchronous
service faade for the server-side components.
In practice, this step requires an in-depth analysis of the server-side
business logic requirements. This step includes the application of Java EE
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
B-14 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Examine the EJB Application Creation Process
Application Application
Component Provider Assembler
Assemble
TM
- Client Module
Application - EJB Component
Components Module
TM - Web Module
s a
- Resource Module
) h a
m x
ob
Application
t
a de g Server
s
Deployer Deployment
n a l@ Gui
Applications
Tool
b e r ent R
RAR JAR t o t u d EA
<ejb-
s
ne his S
WAR
( e r t
TM
TM
e z s e
n a nd to u
e
erJavaeEEnsApplication
a H
Figure l13-6
i c Development Process
l
B ern able
s t o sfeTher roles shown in Figure 13-6 are described in Table 13-8.
r n e ran
E t EE Platform Roles
Table 13-8n-Java
s
ar l o n o
C Role Primary Function
Application Component The multiple roles for Application Component Providers include
Provider HTML document designers, document programmers, and enterprise
bean developers. These roles use tools to produce Java EE
applications and components.
Application Assembler The Application Assembler takes a set of components developed by
Application Component Providers and assembles them into a
complete Java EE application delivered in the form of an Enterprise
Archive (EAR) file.
Deployer The Deployer is responsible for deploying application clients, web
applications, and EJB components into a specific operational
environment.
The Deployers primary tasks are installation into a specific server,
configuration, and application execution startup.
System Administrator The System Administrator is responsible for the configuration and
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
B-16 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A
Comparing Java EE Application Development With Traditional Enterprise
components from the general services and infrastructure. One of the main
benefits of the Java EE platform for the application developer is that developers
can focus on the application business logic while leveraging the supporting
services and platform infrastructure provided by the container and application
server vendor. For example, in an online banking application, the application
component developers need to code the logic that underlies the transfer of funds
from one account to another, but they do not need to be concerned about
s a
managing database concurrency or data integrity in the event of a failure. The
) h a
m x application server infrastructure and services are responsible for these functions.
g b
odeveloper
a t
Figure 13-7 contrasts the tasks that are required of an application who
s
builds all aspects of an application and supporting services to those
@for G ideand
of a
developer who relies on an application component n a l
server u
service platform
e r n t
level functions.
t o b tude
Build From the Ground Up
r n es is Developers
S Checklist
(
z usee t h
n d e Business services
n a t o Persistence
r n al e lic Multi-threading
to sfer
Networking
n e s n Service publishing
Er n-tra
TM
rlo s no
C a Use Application Component Server Developers Checklist
Business services
Services Provided
by Server
Persistence
Transaction management
Multi-threading
TM
Security management
Networking
Service publishing
As you can see, relying on a component server for application support services
dramatically reduces the amount of coding required of the application component
developer.
Unauthorized reproduction or distribution prohibited Copyright 2013, Oracle and/or its affiliates
s a
) h a
m x
t g ob
s a de
n a l@ Gui
b er dent
e s to Stu
( e rn this
d e z use
r n an e to
H e ens
n l
a e lic
r
e abl
B
to sfer
e s
E rn -tran
s non
C arlo
B-18 Building Database Driven Applications with the Java Persistence API
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision A