-
Notifications
You must be signed in to change notification settings - Fork 16
/
chap-record_and_mapper.lyx
8971 lines (6431 loc) · 155 KB
/
chap-record_and_mapper.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 2.0 created this file. For more info see http://www.lyx.org/
\lyxformat 413
\begin_document
\begin_header
\textclass book
\begin_preamble
% "define" Scala
\lstdefinelanguage{scala}{morekeywords={class,object,trait,extends,with,new,if,while,for,def,val,var},sensitive=true,morecomment=[l]{//},
morecomment=[s]{/*}{*/},
morestring=[b]"}
% Default settings for code listings
\lstset{frame=single,frameround=tttt,language=scala}
\end_preamble
\use_default_options false
\maintain_unincluded_children false
\language english
\language_package default
\inputencoding auto
\fontencoding global
\font_roman default
\font_sans default
\font_typewriter default
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize default
\use_geometry false
\use_amsmath 1
\use_esint 1
\use_mhchem 1
\use_mathdots 1
\cite_engine basic
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\use_refstyle 0
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\paragraph_indentation default
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header
\begin_body
\begin_layout Chapter
The Mapper and Record Frameworks
\begin_inset CommandInset label
LatexCommand label
name "cha:mapper_and_record"
\end_inset
\end_layout
\begin_layout Standard
In our experience, most webapps end up needing to store user data somewhere.
Once you start working with user data, though, you start dealing with issues
like coding up input forms, validation
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
validation
\end_layout
\end_inset
, persistence, etc.
to handle the data.
That's where the Mapper and Record frameworks come in.
These frameworks provides a scaffolding for all of your data manipulation
needs.
Mapper is the original Lift persistence framework, and it is closely tied
to JDBC for its storage.
Record is a new refactorization of Mapper that is backing-store agnostic
at its core, so it doesn't matter whether you want to save your data to
JDBC, JPA, or even something such as XML.
With Record, selecting the proper driver will be as simple as hooking the
proper traits into your class.
\end_layout
\begin_layout Standard
\begin_inset Box Framed
position "t"
hor_pos "c"
has_inner_box 0
inner_pos "t"
use_parbox 0
use_makebox 0
width "100col%"
special "none"
height "1in"
height_special "totalheight"
status open
\begin_layout Plain Layout
The Record framework is relatively new to Lift.
\strikeout on
The plan is to move to Record as the primary ORM framework for Lift sometime
post-1.0.
\strikeout default
Because Record is still under active design and development, and because
of its current
\begin_inset Quotes eld
\end_inset
moving target
\begin_inset Quotes erd
\end_inset
status, this chapter is mostly going to focus on Mapper.
We will, however, provide a few comparitive examples of Record functionality
to give you a general feel for the flavor of the changes.
In any case, Mapper will not go away even when record comes out, so you
can feel secure that any code using Mapper will be viable for quite a while.
\end_layout
\end_inset
\end_layout
\begin_layout Section
Introduction to Mapper and MetaMapper
\end_layout
\begin_layout Standard
Let's start by discussing the relationship between the Mapper
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
Mapper
\end_layout
\end_inset
and MetaMapper
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
MetaMapper
\end_layout
\end_inset
traits (and the corresponding Record
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
Record
\end_layout
\end_inset
and MetaRecord
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
MetaRecord
\end_layout
\end_inset
).
Mapper provides the
\emph on
per-instance
\emph default
functionality for your class, while MetaMapper handles the
\emph on
global
\emph default
operations for your class and provides a common location to define per-class
static specializations of things like field order, form generation, and
HTML representation.
In fact, many of the Mapper methods actually delegate to methods on MetaMapper.
In addition to Mapper and MetaMapper, there is a third trait, MappedField,
that provides the per-field functionality for your class.
In Record, the trait is simply called
\begin_inset Quotes eld
\end_inset
Field
\begin_inset Quotes erd
\end_inset
.
The MappedField trait lets you define the individual validators as well
as filters to transform the data and the field name.
Under Record, Field adds some functionality such as tab order and default
error messages for form input handling.
\end_layout
\begin_layout Subsection
Adding Mapper to Your Project
\end_layout
\begin_layout Standard
Since Mapper is a separate module, you need to add the following dependency
to your pom.xml to access it:
\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
Mapper POM Dependency
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
<project ...>
\end_layout
\begin_layout Plain Layout
...
\end_layout
\begin_layout Plain Layout
<dependencies>
\end_layout
\begin_layout Plain Layout
...
\end_layout
\begin_layout Plain Layout
<dependency>
\end_layout
\begin_layout Plain Layout
<groupId>net.liftweb</groupId>
\end_layout
\begin_layout Plain Layout
<artifactId>lift-mapper</artifactId>
\end_layout
\begin_layout Plain Layout
<version>1.0</version> <!-- or 1.1-SNAPSHOT, etc -->
\end_layout
\begin_layout Plain Layout
</dependency>
\end_layout
\begin_layout Plain Layout
</dependencies>
\end_layout
\begin_layout Plain Layout
...
\end_layout
\begin_layout Plain Layout
</project>
\end_layout
\end_inset
\end_layout
\begin_layout Standard
You'll also need the following import in any Scala code that uses Mapper:
\end_layout
\begin_layout Standard
\begin_inset listings
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
Mapper Imports
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
import _root_.net.liftweb.mapper._
\end_layout
\end_inset
\end_layout
\begin_layout Subsection
Setting Up the Database Connection
\end_layout
\begin_layout Standard
The first thing you need to do is to define the database connection.
We do this by defining an object called
\family typewriter
DBVendor
\family default
(but you can call it whatever you want).
This object extends the net.liftweb.mapper.ConnectionManager trait and must
implement two methods: newConnection and releaseConnection.
You can make this as sophisticated as you want, with pooling, caching,
etc., but for now, Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:Setting-up-the-database"
\end_inset
shows a basic implementation to set up a PostgreSQL driver.
\end_layout
\begin_layout Standard
\begin_inset listings
lstparams "breaklines=true"
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
Setting Up the Database
\begin_inset CommandInset label
LatexCommand label
name "lst:Setting-up-the-database"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
..
standard Lift imports ...
\end_layout
\begin_layout Plain Layout
import _root_.net.liftweb.mapper._
\end_layout
\begin_layout Plain Layout
import _root_.java.sql._
\end_layout
\begin_layout Plain Layout
\end_layout
\begin_layout Plain Layout
object DBVendor extends ConnectionManager {
\end_layout
\begin_layout Plain Layout
// Force load the driver
\end_layout
\begin_layout Plain Layout
Class.forName("org.postgresql.Driver")
\end_layout
\begin_layout Plain Layout
// define methods
\end_layout
\begin_layout Plain Layout
def newConnection(name : ConnectionIdentifier) = {
\end_layout
\begin_layout Plain Layout
try {
\end_layout
\begin_layout Plain Layout
Full(DriverManager.getConnection(
\end_layout
\begin_layout Plain Layout
"jdbc:postgresql://localhost/mydatabase",
\end_layout
\begin_layout Plain Layout
"root", "secret"))
\end_layout
\begin_layout Plain Layout
} catch {
\end_layout
\begin_layout Plain Layout
case e : Exception => e.printStackTrace; Empty
\end_layout
\begin_layout Plain Layout
}
\end_layout
\begin_layout Plain Layout
}
\end_layout
\begin_layout Plain Layout
def releaseConnection (conn : Connection) { conn.close }
\end_layout
\begin_layout Plain Layout
}
\end_layout
\begin_layout Plain Layout
\end_layout
\begin_layout Plain Layout
class Boot {
\end_layout
\begin_layout Plain Layout
def boot {
\end_layout
\begin_layout Plain Layout
...
\end_layout
\begin_layout Plain Layout
DB.defineConnectionManager(DefaultConnectionIdentifier, DBVendor)
\end_layout
\begin_layout Plain Layout
}
\end_layout
\begin_layout Plain Layout
}
\end_layout
\end_inset
\end_layout
\begin_layout Standard
A few items to note:
\end_layout
\begin_layout Enumerate
The
\family typewriter
name
\family default
parameter for newConnection can be used if you need to have connections
to multiple distinct databases.
One specialized case of this is when you're doing DB sharding (horizontal
scaling).
Multiple database usage is covered in more depth in Section
\begin_inset CommandInset ref
LatexCommand ref
reference "sub:Multiple-Databases"
\end_inset
\end_layout
\begin_layout Enumerate
The newConnection method needs to return a
\family typewriter
Box[java.sql.Connection]
\family default
.
Returning
\family typewriter
Empty
\family default
indicates failure
\end_layout
\begin_layout Enumerate
The releaseConnection method exists so that you have complete control over
the lifecycle of the connection.
For instance, if you were doing connection pooling yourself you would return
the connection to the available pool rather than closing it
\end_layout
\begin_layout Enumerate
The
\family typewriter
DB.defineConnectionManager
\family default
call is what binds our manager into Mapper.
Without it your manager will never get called
\end_layout
\begin_layout Subsection
Constructing a Mapper-enabled Class
\begin_inset CommandInset label
LatexCommand label
name "sub:Constructing-a-Mapper-enabled-class"
\end_inset
\end_layout
\begin_layout Standard
Now that we've covered some basic background, we can start constructing
some Mapper classes to get more familiar with the framework.
We'll start with a simple example of a class for an expense transaction
from our PocketChange application with the following fields:
\end_layout
\begin_layout Itemize
Date
\end_layout
\begin_layout Itemize
Description: a string with a max length of 100 chars
\end_layout
\begin_layout Itemize
Amount: a decimal value with a precision of 16 digits and two decimal places
\end_layout
\begin_layout Itemize
A reference to the Account that owns the transaction
\end_layout
\begin_layout Standard
Given these requirements we can declare our
\family typewriter
Expense
\family default
class as shown in Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:Entry-class-mapper"
\end_inset
.
\end_layout
\begin_layout Standard
\begin_inset listings
lstparams "showstringspaces=false"
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
Expense Class in Mapper
\begin_inset CommandInset label
LatexCommand label
name "lst:Entry-class-mapper"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
import _root_.java.math.MathContext
\end_layout
\begin_layout Plain Layout
\end_layout
\begin_layout Plain Layout
class Expense extends LongKeyedMapper[Expense] with IdPK {
\end_layout
\begin_layout Plain Layout
def getSingleton = Expense
\end_layout
\begin_layout Plain Layout
object dateOf extends MappedDateTime(this)
\end_layout
\begin_layout Plain Layout
object description extends MappedString(this,100)
\end_layout
\begin_layout Plain Layout
object amount extends MappedDecimal(this, MathContext.DECIMAL64, 2)
\end_layout
\begin_layout Plain Layout
object account extends MappedLongForeignKey(this, Account)
\end_layout
\begin_layout Plain Layout
}
\end_layout
\end_inset
\end_layout
\begin_layout Standard
For comparison, the Record version is shown in Listing
\begin_inset CommandInset ref
LatexCommand ref
reference "lst:Entry-class-record"
\end_inset
.
This example already shows some functionality that hasn't been ported over
to Record from Mapper; among other things, the
\family typewriter
IdPK
\family default
trait, and foreign key fields (many to one mappings) are missing.
The other minor differences are that the
\family typewriter
getSingleton
\family default
method has been renamed to
\family typewriter
meta
\family default
, and the Field traits use different names under the Record framework (i.e.
\family typewriter
DateTimeField
\family default
vs
\family typewriter
MappedDateTime
\family default
).
\end_layout
\begin_layout Standard
\begin_inset listings
lstparams "showstringspaces=false"
inline false
status open
\begin_layout Plain Layout
\begin_inset Caption
\begin_layout Plain Layout
Entry Class in Record
\begin_inset CommandInset label
LatexCommand label
name "lst:Entry-class-record"
\end_inset
\end_layout
\end_inset
\end_layout
\begin_layout Plain Layout
import _root_.java.math.MathContext
\end_layout
\begin_layout Plain Layout
import _root_.net.liftweb.record._
\end_layout
\begin_layout Plain Layout
\end_layout
\begin_layout Plain Layout
class Expense extends KeyedRecord[Expense,Long] {
\end_layout
\begin_layout Plain Layout
def meta = Expense
\end_layout
\begin_layout Plain Layout
def primaryKey = id
\end_layout
\begin_layout Plain Layout
object id extends LongField(this) with KeyField[Long,Expense]
\end_layout
\begin_layout Plain Layout
object dateOf extends DateTimeField(this)
\end_layout
\begin_layout Plain Layout
object description extends StringField(this, 100)
\end_layout
\begin_layout Plain Layout
object amount extends DecimalField(this, MathContext.DECIMAL64, 2)
\end_layout
\begin_layout Plain Layout
object account extends LongField(this)
\end_layout
\begin_layout Plain Layout
}
\end_layout
\end_inset
\end_layout
\begin_layout Standard
As you can see, we've set
\family typewriter
Expense
\family default
to extend the
\family typewriter
LongKeyedMapper
\family default
and
\family typewriter
IdPK
\family default
traits and we've added the fields required by our class.
We would like to provide a primary key for our entity; while not strictly
necessary, having a synthetic primary key often helps with CRUD operations.
The
\family typewriter
LongKeyedMapper
\family default
trait accomplishes two objectives: it tells Lift that we want a primary
key defined and that the key should be a long.
This is basically a shortcut for using the
\family typewriter
KeyedMapper[Long,Expense]
\family default
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
KeyedMapper
\end_layout
\end_inset
trait.
When you use the
\family typewriter
KeyedMapper
\family default
trait you need to provide an implementation for the
\family typewriter
primaryKeyField
\family default
def, which must match the type of the
\family typewriter
KeyedMapper
\family default
trait and be a subtype of
\family typewriter
IndexedField
\family default
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
IndexedField
\end_layout
\end_inset
.
The
\family typewriter
IdPK
\family default
trait handles the implementation, but note that
\family typewriter
IdPK
\family default
currently only supports
\family typewriter
Long
\family default
keys.
Mapper supports both indexed
\family typewriter
Longs
\family default
and
\family typewriter
Strings
\family default
, so if you want
\family typewriter
Strings
\family default
you'll need to explicitly use
\family typewriter
KeyedMapper[String,...]
\family default
and provide the field definition yourself.
It's possible to use some other type for your primary key, but you'll need
to roll your own (Section
\begin_inset CommandInset ref
LatexCommand ref
reference "sub:Defining-Custom-Field-types-mapper"
\end_inset
).
Technically
\family typewriter
Int
\family default
indexes are supported as well, but there is no corresponding trait for
an
\family typewriter
Int
\family default
foreign key.
That means that if you use an
\family typewriter
Int
\family default
for the primary key, you may not be able to add a relationship to another
object (Section
\begin_inset CommandInset ref
LatexCommand ref
reference "sub:Object-Relationships"
\end_inset
), unless you write your own.
Record is a little more flexible in primary key selection because it uses,
in effect, a marker trait (
\family typewriter
KeyField
\family default
) to indicate that a particular field is a key field.
One thing to note is that in the Mapper framework, the table name
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
table name
\end_layout
\end_inset
for your entity defaults to the name of the class (Expense, in our case).
If you want to change this, then you just need to override the
\family typewriter
dbTableName
\family default
\begin_inset Index idx
status collapsed
\begin_layout Plain Layout
dbTableName
\end_layout
\end_inset
def in your MetaMapper object.
\end_layout
\begin_layout Standard
Looking at these examples, you've probably noticed that the fields are defined
as objects rather than instance members (vars).