Professional Documents
Culture Documents
WhatsNewInJpa2.0 - 3201 rc128 010d Jpa2 - 0 PDF
WhatsNewInJpa2.0 - 3201 rc128 010d Jpa2 - 0 PDF
com
#128
Whats New in
CONTENTS INCLUDE:
n
Introduction
JDBC Properties
Access Mode
Mappings
Shared Cache
Additional API and more...
JPA 2.0
By Mike Keith
@Entity @Access(FIELD)
public class Person {
@Id
int id;
@Access(PROPERTY)
public String getName() { }
public void setName(String pName) { }
INTRODUCTION
Hot
Tip
MAPPINGS
JDBC PROPERTIES
Element Collections
Arguably, the most useful of the new mapping types is the
element collection, which allows an entity to reference a
collection of objects that are of a basic type (such as String
or Integer). The @ElementCollection annotation is used to
indicate the mapping. The objects are stored in a separate
table called a collection table, which defaults to be named
<entityName>_<attributeName>, but can be overridden
with the @CollectionTable annotation. The name of the
column in the collection table that stores the values defaults
<properties>
<property name=javax.persistence.jdbc.driver
value=org.apache.derby.jdbc.ClientDriver/>
<property name=javax.persistence.jdbc.url
value=jdbc:derby://dbmachine:1527/accountDB/>
<property name=javax.persistence.jdbc.user value=app/>
<property name=javax.persistence.jdbc.password
value=app/>
</properties>
</persistence-unit>
ACCESS MODE
DZone, Inc.
www.dzone.com
@ElementCollection
@CollectionTable(name=NICKNAMES)
@Column(name=NNAME)
Collection<String> nicknames;
library.getMagazines().remove(magazine);
@OneToMany
@OrderColumn(name=POSITION)
List<Customer> customer;
Maps
Using a Map for a many-valued relationship traditionally
meant that entities were the values and some attribute of
the entities was the key. The new Map features allow Map
types to be used with keys or values that can be basic types,
entities, or embeddables. When the value is an entity type,
then the mapping is a relationship. When the value is a basic
or embeddable type, the mapping is an element collection.
Two examples of using a Map are shown. The deliverySchedule
attribute is an element collection of dates on which deliveries are
made to given address strings. The @MapKeyColumn annotation
indicates the column in the collection table where the keys
(address strings) are stored, and @Column references the column
in which the date values are stored. The @Temporal annotation is
used because the values are Date objects.
@OneToMany
@JoinColumn(name=CUST_ID)
List<Purchase> purchases;
Hot
Tip
Orphan Removal
A parent-child relationship is a one-to-many or one-to-one
relationship in which the target entity (the child) is owned by the
source entity (the parent) or relies upon it for its existence. If
either the parent gets deleted or the relationship from the parent
to the child gets severed, then the child should be deleted.
Previous support for cascading delete offered a solution for the
first case; but to solve the second case when the child is left an
orphan, the new orphanRemoval element of the @OneToMany
or @OneToOne annotations can be set to true to cause the child
object to get removed automatically by the provider.
@ElementCollection
@CollectionTable(name=ASSY_DLRVY)
@MapKeyColumn(name=ADDR)
@Column(name=DLRVY_DATE)
@Temporal(TemporalType.DATE)
Map<String, Date> deliverySchedule;
@OneToMany
@JoinTable(name=PART_SUPP)
@MapKeyJoinColumn(name=PART_NO)
Map<Part, Supplier> suppliers;
@OneToMany(mappedBy=library, orphanRemoval=true)
List<Magazine> magazines;
DZone, Inc.
www.dzone.com
Derived Identifiers
NULLIF, COALESCE
New allowances were made in JPA 2.0 for the case when an entity
has a compound primary key that includes a foreign key. Multiple
@Id annotations can be specified, and they can be on an owned
one-to-one or many-to-one mapping. The foreign key of that
mapping will be included in the id class, as shown in the example.
The id class must still have a field for each of the primary key
components and be named the same as the entity attributes,
but the types of the foreign key-based id class fields must match
the identifier types of the target entity of the relationship. For
example, the dept field in the ProjectId class is not of type
Department as it is in Project, but is of type int, which is the
identifier type of the Department entity.
NULLIF(scalarExpr, scalarExpr)
Scalar expressions in
the SELECT clause
INDEX in a List
Variables in SELECT
constructors
Constructors in SELECT
clause can contain
identification vars
Derived Identifier:
TYPED QUERY
@IdClass(ProjectId.class)
@Entity public class Project {
@Id
String projectName;
One of the simplest but most useful query features added in JPA
2.0 is the TypedQuery interface. When you create a query you can
pass in the type for the query result and get back a typed query
object that, when executed, will return the correctly typed objects
without having to cast. It works for both dynamic queries and
named queries.
@Id @ManyToOne
Department dept;
}
@Entity public class Department {
@Id
int id;
}
public class ProjectId {
String projectName;
int dept;
TypedQuery<Employee> q = em.createNamedQuery(Employee.findByName,
Employee.class);
q.setParameter(empName, Smith);
List<Employee> emps = q.getResultList();
Hot
Tip
SHARED CACHE
Description
Example
Non-polymorphic
queries TYPE
Collection input
parameters
CASE statement
2) CASE pathExpr
{WHEN scalarExpr THEN
scalarExpr}+ ELSE scalarExpr
END
DZone, Inc.
Hot
Tip
Option
Description
ALL
NONE
ENABLE_SELECTIVE
DISABLE_SELECTIVE
UNSPECIFIED
www.dzone.com
Hot
Tip
Description
USE
BYPASS
Dont use the cache; read entity data from the database
CacheStoreMode Value
Description
USE
BYPASS
REFRESH
Parameter<T>
PersistenceUnitUtil
PersistenceUtil
PersistenceProviderResolver
PersistenceProviderResolverHolder
PESSIMISTIC LOCKING
ADDITIONAL API
Lock Modes:
Description
lock(Object entity,
Map<String,Object> properties)
refresh(Object entity
[,LockModeType lockMode]
[,Map<String,Object> properties])
detach(Object entity)
createQuery(String qlString,
Class<T> resultClass)
createQuery(CriteriaQuery<T>
criteriaQuery)
createNamedQuery(String
queryName, Class<T> resultClass)
unwrap(Class<T> cls)
getEntityManagerFactory()
getCriteriaBuilder()
getMetamodel()
Description
TypedQuery<T>
Tuple
TupleElement<T>
DZone, Inc.
OPTIMISTIC_FORCE_INCREMENT
PESSIMISTIC_READ
PESSIMISTIC_WRITE
PESSIMISTIC_FORCE_INCREMENT
VALIDATION
Additional Classes:
Class
OPTIMISTIC
www.dzone.com
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery c = cb.createQuery(Account.class);
Root acct = c.from(Account.class);
c.select(acct)
.where(cb.equal(acct.get(name), Jim Morrison));
List result = em.createQuery(c).getResultList();
CRITERIA API
Hot
Tip
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> c = cb.createQuery(Account.class);
Root<Account> acct = c.from(Account.class);
c.select(acct)
.where(cb.equal(acct.get(Account_.name), Jim Morrison));
List<Account> result = em.createQuery(c).getResultList();
There are two flavors of criteria usage. The one you will use
depends on the reason you are using the API, the development
practices of your company, and personal preference.
STRING-BASED CRITERIA
DZone, Inc.
CRITERIABUILDER
www.dzone.com
createQuery(), createTupleQuery()
String Operations
Selection Construction
Ordering
asc(), desc()
Temporal Functions
Aggregate Functions
Expression Construction
in(), selectCase()
Misc Operations
Subqueries
Boolean Functions
Value Testing
Equality
equal(), notEqual()
Numeric Comparison
Comparison
Numeric Operations
Typecasts
Literals
literal(), nullLiteral()
Aldon
RECOMMENDED BOOK
efer
ion
the not
s on
BUY NOW
http://apress.com/book/view/9781430219569
By Daniel Rubio
dz. com
HTML
LUD E:
Basics
ref car
L vs XHT technologies
Automated growthHTM
& scalable
ION
EGRAT
Valid
ML
Vis it
RichFaces
CSS3
Windows Azure Platform
REST
Structur
Elem
al Elem ents
rdz !
to isolat
space
n
e Work
riptio
itory
a Privat
Desc
ge
These companies
have
webmana
applications
are in long deployed
trol repos
to
n-con
lop softw
ing and making them
Deve
a versio
that adapt
and scale
bases,
rn
les toto large user
ize merg
Patte
it all fi
minim
le
space
Comm
ine to
tos multip
cloud
computing.
e Work knowledgeable in amany
mainl aspects related
Privat
that utilize
lop on
Deve code lines
a system
sitory
of work
active
Repo
are within
d units
This Refcard
will introduce
to you to cloud
softw
riente computing, with an
loping
ine
task-o it
e
Mainl
es by
emphasis onDeve
these
so
youComm
can better understand
ines providers,
INT
softwar
chang
codel
e code
ding
OUS
Task Level
sourc es as aplatform
what it is a cloudnize
computing
can offer your
ut web
line Policy
s of buil
NTINU
control
Orga
Code
e witho
it chang
ces
name
CO
ion
e
sourc
subm
T
and
applications.
it
the pro jects vers
are from
with uniqu
ABOU
softw
(CI) is
um
the build
evel Comm
build
a pro
minim
Label
Task-L
ies to
bare
gration
ed to
blem
all activition
to the
Inte
mitt
pro
ate
cies
a
t
ous
com
USAGE SCENARIOS
to
Autom configurat
nden
ymen
Build
depe
al
tion
deplo
t
Continu ry change
manu
Label
d tool
nmen
a solu ineffective
the same
stalle
)
Build
eve
t, use target enviro
(i.e.,
,
ated
ce pre-in
blem
with
ymen
Redu
Autom
terns
ns (i.e.
ory.
d deploEAR) in each
lar pro that
tagge
via pat
or
cies
-patter
s
reposit
particu
t
nden
For each (e.g. WAR
es
lained ) and anti
al Depeapplication deployment
ge
x the are solution duce
t librari
Web
until
agonmen
was similar
t enviro
packa
Minim
be exp
nden a few years
text
to fi
targe
to pro
rity
all depe
tterns
can
that all
used
CI can ticular con
Integ
le
alize
tend
fi
y
es
i-pa
to most phone services:
plans with
but
late alloted resources,
Centr
Binar
ts with an
etim
, they
temp
s. Ant
nt
nmen
ctices,
in a par hes som
geme
t enviro
e a single based on
incurred
cost
whether
were
consumed
or
proces in the end bad pra
enting
thenot.
Creatsuchareresources
cy Mana
nt targe
es to
rties
rily
nden
implem
approac ed with the cial, but,
chang
prope
Depe
to
essa
into differe
itting
d
er
nec
efi
te builds
pare
e comm
late Verifi
associat to be ben
befor
etc.
are not
Cloud
computing asRun
itsremo
known etoday
has changed this.
Temp
n com
Build
ually,
They
Privat
lts whe
y, contin
appear effects.
rm a
nt team
dicall
The various
resourcesPerfo
consumed
by webperio
applications
(e.g.
opme
ed resu
d Builds
sitory
Build
gration
r to devel
Repo
Stage
adverse unintend
ration on a per-unit
bandwidth,
memory, CPU)
areInteg
tallied
basis
CI serve
e
ous Inte
e Build
rm an
ack from
produc
Privat
Continu Refcard
feedb computing platforms.
on
(starting
from zero) by Perfo
all majorated
cloud
tern.
occur
term
this
pat
based
they
tion
autom
e,
as
as
the
the
builds
Build
gra
Send
of
soon
cycl
such
ration
ion with
ors as
Integ
entat
ous Inte tional use and test concepts
docum
oper
Continu conven
build include
devel
the
the
rate
to
to
s
Gene
While
of CI
expand
Cloud#64Computing
ge. Colla
Chan
Re fca
HTM
L BAS
Core
HTML
Ge t Mo
re
SUMMARY
By An
dy Ha
rris
DZone, Inc.
140 Preston Executive Dr.
Suite 100
Cary, NC 27513
ISBN-13: 978-1-936502-03-5
ISBN-10: 1-936502-03-8
50795
888.678.0399
919.678.0300
Refcardz Feedback Welcome
refcardz@dzone.com
Sponsorship Opportunities
sales@dzone.com
$7.95
Ge t
Mo re
Re fca
rd z!
Vis it
e.com
CONTENTS INCLUDE:
Cost
by...
youTechnologies
Data
t toTier
Comply.
brough
Platform Management and more...
borate.
on:
grati s
s Inte -Patternvall
nuou d AntiBy Paul M. Du
ContiPatterns an
www.dzone.com
ref c
Cloud Computing
Collection Operations
Map Operations
#82
parameter()
Method Names
Parameters
Category
E:
INC LUD gration
NTS
ous Inte Change
CO NTE
Continu at Every
ns
About
Software i-patter
Build
and Ant
Patterns Control
ment
Version
e...
Manage s and mor
Build
Practice
Build
9 781936 502035
Version 1.0