-
Notifications
You must be signed in to change notification settings - Fork 16
/
chap-JPA.lyx
3399 lines (2600 loc) · 67.1 KB
/
chap-JPA.lyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#LyX 1.6.7 created this file. For more info see http://www.lyx.org/
\lyxformat 345
\begin_document
\begin_header
\textclass book
\use_default_options false
\language english
\inputencoding auto
\font_roman default
\font_sans default
\font_typewriter default
\font_default_family default
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100
\graphics default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize default
\use_geometry false
\use_amsmath 1
\use_esint 1
\cite_engine basic
\use_bibtopic false
\paperorientation portrait
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\defskip medskip
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\author ""
\author ""
\end_header
\begin_body
\begin_layout Chapter
JPA Integration
\begin_inset CommandInset label
LatexCommand label
name "cha:JPA-Integration"
\end_inset
\end_layout
\begin_layout Standard
\begin_inset Box Framed
position "t"
hor_pos "c"
has_inner_box 0
inner_pos "t"
use_parbox 0
width "100col%"
special "none"
height "1in"
height_special "totalheight"
status collapsed
\begin_layout Plain Layout
This chapter is still under active development.
The contents will change.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
The Java Persistence API
\begin_inset Foot
status collapsed
\begin_layout Plain Layout
\begin_inset Flex URL
status collapsed
\begin_layout Plain Layout
http://java.sun.com/javaee/overview/faq/persistence.jsp
\end_layout
\end_inset
\end_layout
\end_inset
, or JPA
\begin_inset Index
status collapsed
\begin_layout Plain Layout
JPA
\end_layout
\end_inset
for short, is the evolution of a number of frameworks in Java to provide
a simple database access layer for plain java objects (and, transitively,
Scala objects).
JPA was developed as part of the Enterprise Java Beans 3 (EJB3) specification,
with the goal of simplifying the persistence model.
Prior versions had used the Container Managed Persistence (CMP
\begin_inset Index
status collapsed
\begin_layout Plain Layout
CMP
\end_layout
\end_inset
) framework, which required many boilerplate artifacts in the form of interfaces
and XML descriptors.
As part of the overarching theme of EJB3 to simplify and use convention
over configuration, JPA uses sensible defaults and annotations
\begin_inset Index
status collapsed
\begin_layout Plain Layout
annotations
\end_layout
\end_inset
heavily, while allowing for targetted overrides of behavior via XML descriptors.
JPA also does away with many of the interfaces used in CMP and provides
a single
\family typewriter
javax.persistence.EntityManager
\family default
\begin_inset Index
status collapsed
\begin_layout Plain Layout
EntityManager
\end_layout
\end_inset
class for all persistence operations.
An additional benefit is that JPA was designed so that it could be used
both inside and outside of the Enterprise container, and several projects
(Hibernate
\begin_inset Index
status collapsed
\begin_layout Plain Layout
Hibernate
\end_layout
\end_inset
, TopLink
\begin_inset Index
status collapsed
\begin_layout Plain Layout
TopLink
\end_layout
\end_inset
, JPOX
\begin_inset Index
status collapsed
\begin_layout Plain Layout
JPOX
\end_layout
\end_inset
, etc) provide standalone implementations of
\family typewriter
EntityManager
\family default
.
\end_layout
\begin_layout Standard
As we've seen in chapter
\begin_inset CommandInset ref
LatexCommand ref
reference "cha:mapper_and_record"
\end_inset
, Lift already comes with a very capable database abstraction layer, so
why would we want to use something else? There are a number of reasons:
\end_layout
\begin_layout Enumerate
JPA is easily accessible from both Java and Scala.
If you are using Lift to complement part of a project that also contains
Java components, JPA allows you to use a common database layer between
both and avoid duplication of effort.
It also means that if you have an existing project based on JPA, you can
easily integrate it into Lift
\end_layout
\begin_layout Enumerate
JPA gives you more flexibility with complex and/or large schemas.
While Lift's Mapper provides most of the functionality you would need,
JPA provides additional lifecycle methods and mapping controls when you
have complex needs.
Additionally, JPA has better support for joins and relationships between
entities.
\end_layout
\begin_layout Enumerate
JPA can provide additional performance improvements via second-level object
caching.
It's possible to roll your own in Lift, but JPA allows you to cache frequently-
accessed objects in memory so that you avoid hitting the database entirely
\end_layout
\begin_layout Section
Introducing JPA
\end_layout
\begin_layout Standard
In order to provide a concrete example to build on while learning how to
integrate JPA, we'll be building a small Lift app to manage a library of
books.
The completed example is available under the Lift Git
\begin_inset Index
status collapsed
\begin_layout Plain Layout
Git
\end_layout
\end_inset
repository in the sites directory, and is called
\begin_inset Quotes eld
\end_inset
JPADemo
\begin_inset Quotes erd
\end_inset
.
Basic coverage of the JPA operations is in section
\begin_inset CommandInset ref
LatexCommand vref
reference "sec:JPA-Examples"
\end_inset
; if you want more detail on JPA, particularly with advanced topics like
locking and hinting, there are several very good tutorials to be found
online
\begin_inset Foot
status collapsed
\begin_layout Plain Layout
\begin_inset Flex URL
status collapsed
\begin_layout Plain Layout
http://java.sun.com/developer/technicalArticles/J2EE/jpa/
\end_layout
\end_inset
,
\begin_inset Flex URL
status collapsed
\begin_layout Plain Layout
http://www.jpox.org/docs/1_2/tutorials/jpa_tutorial.html
\end_layout
\end_inset
\end_layout
\end_inset
.
Our first step is to set up a master project
\begin_inset Index
status collapsed
\begin_layout Plain Layout
master project
\end_layout
\end_inset
for Maven.
This project will have two modules under it, one for the JPA library and
one for the Lift application.
In a working directory of your choosing, issue the following command:
\end_layout
\begin_layout LyX-Code
mvn archetype:generate
\backslash
\end_layout
\begin_layout LyX-Code
-DarchetypeRepository=http://scala-tools.org/repo-snapshots
\backslash
\end_layout
\begin_layout LyX-Code
-DarchetypeGroupId=net.liftweb
\backslash
\end_layout
\begin_layout LyX-Code
-DarchetypeArtifactId=lift-archetype-jpa-basic
\backslash
\end_layout
\begin_layout LyX-Code
-DarchetypeVersion=1.1-SNAPSHOT
\backslash
\end_layout
\begin_layout LyX-Code
-DgroupId=com.foo.jpaweb
\backslash
\end_layout
\begin_layout LyX-Code
-DartifactId=JPADemo
\backslash
\end_layout
\begin_layout LyX-Code
-Dversion=1.0-SNAPSHOT
\end_layout
\begin_layout Standard
This will use the JPA archetype to create a new project for you with modules
for the persistence and web portions of the project.
\end_layout
\begin_layout Standard
\align center
\begin_inset Box Shadowbox
position "t"
hor_pos "c"
has_inner_box 1
inner_pos "t"
use_parbox 0
width "75col%"
special "none"
height "1in"
height_special "totalheight"
status open
\begin_layout Plain Layout
Note: The reason we have split the module out into two projects is that
it aids deployment on Jave EE servers to have the Persistence module be
an independent JAR file.
If you don't need that, you can simply merge the contents of the two modules
into a single project and it will work standalone.
Note that you'll need to merge the pom.xml file's dependencies and plugin
configurations from all three POMs.
Lift comes with an archetype that handles this already, albeit without
the demo code we show here.
Simply use the lift-archetype-jpa-blank-single archetype and you'll get
a blank project (with minimal files for JPA and Lift) that you can use
for your app.
There's also a blank archetype that uses two modules if you want that,
called lift-archetype-jpa-blank.
\end_layout
\end_inset
\end_layout
\begin_layout Standard
You will get a prompt asking you to confirm the settings we've chosen; just
hit
\family typewriter
<enter>
\family default
.
As of this writing we have to use the snapshot version of the archetype
because it didn't make the Lift 1.0 deadline, but otherwise it's a stable
archetype.
You will also see some Velocity warnings about invalid references; these
can be safely ignored and will hopefully be fixed by 1.1.
After the archetype is generated, you should have the following tree structure:
\end_layout
\begin_layout LyX-Code
JPADemo
\end_layout
\begin_layout LyX-Code
|-- README
\end_layout
\begin_layout LyX-Code
|-- pom.xml
\end_layout
\begin_layout LyX-Code
|-- spa
\end_layout
\begin_layout LyX-Code
| |-- pom.xml
\end_layout
\begin_layout LyX-Code
| `-- src ...
\end_layout
\begin_layout LyX-Code
`-- web
\end_layout
\begin_layout LyX-Code
|-- pom.xml
\end_layout
\begin_layout LyX-Code
`-- src ...
\end_layout
\begin_layout Standard
If you look at the source directories, you'll see that our code is already
in place! If you're making your own application you can either use the
previously mentioned blank archetypes to start from scratch, or use the
basic archetype and modify the POMs, Scala code and templates to match
your needs.
For now, let's go over the contents of the project.
\end_layout
\begin_layout Subsection
Using Entity Classes
\begin_inset Index
status collapsed
\begin_layout Plain Layout
entity class
\end_layout
\end_inset
in Scala
\end_layout
\begin_layout Standard
The main components of a JPA library are the entity classes that comprise
your data model.
For our example application we need two primary entities: Author and Book.
Let's take a look at the Author class first, shown in listing
\begin_inset CommandInset ref
LatexCommand vref
reference "lst:Author.scala"
\end_inset
.
The listing shows our import of the entire javax.persistence package as
well as several annotations on a basic class.
For those of you coming from the Java world in JPA, the annotations should
look very familiar.
The major difference between Java and Scala annotations is that each parameter
in a Scala annotation is considered a val, which explains the presence
of the val keyword in lines 12, 15 and 17-18.
In line 17 you may also note that we must specify the target entity class;
although Scala uses generics, the generic types aren't visible from Java
\begin_inset Note Note
status open
\begin_layout Plain Layout
I think this changes in 2.8
\end_layout
\end_inset
, so the Java JPA libraries can't deduce the correct type.
You may also notice that on line 18 we need to use the Java collections
classes for Set, List, etc.
With a little bit of implicit conversion magic (to be shown later), this
has very little impact on our code.
On final item item to note is that the Scala compiler currently does not
support nested annotations
\begin_inset Foot
status open
\begin_layout Plain Layout
\begin_inset Flex URL
status collapsed
\begin_layout Plain Layout
https://lampsvn.epfl.ch/trac/scala/ticket/294
\end_layout
\end_inset
\end_layout
\end_inset
, so where we would normally use them (join tables, named queries, etc),
we will have to use the orm.xml descriptor, which we cover next.
\end_layout
\begin_layout Subsection
\begin_inset CommandInset label
LatexCommand label
name "sub:Using-the-orm.xml"
\end_inset
Using the orm.xml
\begin_inset Index
status collapsed
\begin_layout Plain Layout
orm.xml
\end_layout
\end_inset
descriptor
\end_layout
\begin_layout Standard
As we stated in the last section, there are some instances where the Scala
compiler doesn't fully cover the JPA annotations (nested annotations in
particular).
Some would also argue that queries and other ancillary data (table names,
column names, etc) should be separate from code.
Because of that, JPA allows you to specify an external mapping descriptor
to define and/or override the mappings for your entity classes
\begin_inset Index
status collapsed
\begin_layout Plain Layout
entity classes
\end_layout
\end_inset
.
The basic orm.xml file starts with the DTD type declaration, as shown in
listing
\begin_inset CommandInset ref
LatexCommand vref
reference "lst:orm.xml"
\end_inset
.
Following the preamble, we can define a package that will apply to all
subsequent entries so that we don't need to use the fully-qualified name
for each class.
In our example, we would like to define some named queries for each class.
Putting them in the orm.xml allows us to modify them without requiring a
recompile.
The complete XML Schema Definition can be found at
\begin_inset Flex URL
status collapsed
\begin_layout Plain Layout
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd
\end_layout
\end_inset
.
\end_layout
\begin_layout Standard
In this case we have used the orm.xml file to augment our entity classes.
If, however, we would like to override the configuration, we may use that
as well on a case-by-case basis.
Suppose we wished to change the column name for the Author's
\family typewriter
name
\family default
property.
We can add (per the XSD) a section to the Author entity element as shown
in listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:JPA-Author-override"
\end_inset
.
The
\family typewriter
attribute-override
\family default
element lets us change anything that we would normally specify on the
\family typewriter
@Column
\family default
annotation.
This gives us an extremely powerful method for controlling our schema mapping
outside of the source code.
We can also add named queries
\begin_inset Index
status collapsed
\begin_layout Plain Layout
named queries
\end_layout
\end_inset
in the orm.xml so that we have a central location for defining or altering
the queries.
\end_layout
\begin_layout Standard
\begin_inset listings
lstparams "language=XML"
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
\begin_inset CommandInset label
LatexCommand label
name "lst:JPA-Author-override"
\end_inset
Author override
\end_layout
\end_inset
<entity class="Author">
\end_layout
\begin_layout Plain Layout
<named-query name="findAllAuthors">
\end_layout
\begin_layout Plain Layout
<query><![CDATA[from Author a order by a.name]]></query>
\end_layout
\begin_layout Plain Layout
</named-query>
\end_layout
\begin_layout Plain Layout
<attribute-override name="name">
\end_layout
\begin_layout Plain Layout
<column name="author_name" length="30" />
\end_layout
\begin_layout Plain Layout
</attribute-override>
\end_layout
\begin_layout Plain Layout
</entity>
\end_layout
\end_inset
\end_layout
\begin_layout Subsection
Working with Attached and Detached Objects
\begin_inset CommandInset label
LatexCommand label
name "sub:Working-with-Attached"
\end_inset
\end_layout
\begin_layout Standard
JPA operates with entities in one of two modes: attached and detached.
An attached object is one that is under the direct control of a live JPA
session.
That means that the JPA provider monitors the state of the object and writes
it to the database at the appropriate time.
Objects can be attached either explicitly via the
\family typewriter
persist
\family default
and
\family typewriter
merge
\family default
methods (section
\begin_inset CommandInset ref
LatexCommand ref
reference "sub:Persisting,-merging-and-removing"
\end_inset
), or implicitly via query results, the
\family typewriter
getReference
\family default
method or the
\family typewriter
find
\family default
method.
\end_layout
\begin_layout Standard
As soon as the session ends, any formerly attached objects are now considered
detached.
You can still operate on them as normal objects but any changes are not
directly applied to the database.
If you have a detached object, you can re-attach it to your current session
with the
\family typewriter
merge
\family default
method; any changes since the object was detached, as well as any subsequent
changes to the attached object, will be applied to the database at the
appropriate time.
The concept of object attachment is particularly useful in Lift because
it allows us to generate or query for an object in one request cycle and
then make modifications and merge in a different cycle.
\end_layout
\begin_layout Standard
As an example, our library application provides a summary listing of authors
on one page (
\family typewriter
src/main/webapp/authors/list.html
\family default
) and allows editing of those entities on another (
\family typewriter
src/main/webapp/authors/add.html
\family default
).
We can use the
\family typewriter
SHtml.link
\family default
generator on our list page, combined with a
\family typewriter
RequestVar
\family default
, to pass the instance (detached once we return from the list snippet) to
our edit snippet.
Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:Passing-Detached-Instances"
\end_inset
shows excerpts from our library application snippets demonstrating how
we hand off the instance and do a merge within our edit snippets submission
processing function (
\family typewriter
doAdd
\family default
).
\end_layout
\begin_layout Standard
\begin_inset listings
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
Passing Detached Instances Around an Application
\begin_inset CommandInset label
LatexCommand label
name "lst:Passing-Detached-Instances"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
// in src/main/scala/net/liftweb/jpademo/snippets/Author.scala
\end_layout
\begin_layout Plain Layout
...package and imports ...
\end_layout
\begin_layout Plain Layout
class AuthorOps {
\end_layout
\begin_layout Plain Layout
def list (xhtml : NodeSeq) : NodeSeq = {
\end_layout
\begin_layout Plain Layout
val authors = ...
\end_layout
\begin_layout Plain Layout
authors.flatMap(author => bind("author", xhtml, ...
\end_layout
\begin_layout Plain Layout
// use the link closure to capture the current
\end_layout
\begin_layout Plain Layout
// instance for edit insertion
\end_layout
\begin_layout Plain Layout
"edit" -> SHtml.link("add.html",
\end_layout
\begin_layout Plain Layout
() => authorVar(author), Text(?("Edit")))))
\end_layout
\begin_layout Plain Layout
}
\end_layout
\begin_layout Plain Layout
...
\end_layout
\begin_layout Plain Layout
// Set up a requestVar to track the author object for edits and adds
\end_layout
\begin_layout Plain Layout
object authorVar extends RequestVar(new Author())
\end_layout
\begin_layout Plain Layout
// helper def
\end_layout
\begin_layout Plain Layout
def author = authorVar.is
\end_layout
\begin_layout Plain Layout
def add (xhtml : NodeSeq) : NodeSeq = {
\end_layout
\begin_layout Plain Layout
def doAdd () = {
\end_layout
\begin_layout Plain Layout
...
\end_layout
\begin_layout Plain Layout
// merge and save the detached instance
\end_layout
\begin_layout Plain Layout
Model.mergeAndFlush(author)
\end_layout
\begin_layout Plain Layout
...
\end_layout
\begin_layout Plain Layout
}
\end_layout
\begin_layout Plain Layout
// Hold a val here so that the closure grabs it instead of the def
\end_layout
\begin_layout Plain Layout
val current = author
\end_layout
\begin_layout Plain Layout
// Use a hidden element to reinsert the instance on form submission
\end_layout
\begin_layout Plain Layout
bind("author", xhtml,
\end_layout
\begin_layout Plain Layout
"id" -> SHtml.hidden(() => authorVar(current)), ...,
\end_layout
\begin_layout Plain Layout
"submit" -> SHtml.submit(?("Save"), doAdd))
\end_layout
\begin_layout Plain Layout
}
\end_layout
\begin_layout Plain Layout
}
\end_layout
\end_inset
\end_layout
\begin_layout Section
\begin_inset CommandInset label
LatexCommand label
name "sec:Obtaining-an-EM"
\end_inset