8/17/2019 Java EE Lecture
1/74
1
8/17/2019 Java EE Lecture
2/74
Week 2
Object-Relational Mapping
2
8/17/2019 Java EE Lecture
3/74
The slides in this presentation aredeveloped from:
Chapter 5 Object-Relational Mapping (page125 to 159)
Beginning Java EE 7ntonio !oncalve"
pre""#
3
A CKNOWLEDGMEN
TS
8/17/2019 Java EE Lecture
4/74
4
OBJECTIVES
Interpret the basics of object-relationalmapping (OR! in terms of ho# attrib$tesand relationships are mapped from a
domain model to a database% &evelop di'erent mappings $sing )*
annotations or +, mapping descriptors%
Investigate di'erent #as for comple.relationship mappings%
8/17/2019 Java EE Lecture
5/74
/
ORM B ASIC R ULES
The entit class m$st be annotated #[email protected] annotation%
Or denoted in an +, descriptor as an entit @javax.persistence.Id annotation m$st
be $sed to denote a simple primar 0e%
The entit class m$st have a no-arg
constr$ctor that has to be p$blic orprotected% The entit class ma have other constr$ctors
as #ell%
8/17/2019 Java EE Lecture
6/74
ORM B ASIC R ULES
The entit class m$st be a top-level class% *n en$m or interface cannot be designated as
an entit%
The entit class m$st not be nal% o methods or persistent instance variables of
the entit class ma be nal%
If an entit instance has to be passed bval$e as a detached object (e%g% thro$gha remote interface! the entit class m$stimplement the Serializable interface%
8/17/2019 Java EE Lecture
7/74
5
ORM B ASIC R ULES
The mapping of the Book entit
8/17/2019 Java EE Lecture
8/74
6
ORM B ASIC R ULES
7ince the 8oo0 entit follo#s these simpler$les the persistence provider can 7nchronise the data bet#een the attrib$tes
of the 8oo0 entit and the col$mns of the8OO9 table%
%g% if the attrib$te isbn is modied b theapplication the I78 col$mn #ill be
snchronised provided:o The entit is managedo The transaction conte.t is set
8/17/2019 Java EE Lecture
9/74
;
CONFIGURATION BY
EXCEPTION
8/17/2019 Java EE Lecture
10/74
1>
CONFIGURATION BY
EXCEPTION ?itho$t an annotation the 8oo0 entit#o$ld be treated j$st li0e a )OO and notbe persisted%
?ith @Entity the entit is persisted% ?ith @Id the id attrib$te has to be
mapped to a primar 0e%
@or all the other attrib$tes: The entit name is mapped to a relationaltable nameo e%g% the 8oo0 entit ↔ the 8OO9 table
*ttrib$te names are mapped to col$mn
8/17/2019 Java EE Lecture
11/74
11
CONFIGURATION BY
EXCEPTION &8A r$les appl for mapping avaprimitives to relational data tpes% 7tring↔ B*RA=*R(2//!
,ong ↔ 8ICIT 8oolean ↔ 7*,,IT
&efa$lt mapping r$les are di'erentfrom one database to another%
* 7tring is mapped to a B*RA=*R in &erbb$t a B*RA=*R2 in Oracle%
*n Integer is mapped to an ITCR in &erband a
8/17/2019 Java EE Lecture
12/74
12
T ABLE
R$les for cong$ration-b-e.ceptionmapping state that the entit and thetable name are the same%
Do$ ma #ant to map data to a di'erenttable or even map a single entit tom$ltiple tables%
The @javax.persistence.Tableannotation ma0es it possible to changethe defa$lt val$es related to the table% The name of the table
The catalog and the database schema @UniqueConstraint in conjunction it!
8/17/2019 Java EE Lecture
13/74
13
T ABLE
The Book entit being mapped to a T"B##$ table
8/17/2019 Java EE Lecture
14/74
14
SECONDARY T ABLE
*n entit can be mapped to a single table(primar table!%
&ata can be spread across m$ltiple tables
(secondar tables!%o
8/17/2019 Java EE Lecture
15/74
1/
SECONDARY T ABLE
*ttrib$tes of the &ddress entit aremapped into three di'erent tables%
8/17/2019 Java EE Lecture
16/74
1
SECONDARY T ABLE
ach table contains di'erent attrib$tesb$t the all have the same primar 0e (to
join the tables together!%
8/17/2019 Java EE Lecture
17/74
15
PRIMARY K EYS
In relational database a primar 0e$niE$el identies each ro# in a table%
It comprises either a single col$mn or set
of col$mns% )* reE$ires entities to have an identier
mapped to a primar 0e%
8/17/2019 Java EE Lecture
18/74
16
PRIMARY K EYS
@javax.persistence.Id annotates anattrib$te as being a $niE$e identier%
The val$e of this identier can be
generated an$all b the application *$tomaticall b the persistence provider
$sing the @'enerated(alue annotation%
If the @'enerated(alue annotation is notdened the application has to create itso#n identier b appling an algorithmthat #ill ret$rn a $niE$e val$e%
8/17/2019 Java EE Lecture
19/74
1;
PRIMARY K EYS
The Book entit #ith an a$tomaticallgenerated identier
8/17/2019 Java EE Lecture
20/74
2>
COMPOSITE PRIMARY
K EYS It is a good practice to designate a singlededicated col$mn as the primar 0e% There are cases #here a composite
primar 0e is reE$ired% apping to a legac database )rimar 0es have to follo# certain b$siness
r$leso * date and a val$e or a co$ntr code and a
time stamp need to be incl$ded% @or e.ample
The A&-8oo07tore application needs to postne#s%
The ne#s has content a title and a lang$agecode%
8/17/2019 Java EE Lecture
21/74
21
COMPOSITE PRIMARY
K EYS The primar 0e class )esId is composedof t#o attrib$tes of tpe 7tring: title andlang$age%
)rimar 0e classes m$st incl$de method
denitions for equals*+ and !as!Code*+% The m$st also be p$blic and have a no-
arg constr$ctor% The m$st implement serialiHable if need
to cross architect$ral laers (e%g%persistence presentation!
The primar 0e class is annotated #ith
Jmbeddable%
8/17/2019 Java EE Lecture
22/74
22
COMPOSITE PRIMARY
K EYS The entit )es embeds the primar 0eclass #ith @E%beddedId annotation%
ver JmbeddedId m$st refer to anembeddable class
7implied code to nd an entit thro$ghits composite primar 0e%
8/17/2019 Java EE Lecture
23/74
23
A TTRIBUTES
* primar 0e (simple or composite! is am$st an entit
*n entit has all sorts of di'erentattrib$tes ma0ing $p its state that haveto be mapped to the table%
This state can incl$de almost ever ava
tpe: ava primitive tpeso int do$ble Koat etc%
The #rapper classes of primitive java tpeso Integer &o$ble @loat etc%
L *rras of btes and characters
8/17/2019 Java EE Lecture
24/74
24
A TTRIBUTES
7tring large n$meric and temporal tpeso java.lan,.Strin,o java.%at!.Bi,Inte,er
java.%at!.Bi,-eci%al java.util.-ate
java.util.Calendar java.sql.-atejava.sql.Ti%e java.sql.Ti%esta%p
n$merated tpes and $ser-dened tpes thatimplement the Serializable interface
Aollections of basic and embeddable tpes *n entit can also have entit attrib$tes collections of entities or embeddable classes%
This reE$ires introd$cing relationships
bet#een entities%
8/17/2019 Java EE Lecture
25/74
2/
A TTRIBUTES
The @javax.persistence.Basicannotation has t#o parameters
(optional and fetch! The val$e of the attrib$te ma be n$ll(optional!
The @etch element can ta0e t#o val$es:o ,*D: data sho$ld be fetched laHil
(onl #hen the application as0s forthe propert!
o *CR: data sho$ld be fetched
eagerl (#hen the entit is initiall
8/17/2019 Java EE Lecture
26/74
2
A TTRIBUTES
The Track entit #ith azy loading on the#av attrib$te
8/17/2019 Java EE Lecture
27/74
8/17/2019 Java EE Lecture
28/74
26
A TTRIBUTES
A$stomising mapping for the Book entit
8/17/2019 Java EE Lecture
29/74
2;
A TTRIBUTES
@javax.persistence.Te%poralannotation has three possible val$es:
&*T TI or TI7T*) %ap java.util.-ate and
java.util.Calendar represent date ho$r or second
8/17/2019 Java EE Lecture
30/74
3>
A TTRIBUTES
*nnotated #ith @Entity all attrib$tes area$tomaticall mapped to a table%
?hile no need to map an attrib$te $se
the @javax.persistence.Transient*@Transient+ annotation or the javatransient 0e#ord%
@or e.ample in the A$stomer entit *ge can be calc$lated from the date of birth% The age attrib$te does not need to be
mapped% Therefore the age attrib$te can be transient%
8/17/2019 Java EE Lecture
31/74
31
A TTRIBUTES
The Custo%er entit #ith a Transient age
8/17/2019 Java EE Lecture
32/74
32
A TTRIBUTES
The en$meration tpes are no# sofreE$entl $sed
The val$es of an en$m *re constantsF =ave an implicit ordinal assignment that is
determined b the order in #hich the aredeclared%
This ordinal cannot be modied at r$ntime b$tcan be $sed to store the val$e of theen$merated tpe in the database%
8/17/2019 Java EE Lecture
33/74
33
A TTRIBUTES
In the follo#ing AreditAard entit and #iththe defa$lt mapping The ordinals assigned to the val$es of this
en$merated tpe at compile time are > forBI7* 1 for *7TRPA*R& and 2 forRIA*P+)R77%
The persistence providers #ill map thisen$merated tpe to the database ass$mingthat the col$mn is of tpe Integer%
8/17/2019 Java EE Lecture
34/74
34
A TTRIBUTES
A
8/17/2019 Java EE Lecture
35/74
3/
A TTRIBUTES
In the follo#ing AreditAard entit and #iththe defa$lt mapping The ordinal assignment is determined b the
order in #hich val$es are declared% If introd$cing a ne# constant to the top of the
en$meration the val$es alread stored in thedatabase #ill no longer match theen$meration%
* better sol$tion #o$ld be to store thename of the val$e as a string #ith@Enu%erated annotation instead ofstoring the ordinal%
A
8/17/2019 Java EE Lecture
36/74
3
A TTRIBUTES
apping an en$merated tpe #ithStrin,
A
8/17/2019 Java EE Lecture
37/74
35
A TTRIBUTES
@Ele%entCollection annotation is $sedto indicate that an attrib$te contains acollection of instances of basic tpes or
embeddables java.util.Collection java.util.Set java.util.ist
@CollectionTable annotation allo#s toc$stomise details of the collection tables$ch as its name%
8/17/2019 Java EE Lecture
38/74
A
8/17/2019 Java EE Lecture
39/74
3;
A TTRIBUTES
Relationship bet#een the 8OO9 and the T*C tables
M XML
8/17/2019 Java EE Lecture
40/74
4>
M APPING WITH XML
)* also o'ers an +, snta. to mapentities%
ver single annotation has an +,
eE$ivalent% If both is $sed +, overrides annotations%
(the length of the QdescriptionG col$mn(slide 42! in +, mapping #ill override
that declared in Jntit (slide 41! ItGs a matter of taste as the behavio$r of
both is e.actl the same% etadata (e%g% col$mn length! can be
chan ed de endin on
M XML
8/17/2019 Java EE Lecture
41/74
41
M APPING WITH XML
This ma be better e.pressed in e.ternal+, deploment descriptors
7o the code doesnGt have to be modied%
M XML
8/17/2019 Java EE Lecture
42/74
42
M APPING WITH XML
The mapping le /ET&0I)12book"%appin,.x%l
M XML
8/17/2019 Java EE Lecture
43/74
43
M APPING WITH XML
B##$"3/"/&44I)' table str$ct$re
In persistence%.ml le o$ need to
reference the book"%appin,.x%l le% The persistence.x%l denes
The entit persistence conte.t The database it sho$ld be mapped to
8/17/2019 Java EE Lecture
44/74
E S
8/17/2019 Java EE Lecture
45/74
4/
EMBEDDABLES
mbeddables are objects that donGt have apersistent identit on their o#n%
The can be embedded onl #ithin o#ningentities%
The o#ning entit can have collections ofembeddables or a single embeddable
attrib$te% The are stored as an intrinsic part of ano#ning entit and share the identit of thisentit%
ach attrib$te of the embedded object is
EMBEDDABLES
8/17/2019 Java EE Lecture
46/74
4
EMBEDDABLES
The @E%beddable annotation species that&ddress can be embedded in anotherentit class (or another embeddable!%
mbeddables donGt have a persistent
identit on their o#n
EMBEDDABLES
8/17/2019 Java EE Lecture
47/74
45
EMBEDDABLES
The Custo%er entit $ses the @E%bedded annotation to specif &ddress is a persistentattrib$te that #ill be stored as an intrinsicpart and share its identit%
Structure of the CUSTOMER table
with all ADDRESS attributes
RELATIONSHIP MAPPING
8/17/2019 Java EE Lecture
48/74
46
R ELATIONSHIP M APPING
Object-oriented programming abo$nds#ith classes and associations bet#eenclasses%
These associations lin0 objects and allo#
one object to ca$se another to perform anaction on its behalf%
*n association has a direction
8/17/2019 Java EE Lecture
49/74
4;
R ELATIONSHIP M APPING
In ava o$ $se the dot (%! snta. tonavigate thro$gh objects% c$stomer%get*ddress(!%getAo$ntr(!
$nidirectional
bidirectional
8idirectionalassociationrepresented
#ith t#oarro#s
RELATIONSHIP MAPPING
8/17/2019 Java EE Lecture
50/74
/>
R ELATIONSHIP M APPING
*n association also has a m$ltiplicit (orcardinalit!%
ach end of an association can specifho# man referring objects are involved in
the association%
In ava an association that representsmore than one object $ses collections oftpe java.util.Collection5 java.util.Set5
java.util.ist5 or even java.util./ap
RELATIONSHIP MAPPING
8/17/2019 Java EE Lecture
51/74
/1
R ELATIONSHIP M APPING
* relationship has an o#nership (i%e% theo#ner of the relationship!
8/17/2019 Java EE Lecture
52/74
/2
R ELATIONSHIP M APPING
* relational database is a collection ofrelations (also called tables S anthing o$model is a table!%
In )* #hen o$ have an associationbet#een one class and another in thedatabase o$ #ill get a table reference%
This reference can be modelled in t#o
di'erent #as:
8/17/2019 Java EE Lecture
53/74
RELATIONSHIP MAPPING
8/17/2019 Java EE Lecture
54/74
/4
R ELATIONSHIP M APPING
Do$ #o$ldnGt $se a join table torepresent a one-to-one relationship
as this co$ld have performance iss$es @or e.ample o$ al#as need to access
a third table to get the address of ac$stomer%
oin tables are generall $sed #heno$ have one-to-man or man-to-man cardinalities%
8/17/2019 Java EE Lecture
55/74
8/17/2019 Java EE Lecture
56/74
ONE TO ONE
8/17/2019 Java EE Lecture
57/74
/5
ONE-TO-ONE
UNIDIRECTIONAL * one-to-one $nidirectional relationship
bet#een entities =as a reference of cardinalit 1 Aan be reached in onl one direction
*ss$me the c$stomer has onl oneaddress%
It is important to navigate from the
c$stomer to#ard the address% Do$ donGt need to be able to navigate inthe opposite direction ?hich c$stomer lives at a given address
ONE TO ONE
8/17/2019 Java EE Lecture
58/74
/6
ONE-TO-ONE
UNIDIRECTIONAL * Custo%er #ith one &ddress
ONE TO ONE
8/17/2019 Java EE Lecture
59/74
/;
ONE-TO-ONE
UNIDIRECTIONAL *s o$ see in A
8/17/2019 Java EE Lecture
60/74
>
ONE-TO-ONE
UNIDIRECTIONAL The CUST#/E6 Table #ith a foreign 0e
pointing to the &--6ESS table
ONE TO ONE
8/17/2019 Java EE Lecture
61/74
1
ONE-TO-ONE
UNIDIRECTIONAL
To c$stomise the mapping o$ can $set#o annotations%
@#neTo#ne It can modif some attrib$tes of theassociation itself s$ch as the #a it has to befetched%
@7oinColu%n It is $sed to c$stomise the join col$mn -the
foreign 0e of the o#ning side%
ONE TO ONE
8/17/2019 Java EE Lecture
62/74
2
ONE-TO-ONE
UNIDIRECTIONAL The Custo%er entit #ith c$stomised
relationship mapping
ONE TO ONE
8/17/2019 Java EE Lecture
63/74
3
ONE-TO-ONE
UNIDIRECTIONAL
In )* a foreign 0e col$mn is called a joincol$mn%
The @7oinColu%n annotation allo#s toc$stomise the mapping of a foreign 0e% The previo$s e.ample:
Renames the foreign 0e col$mn to &--"1$
a0es the relationship obligator b ref$singthe n$ll val$e (nullable89alse!% Cives the persistence provider a hint to fetch
the relationship laHil%
ONE TO MANY
8/17/2019 Java EE Lecture
64/74
4
ONE-TO-M ANY
UNIDIRECTIONAL ?ith a one-to-man relationship one
so$rce object refers to an ensemble oftarget objects%
@or e.ample a p$rchase order iscomposed of several order lines%
ONE TO MANY
8/17/2019 Java EE Lecture
65/74
/
ONE-TO-M ANY
UNIDIRECTIONAL
The cardinalit is m$ltiple and thenavigation is done onl from Order to#ardOrder,ine%
In ava this m$ltiplicit is described bthe Collection5 ist and Set interfacesof the java.util packa,e%
8/17/2019 Java EE Lecture
66/74
ONE TO MANY
8/17/2019 Java EE Lecture
67/74
5
ONE-TO-M ANY
UNIDIRECTIONAL In the previo$s e.ample a collection of an
entit tpe is being $sed as an attrib$teon this entit triggers:
* OneToan relationship mapping b defa$ltF One-to-man $nidirectional relationshipsF * join table to 0eep the relationship
information #ith t#o foreign 0e col$mns%o One foreign 0e col$mn refers to the table
OR&RFo The other refers to OR&RP,I%
The join table is named OR&RPOR&RP,I(name of both tables separated b the
$nderscore P smbol!%
ONE TO MANY
8/17/2019 Java EE Lecture
68/74
6
ONE-TO-M ANY
UNIDIRECTIONAL oin table bet#een #6-E6 and #6-E6"I)E
ONE TO MANY
8/17/2019 Java EE Lecture
69/74
;
ONE-TO-M ANY
UNIDIRECTIONAL If o$ li0e to rename the defa$lt join table
and foreign 0e names or to c$stomisemapping o$ can $se )* annotations to
redene these defa$lt val$es% The @7oinColu%n annotation can be $sed to
change the foreign 0e col$mns% The @7oinTable annotation can do the same
for the join table mapping% The @#neTo/any annotation c$stomises therelationship itself%
ONE TO MANY
8/17/2019 Java EE Lecture
70/74
5>
ONE-TO-M ANY
UNIDIRECTIONAL The #rder entit #ith annotated One-to-
an relationship
ONE TO MANY
8/17/2019 Java EE Lecture
71/74
51
ONE-TO-M ANY
UNIDIRECTIONAL 7tr$ct$re of the join table
The defa$lt r$le for a one-to-man$nidirectional relationship is to $se a join
table% To change to $sing foreign 0es the #rder entit has to provide a @7oinColu%n annotation instead of a @7oinTable.
ONE TO MANY
8/17/2019 Java EE Lecture
72/74
52
ONE-TO-M ANY
UNIDIRECTIONAL The #rder entit #ith a join col$mn
ONE-TO-MANY
8/17/2019 Java EE Lecture
73/74
53
ONE-TO-M ANY
UNIDIRECTIONAL In the previo$s e.ample: The @#neTo/any annotation is overriding the
defa$lt fetch mode (t$rning it to E&'E6 insteadof &:;!%
8 $sing @7oinColu%n the $nidirectional
association is then mapped $sing the foreign0e strateg% The foreign 0e is renamed to #6-E6"1$ b the
annotation and e.ists in the target table(#6-E6"I)E!%
SUMMARY
8/17/2019 Java EE Lecture
74/74
SUMMARY
The foc$s of this #ee0 is OR% ?ith cong$ration b e.ception not m$ch
is reE$ired to map entities to tables% )* $ses @Entity informs the persistence
provider that a class is an entit% )* $ses @Id informs that an attrib$te is
its identier% )* has a ver rich set of annotations to
c$stomise ever little detail of OR% lementar annotations can be $sed on
attrib$tes or classes to c$stomise the
Top Related