-
Notifications
You must be signed in to change notification settings - Fork 0
/
java-working-with-a-database.html
1291 lines (1095 loc) · 180 KB
/
java-working-with-a-database.html
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
<!DOCTYPE html><html lang="de-ch"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Java working with databases - Finecloud</title><meta name="description" content="Introduction In this Post I will describe how you can easily learn, test and play around with Java interacting with SQL Databases. This post is a summary of my Java learning course I'm taking on udemy. The post is not intended to be spread around…"><meta name="generator" content="Publii Open-Source CMS for Static Site"><link rel="stylesheet" href="https://www.finecloud.ch/media/plugins/syntaxHighlighter/prism-black.css"><link rel="canonical" href="https://www.finecloud.ch/java-working-with-a-database.html"><link rel="alternate" type="application/atom+xml" href="https://www.finecloud.ch/feed.xml"><link rel="alternate" type="application/json" href="https://www.finecloud.ch/feed.json"><meta property="og:title" content="Java working with databases"><meta property="og:site_name" content="Finecloud"><meta property="og:description" content="Introduction In this Post I will describe how you can easily learn, test and play around with Java interacting with SQL Databases. This post is a summary of my Java learning course I'm taking on udemy. The post is not intended to be spread around…"><meta property="og:url" content="https://www.finecloud.ch/java-working-with-a-database.html"><meta property="og:type" content="article"><link rel="shortcut icon" href="https://www.finecloud.ch/media/website/finecloud.png" type="image/png"><link rel="stylesheet" href="https://www.finecloud.ch/assets/css/style.css?v=39da73365516a098a9b73b721fc970e2"><script type="application/ld+json">{"@context":"http://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.finecloud.ch/java-working-with-a-database.html"},"headline":"Java working with databases","datePublished":"2022-09-06T14:20","dateModified":"2022-09-10T06:42","description":"Introduction In this Post I will describe how you can easily learn, test and play around with Java interacting with SQL Databases. This post is a summary of my Java learning course I'm taking on udemy. The post is not intended to be spread around…","author":{"@type":"Person","name":"Finecloud","url":"https://www.finecloud.ch/authors/finecloud/"},"publisher":{"@type":"Organization","name":"Finecloud"}}</script><meta name="google-site-verification" content="seFY9U12uiEq5U3_MyZiX6XWzk0AVFl9zITr2ZKsytY"></head><body><div class="site-container"><header class="top" id="js-header"><a class="logo" href="https://www.finecloud.ch/">Finecloud</a><nav class="navbar js-navbar"><button class="navbar__toggle js-toggle" aria-label="Menu" aria-haspopup="true" aria-expanded="false"><span class="navbar__toggle-box"><span class="navbar__toggle-inner">Menu</span></span></button><ul class="navbar__menu"><li><a href="https://www.finecloud.ch/" target="_self">Blog</a></li><li><a href="https://www.finecloud.ch/tags/" target="_self">Tags</a></li></ul></nav><div class="search"><div class="search__overlay js-search-overlay"><div class="search__overlay-inner"><form action="https://www.finecloud.ch/search.html" class="search__form"><input class="search__input js-search-input" type="search" name="q" placeholder="search..." aria-label="search..." autofocus="autofocus"></form><button class="search__close js-search-close" aria-label="Close">Close</button></div></div><button class="search__btn js-search-btn" aria-label="Search"><svg role="presentation" focusable="false"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#search"/></svg></button></div></header><main><article class="post"><div class="hero"><figure class="hero__image hero__image--overlay"><img src="https://www.finecloud.ch/media/website/download.jpg" srcset="https://www.finecloud.ch/media/website/responsive/download-xs.jpg 300w, https://www.finecloud.ch/media/website/responsive/download-sm.jpg 480w, https://www.finecloud.ch/media/website/responsive/download-md.jpg 768w, https://www.finecloud.ch/media/website/responsive/download-lg.jpg 1024w, https://www.finecloud.ch/media/website/responsive/download-xl.jpg 1360w, https://www.finecloud.ch/media/website/responsive/download-2xl.jpg 1600w" sizes="100vw" loading="eager" alt=""></figure><header class="hero__content"><div class="wrapper"><div class="post__meta"><time datetime="2022-09-06T14:20">September 6, 2022</time></div><h1>Java working with databases</h1></div></header></div><div class="wrapper post__entry"><div class="post__toc"><h3>Table of Contents</h3><ul><li><a href="#mcetoc_1gbnqrj4jjf">Introduction</a></li><li><a href="#mcetoc_1gbpqdh8573">SQL Queries</a><ul><li><a href="#mcetoc_1gbnqrj4jjg">Create Table</a></li><li><a href="#mcetoc_1gbpqdh8574">Function calls</a></li><li><a href="#mcetoc_1gbpqdh8575">Regex</a></li><li><a href="#mcetoc_1gbpqdh8576">Modify Data (CRUD)</a></li></ul></li><li><a href="#mcetoc_1gbq4dguead">Interact with a database with Java</a><ul><li><a href="#mcetoc_1gbq4dgueae">JDBC</a></li><li><a href="#mcetoc_1gbri47otbv">How to handle JUnit test records / testdata</a></li><li><a href="#mcetoc_1gbrkro2vev">Save return value</a></li><li><a href="#mcetoc_1gbrkro2vf0">Prevent SQL injection</a></li><li><a href="#mcetoc_1gc0q0084hv">Find Person by Id</a></li><li><a href="#mcetoc_1gc0q0084i0">Delete one or more persons</a></li><li><a href="#mcetoc_1gc8qakok1a8">Update a person</a></li></ul></li><li><a href="#mcetoc_1gc8r84pi1ab">Making it reusable</a></li><li><a href="#mcetoc_1gc9c3hup1b5">Improve the SQL statement calls</a></li><li><a href="#mcetoc_1gcir9j7k2d">Speeding up SQL queries</a></li></ul></div><h2 id="mcetoc_1gbnqrj4jjf">Introduction</h2><p>In this Post I will describe how you can easily learn, test and play around with Java interacting with SQL Databases. This post is a summary of my Java learning course I'm taking on udemy. The post is not intended to be spread around the world, since the contents are not my own ideas, its only just for my own sake of summarizing and writing down what I'm learning.</p><p>As working environment we will use the <a href="https://squirrel-sql.sourceforge.io/" target="_blank" rel="nofollow noopener noreferrer">SQuirreL SQL Client</a> and create a local H2 Database with it. This allows us to start very quick and skip the hole SQL Server overhead, which is just to learn Java with Databases not relevant so far. You also need to download the <a href="http://www.h2database.com/html/download.html" target="_blank" rel="nofollow noopener noreferrer">H2 driver</a> to work with this.</p><h2 id="mcetoc_1gbpqdh8573">SQL Queries</h2><h3 id="mcetoc_1gbnqrj4jjg">Create Table</h3><p>First of all we need to create our initial SQL Table to work with later on. You can use this SQL Query:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">CREATE</span> <span class="hljs-keyword" style="color: #cc7832;">TABLE</span> PEOPLE(<span class="hljs-keyword" style="color: #cc7832;">ID</span> <span class="hljs-built_in">BIGINT</span> AUTO_INCREMENT, FIRST_NAME <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number" style="color: #6897bb;">255</span>), LAST_NAME <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number" style="color: #6897bb;">255</span>), DOB <span class="hljs-keyword" style="color: #cc7832;">TIMESTAMP</span>, SALARY <span class="hljs-built_in">NUMERIC</span>);</pre><p>let's add a test record:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">INSERT</span> <span class="hljs-keyword" style="color: #cc7832;">INTO</span> PEOPLE (FIRST_NAME, LAST_NAME, DOB, SALARY) <span class="hljs-keyword" style="color: #cc7832;">VALUES</span>(<span class="hljs-string" style="color: #6a8759;">'Harry'</span>, <span class="hljs-string" style="color: #6a8759;">'Johnson'</span>, <span class="hljs-string" style="color: #6a8759;">'1950-03-15 10:45:10'</span>, <span class="hljs-number" style="color: #6897bb;">100000.00</span>);</pre><p>let's verify the record by querying all records in the table people:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> * <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE;</pre><p>output:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-comment" style="color: grey;">ID</span> <span class="hljs-comment" style="color: grey;">FIRST_NAME</span> <span class="hljs-comment" style="color: grey;">LAST_NAME</span> <span class="hljs-comment" style="color: grey;">DOB</span> <span class="hljs-comment" style="color: grey;">SALARY</span>
<span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span> <span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span> <span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span> <span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span> <span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-literal" style="color: #6897bb;">-</span>
<span class="hljs-comment" style="color: grey;">1</span> <span class="hljs-comment" style="color: grey;">Harry</span> <span class="hljs-comment" style="color: grey;">Johnson</span> <span class="hljs-comment" style="color: grey;">1950</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-comment" style="color: grey;">03</span><span class="hljs-literal" style="color: #6897bb;">-</span><span class="hljs-comment" style="color: grey;">15</span> <span class="hljs-comment" style="color: grey;">10:45:10</span><span class="hljs-string" style="color: #6a8759;">.</span><span class="hljs-comment" style="color: grey;">0</span> <span class="hljs-comment" style="color: grey;">100000</span></pre><p>great, this looks good so far. Let's add some more records:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">INSERT</span> <span class="hljs-keyword" style="color: #cc7832;">INTO</span> PEOPLE (FIRST_NAME, LAST_NAME, DOB, SALARY) <span class="hljs-keyword" style="color: #cc7832;">VALUES</span>(<span class="hljs-string" style="color: #6a8759;">'Jack'</span>, <span class="hljs-string" style="color: #6a8759;">'Johnson'</span>, <span class="hljs-string" style="color: #6a8759;">'2000-01-10 8:45:10'</span>, <span class="hljs-number" style="color: #6897bb;">50000.00</span>);
<span class="hljs-keyword" style="color: #cc7832;">INSERT</span> <span class="hljs-keyword" style="color: #cc7832;">INTO</span> PEOPLE (FIRST_NAME, LAST_NAME, DOB, SALARY) <span class="hljs-keyword" style="color: #cc7832;">VALUES</span>(<span class="hljs-string" style="color: #6a8759;">'Mary'</span>, <span class="hljs-string" style="color: #6a8759;">'Johnson'</span>, <span class="hljs-string" style="color: #6a8759;">'2005-05-13 17:30:10'</span>, <span class="hljs-number" style="color: #6897bb;">20000.00</span>);
<span class="hljs-keyword" style="color: #cc7832;">INSERT</span> <span class="hljs-keyword" style="color: #cc7832;">INTO</span> PEOPLE (FIRST_NAME, LAST_NAME, DOB, SALARY) <span class="hljs-keyword" style="color: #cc7832;">VALUES</span>(<span class="hljs-string" style="color: #6a8759;">'Susan'</span>, <span class="hljs-string" style="color: #6a8759;">'Johnson'</span>, <span class="hljs-string" style="color: #6a8759;">'1951-10-31 19:13:43'</span>, <span class="hljs-number" style="color: #6897bb;">200000.00</span>);
<span class="hljs-keyword" style="color: #cc7832;">INSERT</span> <span class="hljs-keyword" style="color: #cc7832;">INTO</span> PEOPLE (FIRST_NAME, LAST_NAME, DOB, SALARY) <span class="hljs-keyword" style="color: #cc7832;">VALUES</span>(<span class="hljs-string" style="color: #6a8759;">'Jake'</span>, <span class="hljs-string" style="color: #6a8759;">'Smith'</span>, <span class="hljs-string" style="color: #6a8759;">'1970-10-31 19:13:43'</span>, <span class="hljs-number" style="color: #6897bb;">75000.00</span>);</pre><p>Let's play around with some SQL statements. This are only a few SQL example queries:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> * <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">WHERE</span> FIRST_NAME <span class="hljs-keyword" style="color: #cc7832;">LIKE</span> <span class="hljs-string" style="color: #6a8759;">'J%'</span>;</pre><p>gives us back all records with firstname J*.</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> * <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">WHERE</span> SALARY > <span class="hljs-number" style="color: #6897bb;">99000</span>;</pre><p>gives all records where salary is bigger than 99000</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> * <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">WHERE</span> DOB < <span class="hljs-built_in">DATE</span> <span class="hljs-string" style="color: #6a8759;">'1980-01-01'</span> <span class="hljs-keyword" style="color: #cc7832;">AND</span> FIRST_NAME <span class="hljs-keyword" style="color: #cc7832;">LIKE</span> <span class="hljs-string" style="color: #6a8759;">'H%'</span>;</pre><p>gives all records where dateofbirth is before 1980-01-01 and firstname starts with H*.</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> * <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">ORDER</span> <span class="hljs-keyword" style="color: #cc7832;">BY</span> FIRST_NAME;</pre><p>gives back all records sort by firstname</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> * <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">ORDER</span> <span class="hljs-keyword" style="color: #cc7832;">BY</span> DOB <span class="hljs-keyword" style="color: #cc7832;">ASC</span>, FIRST_NAME <span class="hljs-keyword" style="color: #cc7832;">DESC</span>;</pre><p>gives back all records, sort by dateofbirth (ascending) and sort by firstname (descending)</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> <span class="hljs-keyword" style="color: #cc7832;">SUM</span>(SALARY), LAST_NAME <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">GROUP</span> <span class="hljs-keyword" style="color: #cc7832;">BY</span> LAST_NAME;</pre><p>calculates the summary of all records grouped by lastname.</p><h3 id="mcetoc_1gbpqdh8574">Function calls</h3><p>We can go one step further and also use SQL function calls like these:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> LAST_NAME, <span class="hljs-keyword" style="color: #cc7832;">COUNT</span>(*) <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">GROUP</span> <span class="hljs-keyword" style="color: #cc7832;">BY</span> LAST_NAME;</pre><p>output:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">LAST_NAME COUNT(*)
<span class="hljs-comment" style="color: grey;">--------- --------</span>
Johnson 4
Smith 2</pre><p>It's also possible to display combined table rows in the output of a sql query:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> <span class="hljs-keyword" style="color: #cc7832;">CONCAT</span>(LAST_NAME, <span class="hljs-string" style="color: #6a8759;">', '</span>, FIRST_NAME) <span class="hljs-keyword" style="color: #cc7832;">AS</span> <span class="hljs-keyword" style="color: #cc7832;">NAME</span>, DOB <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE;</pre><p>output:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">NAME DOB
<span class="hljs-comment" style="color: grey;">-------------- ---------------------</span>
Johnson, Harry 1950-03-15 10:45:10.0
Smith, Jake 1970-10-31 19:13:43.0
Johnson, Jack 2000-01-10 08:45:10.0
Johnson, Mary 2005-05-13 17:30:10.0
Johnson, Susan 1951-10-31 19:13:43.0
Smith, Jake 1970-10-31 19:13:43.0</pre><p>or we can manipulate data, before we display the sql query result, without modifying the real db data:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> <span class="hljs-keyword" style="color: #cc7832;">CONCAT</span>(<span class="hljs-keyword" style="color: #cc7832;">UPPER</span>(LAST_NAME), <span class="hljs-string" style="color: #6a8759;">', '</span>, FIRST_NAME) <span class="hljs-keyword" style="color: #cc7832;">AS</span> <span class="hljs-keyword" style="color: #cc7832;">NAME</span>, <span class="hljs-keyword" style="color: #cc7832;">DATEADD</span>(<span class="hljs-keyword" style="color: #cc7832;">YEAR</span>, <span class="hljs-number" style="color: #6897bb;">10</span>, DOB) <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE;</pre><p>output:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">NAME DATEADD(YEAR, 10, DOB)
<span class="hljs-comment" style="color: grey;">-------------- ----------------------</span>
JOHNSON, Harry 1960-03-15 10:45:10.0
SMITH, Jake 1980-10-31 19:13:43.0
JOHNSON, Jack 2010-01-10 08:45:10.0
JOHNSON, Mary 2015-05-13 17:30:10.0
JOHNSON, Susan 1961-10-31 19:13:43.0
SMITH, Jake 1980-10-31 19:13:43.0</pre><h3 id="mcetoc_1gbpqdh8575">Regex</h3><p>If all of this is not enough, you cold even use regex with sql queries:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">SELECT</span> REGEXP_REPLACE(<span class="hljs-string" style="color: #6a8759;">'1970-10-31'</span>, <span class="hljs-string" style="color: #6a8759;">'\d{4}-'</span>, <span class="hljs-string" style="color: #6a8759;">'aaaa-'</span>);</pre><p>output:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">'aaaa-10-31'
<span class="hljs-comment" style="color: grey;">------------</span>
aaaa-10-31 </pre><h3 id="mcetoc_1gbpqdh8576">Modify Data (CRUD)</h3><p>If we need to change existing data, we can for example use the update query:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">UPDATE</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">SET</span> FIRST_NAME=<span class="hljs-string" style="color: #6a8759;">'Sabrina'</span> <span class="hljs-keyword" style="color: #cc7832;">WHERE</span> FIRST_NAME=<span class="hljs-string" style="color: #6a8759;">'Susan'</span>;</pre><p>To remove a record we can use the delete query:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">DELETE</span> <span class="hljs-keyword" style="color: #cc7832;">FROM</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">WHERE</span> LAST_NAME=<span class="hljs-string" style="color: #6a8759;">'Smith'</span>;</pre><p>We can also change the structure of a table. Let's say we want to add a Column:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">ALTER</span> <span class="hljs-keyword" style="color: #cc7832;">TABLE</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">ADD</span> <span class="hljs-keyword" style="color: #cc7832;">COLUMN</span> EMAIL <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number" style="color: #6897bb;">255</span>);</pre><p>The table looks like this now: </p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">ID FIRST_NAME LAST_NAME DOB SALARY EMAIL
<span class="hljs-comment" style="color: grey;">-- ---------- --------- --------------------- ------ ------</span>
12 Harry Jonson 1950-03-15 10:45:10.0 100000 <null>
14 Jack Jonson 2000-01-10 08:45:10.0 50000 <null>
15 Mary Jonson 2005-05-13 17:30:10.0 20000 <null>
16 Sabrina Jonson 1951-10-31 19:13:43.0 200000 <null></pre><p>Lets fill the <null> EMAIL values with a placeholder address:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">UPDATE</span> PEOPLE <span class="hljs-keyword" style="color: #cc7832;">SET</span> EMAIL=<span class="hljs-string" style="color: #6a8759;">'[email protected]'</span>;</pre><p>result:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">ID FIRST_NAME LAST_NAME DOB SALARY EMAIL
<span class="hljs-comment" style="color: grey;">-- ---------- --------- --------------------- ------ -------------------</span>
12 Harry Jonson 1950-03-15 10:45:10.0 100000 [email protected]
14 Jack Jonson 2000-01-10 08:45:10.0 50000 [email protected]
15 Mary Jonson 2005-05-13 17:30:10.0 20000 [email protected]
16 Sabrina Jonson 1951-10-31 19:13:43.0 200000 [email protected]</pre><h2 id="mcetoc_1gbq4dguead">Interact with a database with Java</h2><p>So far so good, but how can we use Java to Create and manipulate a SQL Database? First we will create a new gradle Project in IntellJ IDEA. To add the H2 dependency you can open the<em> build.gradle</em> file and open the dependencie Manager with the shortcut <em>command + n</em> on mac. Search for <em>h2 </em>and add the<em> H2 Database Engine:</em></p><figure class="post__image"><img loading="lazy" src="https://www.finecloud.ch/media/posts/61/Screenshot-2022-08-31-at-13.41.45.png" alt="" width="1896" height="373" sizes="100vw" srcset="https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.41.45-xs.png 300w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.41.45-sm.png 480w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.41.45-md.png 768w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.41.45-lg.png 1024w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.41.45-xl.png 1360w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.41.45-2xl.png 1600w"></figure><p>Lets do our development with the TDD method and add another dependency for this. Search for Assertj and add the<em> AssertJ fluent assertions</em>:</p><figure class="post__image"><img loading="lazy" src="https://www.finecloud.ch/media/posts/61/Screenshot-2022-08-31-at-13.47.28.png" alt="" width="1896" height="373" sizes="100vw" srcset="https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.47.28-xs.png 300w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.47.28-sm.png 480w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.47.28-md.png 768w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.47.28-lg.png 1024w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.47.28-xl.png 1360w, https://www.finecloud.ch/media/posts/61/responsive/Screenshot-2022-08-31-at-13.47.28-2xl.png 1600w"></figure><p>Make sure to change the newly added AssertJ dependency line in build.gradle from</p><p><code>implementation 'org.assertj:assertj-core:3.23.1'</code></p><p>to</p><p><code>testImplementation 'org.assertj:assertj-core:3.23.1'</code></p><p>Now Lets add a TDD TestClass as well as a main Class:</p><p>PeopleRepositoryTests.java:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.repository;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.Person;
<span class="hljs-keyword" style="color: #cc7832;">import</span> org.junit.jupiter.api.Test;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZoneId;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">import</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> org.assertj.core.api.Assertions.assertThat;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">PeopleRepositoryTests</span> </span>{
<span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canSave</span><span class="hljs-params">()</span> </span>{
PeopleRepository repo = <span class="hljs-keyword" style="color: #cc7832;">new</span> PeopleRepository();
Person john = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"John"</span>, <span class="hljs-string" style="color: #6a8759;">"Smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">1980</span>,<span class="hljs-number" style="color: #6897bb;">11</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-6"</span>)));
Person savedPerson = repo.save(john);
assertThat(savedPerson.getId()).isGreaterThan(<span class="hljs-number" style="color: #6897bb;">0</span>);
}
}
</pre><p>model/Person.java:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.model;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">Person</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">private</span> Long id;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(String firstName, String lastName, ZonedDateTime odb)</span> </span>{
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Long <span class="hljs-title" style="color: #ffc66d;">getId</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-number" style="color: #6897bb;">1L</span>;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setId</span><span class="hljs-params">(Long id)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.id = id;
}
}
</pre><p>repository/PeopleRepository.java: </p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.repository;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.Person;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">PeopleRepository</span> </span>{
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Person <span class="hljs-title" style="color: #ffc66d;">save</span><span class="hljs-params">(Person person)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> person;
}
}
</pre><p>The logic of this code is not implemented yet. The goal of TDD is to just make the test pass. So we need to force ourself to create a test where the getId method will fail without the correct logic. We can achieve this by adding another Person and calling one of those two person by it's Id:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canSaveTwoPeople</span><span class="hljs-params">()</span> </span>{
PeopleRepository repo = <span class="hljs-keyword" style="color: #cc7832;">new</span> PeopleRepository();
Person john = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"John"</span>, <span class="hljs-string" style="color: #6a8759;">"Smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">1980</span>,<span class="hljs-number" style="color: #6897bb;">11</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-6"</span>)));
Person bobby = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Bobby"</span>, <span class="hljs-string" style="color: #6a8759;">"Smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">1982</span>,<span class="hljs-number" style="color: #6897bb;">9</span>,<span class="hljs-number" style="color: #6897bb;">13</span>,<span class="hljs-number" style="color: #6897bb;">1</span>,<span class="hljs-number" style="color: #6897bb;">51</span>,<span class="hljs-number" style="color: #6897bb;">54</span>,<span class="hljs-number" style="color: #6897bb;">1</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+1"</span>)));
Person savedPerson1 = repo.save(john);
Person savedPerson2 = repo.save(bobby);
assertThat(savedPerson1.getId()).isNotEqualTo(savedPerson2.getId());
}</pre><p>this thest does now fail as expected: </p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;">Expecting actual:
<span class="hljs-number" style="color: #6897bb;">1L</span>
not to be equal to:
<span class="hljs-number" style="color: #6897bb;">1L</span>
java.lang.AssertionError:
Expecting actual:
<span class="hljs-number" style="color: #6897bb;">1L</span>
not to be equal to:
<span class="hljs-number" style="color: #6897bb;">1L</span>
PeopleRepositoryTests > canSaveTwoPeople() FAILED
java.lang.AssertionError at PeopleRepositoryTests.java:<span class="hljs-number" style="color: #6897bb;">28</span>
<span class="hljs-number" style="color: #6897bb;">1</span> test completed, <span class="hljs-number" style="color: #6897bb;">1</span> failed
FAILURE: Build failed with an exception.</pre><p>Now we are at the point where we need to write the connection to the database.</p><h3 id="mcetoc_1gbq4dgueae">JDBC</h3><p>PeopleRepositoryTests.java:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.repository;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.Person;
<span class="hljs-keyword" style="color: #cc7832;">import</span> org.junit.jupiter.api.BeforeEach;
<span class="hljs-keyword" style="color: #cc7832;">import</span> org.junit.jupiter.api.Test;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.sql.Connection;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.sql.DriverManager;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.sql.SQLException;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZoneId;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">import</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> org.assertj.core.api.Assertions.assertThat;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">PeopleRepositoryTests</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">private</span> Connection connection;
<span class="hljs-meta" style="color: #bbb529;">@BeforeEach</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException </span>{
connection = DriverManager.getConnection(<span class="hljs-string" style="color: #6a8759;">"jdbc:h2:~/peopletest"</span>.replace(<span class="hljs-string" style="color: #6a8759;">"~"</span>, System.getProperty(<span class="hljs-string" style="color: #6a8759;">"user.home"</span>)));
}
<span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canSaveOnePerson</span><span class="hljs-params">()</span> </span>{
PeopleRepository repo = <span class="hljs-keyword" style="color: #cc7832;">new</span> PeopleRepository(connection);
Person john = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"John"</span>, <span class="hljs-string" style="color: #6a8759;">"Smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">1980</span>,<span class="hljs-number" style="color: #6897bb;">11</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-6"</span>)));
Person savedPerson = repo.save(john);
assertThat(savedPerson.getId()).isGreaterThan(<span class="hljs-number" style="color: #6897bb;">0</span>);
}
<span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canSaveTwoPeople</span><span class="hljs-params">()</span> </span>{
PeopleRepository repo = <span class="hljs-keyword" style="color: #cc7832;">new</span> PeopleRepository(connection);
Person john = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"John"</span>, <span class="hljs-string" style="color: #6a8759;">"Smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">1980</span>,<span class="hljs-number" style="color: #6897bb;">11</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">15</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-6"</span>)));
Person bobby = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Bobby"</span>, <span class="hljs-string" style="color: #6a8759;">"Smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">1982</span>,<span class="hljs-number" style="color: #6897bb;">9</span>,<span class="hljs-number" style="color: #6897bb;">13</span>,<span class="hljs-number" style="color: #6897bb;">1</span>,<span class="hljs-number" style="color: #6897bb;">51</span>,<span class="hljs-number" style="color: #6897bb;">54</span>,<span class="hljs-number" style="color: #6897bb;">1</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+1"</span>)));
Person savedPerson1 = repo.save(john);
Person savedPerson2 = repo.save(bobby);
assertThat(savedPerson1.getId()).isNotEqualTo(savedPerson2.getId());
}
}
</pre><p>model/Person.java:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.model;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">Person</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">private</span> Long id;
<span class="hljs-keyword" style="color: #cc7832;">private</span> String firstName;
<span class="hljs-keyword" style="color: #cc7832;">private</span> String lastName;
<span class="hljs-keyword" style="color: #cc7832;">private</span> ZonedDateTime dob;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(String firstName, String lastName, ZonedDateTime odb)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.firstName = firstName;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.lastName = lastName;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.dob = odb;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Long <span class="hljs-title" style="color: #ffc66d;">getId</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> id;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setId</span><span class="hljs-params">(Long id)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.id = id;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">getFirstName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> firstName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setFirstName</span><span class="hljs-params">(String firstName)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.firstName = firstName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">getLastName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> lastName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setLastName</span><span class="hljs-params">(String lastName)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.lastName = lastName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> ZonedDateTime <span class="hljs-title" style="color: #ffc66d;">getDob</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> dob;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setDob</span><span class="hljs-params">(ZonedDateTime dob)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.dob = dob;
}
}
</pre><p>repository/PeopleRepository.java: </p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.repository;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.Person;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.sql.*;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZoneId;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">PeopleRepository</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">private</span> Connection connection;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">PeopleRepository</span><span class="hljs-params">(Connection connection)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.connection = connection;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Person <span class="hljs-title" style="color: #ffc66d;">save</span><span class="hljs-params">(Person person)</span> </span>{
String sql = String.format(<span class="hljs-string" style="color: #6a8759;">"INSERT INTO PEOPLE (FIRST_NAME, LAST_NAME, DOB) VALUES(?,?,?)"</span>);
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(<span class="hljs-number" style="color: #6897bb;">1</span>, person.getFirstName());
ps.setString(<span class="hljs-number" style="color: #6897bb;">2</span>, person.getLastName());
ps.setTimestamp(<span class="hljs-number" style="color: #6897bb;">3</span>, Timestamp.valueOf(person.getDob().withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)).toLocalDateTime()));
<span class="hljs-keyword" style="color: #cc7832;">int</span> recordsAffected = ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
<span class="hljs-keyword" style="color: #cc7832;">long</span> id = rs.getLong(<span class="hljs-number" style="color: #6897bb;">1</span>);
person.setId(id);
}
System.out.printf(<span class="hljs-string" style="color: #6a8759;">"Records affected: %d%n"</span>, recordsAffected);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> person;
}
}
</pre><h3 id="mcetoc_1gbri47otbv">How to handle JUnit test records / testdata</h3><p>Currently we're dirtying up our database every time we run our tests. But that's not necessarily the most desirable way for these tests to run there. Now that we have confirmed that we generally are able to write data to the database, perhaps we don't want to keep dirtying up our database permanently with all these duplicated records, as we are doing now.</p><p>There's actually a great technique that we can use if we want to use the database temporarily while the tests are working, but then have the tests essentially clean up after themselves when they're all done so that we're not permanently impacting the database. Currently, every time we connect to the database and we interact with it, and particularly we update or insert records in to the database, our SQirreL commands or statements are getting committed to the database and that's happening for us automatically.<br><br>But we can actually turn off the auto commits. This still allows us to insert data or update the database in any way at all. But we don't commit the changes and then we close the database connection. All of the changes that we did to the database will just go away. They won't be committed. They won't be permanently recorded. They will look as if they all worked for as long as we have a connection to the database. But once the database connection is gone, so will be those changes that we made. So that can give us a cool technique for cleaning up after our tests. The needed change are:</p><p>PeopleRepositoryTests.java:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@BeforeEach</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException </span>{
connection = DriverManager.getConnection(<span class="hljs-string" style="color: #6a8759;">"jdbc:h2:~/peopletest"</span>.replace(<span class="hljs-string" style="color: #6a8759;">"~"</span>, System.getProperty(<span class="hljs-string" style="color: #6a8759;">"user.home"</span>)));
connection.setAutoCommit(<span class="hljs-keyword" style="color: #cc7832;">false</span>);
}
<span class="hljs-meta" style="color: #bbb529;">@AfterEach</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">tearDown</span><span class="hljs-params">()</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException </span>{
<span class="hljs-keyword" style="color: #cc7832;">if</span> (connection != <span class="hljs-keyword" style="color: #cc7832;">null</span>) {
connection.close();
}
}</pre><p>The important line is the <em>connection.setAutoCommit(false);</em></p><h3 id="mcetoc_1gbrkro2vev">Save return value</h3><p>At the moment, if we save a person, we just get back a generic message like this:</p><p><code>Records affected: 1</code></p><p>Let's improve this, so that we see the record which has been saved:</p><p>/repository/PeopleRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
<span class="hljs-keyword" style="color: #cc7832;">long</span> id = rs.getLong(<span class="hljs-number" style="color: #6897bb;">1</span>);
person.setId(id);
System.out.println(person);
}</pre><p>just add the System.out.... Line. But now we need to overwrite the toString() method on the Person class:</p><p>/model/Person.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-string" style="color: #6a8759;">"Person{"</span> +
<span class="hljs-string" style="color: #6a8759;">"id="</span> + id +
<span class="hljs-string" style="color: #6a8759;">", firstName='"</span> + firstName + <span class="hljs-string" style="color: #6a8759;">'\''</span> +
<span class="hljs-string" style="color: #6a8759;">", lastName='"</span> + lastName + <span class="hljs-string" style="color: #6a8759;">'\''</span> +
<span class="hljs-string" style="color: #6a8759;">", dob="</span> + dob +
<span class="hljs-string" style="color: #6a8759;">'}'</span>;
}</pre><p>If we now save a Person we get the following return value:</p><p><code>Person{id=47, firstName='John', lastName='Smith', dob=1980-11-15T15:15-06:00}</code><br><code>Records affected: 1</code><br><code>Person{id=48, firstName='Bobby', lastName='Smith', dob=1982-09-13T01:51:54+01:00}</code><br><code>Records affected: 1</code></p><h3 id="mcetoc_1gbrkro2vf0">Prevent SQL injection</h3><p>We could have made the SQL statement without using a prepared statement but by using just a regular statement. But if we had used a regular statement, then we would have had to use some string concatenation tricks to get these values in here. In other words, we would have had to hard code these values into the values area of our insert statement and lots of database code in Java has been written in that way. <br><br>But if you've got parameters that you need to pass in using a regular statement and using string concatenation is like the worst possible way to get those parameters in there. The reason for this has to do with a major security flaw that exists in lots of code not only just Java, it's called SQL injection. <br><br>Let's imagine that this code here is part of a web application where there's a web page and the web page asks people to enter their first name, last name, date of birth.<br><br>Now there is a malicious and intelligent hacker who wants to hack into our application and steal all of our data. One thing that he might try to do is to utilize this SQL injection technique and enter this pseudocode in the firstName field:</p><p><code>Max', 'Müller', '1999-01-01'); SELECT * FROM PEOPLE;</code></p><p>You can imagine what happens. These would just be appended via string concatenation. And depending on how badly we wrote our database code, our database code might have allowed this to execute and for the output of this to make its way back to the web browser.<br><br>So how can we avoid this? By using a prepared statement, SQL injection like this is not possible because with a prepared statement, every parameter that we're expecting to read in is constrained to just it's one little bit of data. So in other words, this name Max here is the only value that can actually be allowed in here, and all the rest of the text would just cause an exception to be thrown.</p><p><strong>The rule to live by when when you're writing JDBC code and you've got parameters that you need to bind to outside data. Always use a prepared statement. That will save you from this particular level of SQL injection.</strong></p><h3 id="mcetoc_1gc0q0084hv">Find Person by Id</h3><p>Now let's implement the function to query a Person by ID:</p><p>repository/PeopleRepositoryTests.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canFindPersonById</span><span class="hljs-params">()</span> </span>{
Person savedPerson = repo.save(<span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Test"</span>, <span class="hljs-string" style="color: #6a8759;">"Jackson"</span>, ZonedDateTime.now()));
Person foundPerson = repo.findById(savedPerson.getId());
assertThat(foundPerson).isEqualTo(savedPerson);
}</pre><p>this forces us to implement some methods like these:</p><p>model/Person.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">boolean</span> <span class="hljs-title" style="color: #ffc66d;">equals</span><span class="hljs-params">(Object o)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">if</span> (<span class="hljs-keyword" style="color: #cc7832;">this</span> == o) <span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">true</span>;
<span class="hljs-keyword" style="color: #cc7832;">if</span> (!(o <span class="hljs-keyword" style="color: #cc7832;">instanceof</span> Person)) <span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">false</span>;
Person person = (Person) o;
<span class="hljs-keyword" style="color: #cc7832;">return</span> Objects.equals(id, person.id) && firstName.equals(person.firstName) && lastName.equals(person.lastName) && dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)).equals(person.dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)));
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">int</span> <span class="hljs-title" style="color: #ffc66d;">hashCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> Objects.hash(id, firstName, lastName, dob);
}</pre><p>model/PersonTest.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.model;
<span class="hljs-keyword" style="color: #cc7832;">import</span> org.junit.jupiter.api.Test;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZoneId;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">import</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> org.assertj.core.api.Assertions.assertThat;
<span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">PersonTest</span> </span>{
<span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">testForEquality</span><span class="hljs-params">()</span> </span>{
Person p1 = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"p1"</span>, <span class="hljs-string" style="color: #6a8759;">"smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">2000</span>,<span class="hljs-number" style="color: #6897bb;">9</span>,<span class="hljs-number" style="color: #6897bb;">1</span>,<span class="hljs-number" style="color: #6897bb;">12</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-1"</span>)));
Person p2 = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"p1"</span>, <span class="hljs-string" style="color: #6a8759;">"smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">2000</span>,<span class="hljs-number" style="color: #6897bb;">9</span>,<span class="hljs-number" style="color: #6897bb;">1</span>,<span class="hljs-number" style="color: #6897bb;">12</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-1"</span>)));
assertThat(p1).isEqualTo(p2);
}
<span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">testForInequality</span><span class="hljs-params">()</span> </span>{
Person p1 = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"p1"</span>, <span class="hljs-string" style="color: #6a8759;">"smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">2000</span>,<span class="hljs-number" style="color: #6897bb;">9</span>,<span class="hljs-number" style="color: #6897bb;">1</span>,<span class="hljs-number" style="color: #6897bb;">12</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-1"</span>)));
Person p2 = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"p2"</span>, <span class="hljs-string" style="color: #6a8759;">"smith"</span>, ZonedDateTime.of(<span class="hljs-number" style="color: #6897bb;">2000</span>,<span class="hljs-number" style="color: #6897bb;">9</span>,<span class="hljs-number" style="color: #6897bb;">1</span>,<span class="hljs-number" style="color: #6897bb;">12</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>,<span class="hljs-number" style="color: #6897bb;">0</span>, ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"-1"</span>)));
assertThat(p1).isNotEqualTo(p2);
}
}</pre><p>repository/PeopleRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Person <span class="hljs-title" style="color: #ffc66d;">findById</span><span class="hljs-params">(Long id)</span> </span>{
Person person = <span class="hljs-keyword" style="color: #cc7832;">null</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(GET_PERSON_BY_ID);
ps.setLong(<span class="hljs-number" style="color: #6897bb;">1</span>, id);
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
<span class="hljs-keyword" style="color: #cc7832;">long</span> personID = rs.getLong(<span class="hljs-string" style="color: #6a8759;">"ID"</span>);
String firstName = rs.getString(<span class="hljs-string" style="color: #6a8759;">"FIRST_NAME"</span>);
String lastName = rs.getString(<span class="hljs-string" style="color: #6a8759;">"LAST_NAME"</span>);
ZonedDateTime dob = ZonedDateTime.of(rs.getTimestamp(<span class="hljs-string" style="color: #6a8759;">"DOB"</span>).toLocalDateTime(), ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>));
person = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(firstName, lastName, dob);
person.setId(personID);
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> person;
}</pre><p>But let's also add a negative test case:</p><p>repository/PeopleRepositoryTests.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">testPersonIdNotFound</span><span class="hljs-params">()</span> </span>{
Optional<Person> foundPerson = repo.findById(-<span class="hljs-number" style="color: #6897bb;">1L</span>);
assertThat(foundPerson).isEmpty();
}</pre><p>repository/PeopleRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Optional<Person> <span class="hljs-title" style="color: #ffc66d;">findById</span><span class="hljs-params">(Long id)</span> </span>{
Person person = <span class="hljs-keyword" style="color: #cc7832;">null</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(GET_PERSON_BY_ID);
ps.setLong(<span class="hljs-number" style="color: #6897bb;">1</span>, id);
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
<span class="hljs-keyword" style="color: #cc7832;">long</span> personID = rs.getLong(<span class="hljs-string" style="color: #6a8759;">"ID"</span>);
String firstName = rs.getString(<span class="hljs-string" style="color: #6a8759;">"FIRST_NAME"</span>);
String lastName = rs.getString(<span class="hljs-string" style="color: #6a8759;">"LAST_NAME"</span>);
ZonedDateTime dob = ZonedDateTime.of(rs.getTimestamp(<span class="hljs-string" style="color: #6a8759;">"DOB"</span>).toLocalDateTime(), ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>));
person = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(firstName, lastName, dob);
person.setId(personID);
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> Optional.ofNullable(person);
}</pre><h3 id="mcetoc_1gc0q0084i0">Delete one or more persons</h3><p>Let's implement the function to delete one or more persons:</p><p>repository/PeopleRepositoryTests.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canDeleteOnePerson</span><span class="hljs-params">()</span> </span>{
Person savedPerson = repo.save(<span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Test"</span>, <span class="hljs-string" style="color: #6a8759;">"Jackson"</span>, ZonedDateTime.now()));
<span class="hljs-keyword" style="color: #cc7832;">long</span> startCount = repo.count();
repo.delete(savedPerson);
<span class="hljs-keyword" style="color: #cc7832;">long</span> endCount = repo.count();
assertThat(endCount).isEqualTo(startCount-<span class="hljs-number" style="color: #6897bb;">1</span>);
}
<span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canDeleteMultiplePerson</span><span class="hljs-params">()</span> </span>{
Person p1 = repo.save(<span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Test1"</span>, <span class="hljs-string" style="color: #6a8759;">"Jackson"</span>, ZonedDateTime.now()));
Person p2 = repo.save(<span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Test2"</span>, <span class="hljs-string" style="color: #6a8759;">"Jackson"</span>, ZonedDateTime.now()));
<span class="hljs-keyword" style="color: #cc7832;">long</span> startCount = repo.count();
repo.delete(p1, p2);
<span class="hljs-keyword" style="color: #cc7832;">long</span> endCount = repo.count();
assertThat(endCount).isEqualTo(startCount -<span class="hljs-number" style="color: #6897bb;">2</span>);
}</pre><p>repository/PeopleRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">long</span> <span class="hljs-title" style="color: #ffc66d;">count</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">long</span> count = <span class="hljs-number" style="color: #6897bb;">0</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(<span class="hljs-string" style="color: #6a8759;">"SELECT COUNT(*) FROM PEOPLE"</span>);
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">if</span> (rs.next()) {
count = rs.getLong(<span class="hljs-number" style="color: #6897bb;">1</span>);
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
e.printStackTrace();
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> count;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">delete</span><span class="hljs-params">(Person person)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(<span class="hljs-string" style="color: #6a8759;">"DELETE FROM PEOPLE WHERE ID=?"</span>);
ps.setLong(<span class="hljs-number" style="color: #6897bb;">1</span>, person.getId());
<span class="hljs-keyword" style="color: #cc7832;">int</span> recordsAffected = ps.executeUpdate();
System.out.println(recordsAffected);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">delete</span><span class="hljs-params">(Person...people)</span> </span>{
<span class="hljs-comment" style="color: grey;">// This would be the easiest Option to delete people,</span>
<span class="hljs-comment" style="color: grey;">// however from a DB view it's not the most efficient:</span>
<span class="hljs-comment" style="color: grey;">// for (Person person : people) {</span>
<span class="hljs-comment" style="color: grey;">// delete(person);</span>
<span class="hljs-comment" style="color: grey;">// }</span>
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
<span class="hljs-comment" style="color: grey;">// - Unfortunately the current version of H2 DB does not support a prepared SQL statement for this.</span>
<span class="hljs-comment" style="color: grey;">// - This will make us vulnerable to SQL injection, but for demo purposes we do it anyway</span>
<span class="hljs-comment" style="color: grey;">// - This should never be used in production</span>
Statement stmt = connection.createStatement();
String ids = Arrays.stream(people).toList().stream()
.map(person -> person.getId().toString())
.collect(Collectors.joining(<span class="hljs-string" style="color: #6a8759;">","</span>));
<span class="hljs-keyword" style="color: #cc7832;">int</span> affectedRecordCount = stmt.executeUpdate(<span class="hljs-string" style="color: #6a8759;">"DELETE FROM PEOPLE WHERE ID IN (:ids)"</span>.replace(<span class="hljs-string" style="color: #6a8759;">":ids"</span>, ids));
System.out.println(affectedRecordCount);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
}</pre><h3 id="mcetoc_1gc8qakok1a8">Update a person</h3><p>We need a method to update existing data records. What if we need to change an existing person record because of a change in the timezone?</p><p>repository/PeopleRepositoryTests.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-meta" style="color: #bbb529;">@Test</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">canUpdate</span><span class="hljs-params">()</span> </span>{
Person savedPerson = repo.save(<span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Test2"</span>, <span class="hljs-string" style="color: #6a8759;">"Jackson"</span>, ZonedDateTime.now()));
Person p1 = repo.findById(savedPerson.getId()).get();
savedPerson.setSalary(<span class="hljs-keyword" style="color: #cc7832;">new</span> BigDecimal(<span class="hljs-string" style="color: #6a8759;">"7300.28"</span>));
repo.update(savedPerson);
Person P2 = repo.findById(savedPerson.getId()).get();
assertThat(P2.getSalary()).isNotEqualTo(p1.getSalary());
}</pre><p>repository/PeopleRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"> <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">update</span><span class="hljs-params">(Person person)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(<span class="hljs-string" style="color: #6a8759;">"UPDATE PEOPLE SET FIRST_NAME=?, LAST_NAME=?, DOB=?, SALARY=? WHERE ID=?"</span>);
ps.setString(<span class="hljs-number" style="color: #6897bb;">1</span>, person.getFirstName());
ps.setString(<span class="hljs-number" style="color: #6897bb;">2</span>, person.getLastName());
ps.setTimestamp(<span class="hljs-number" style="color: #6897bb;">3</span>, convertODBtoTimeStamp(person.getDob()));
ps.setBigDecimal(<span class="hljs-number" style="color: #6897bb;">4</span>, person.getSalary());
ps.setLong(<span class="hljs-number" style="color: #6897bb;">5</span>, person.getId());
ps.executeUpdate();
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">private</span> Timestamp <span class="hljs-title" style="color: #ffc66d;">convertODBtoTimeStamp</span><span class="hljs-params">(ZonedDateTime dob)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> Timestamp.valueOf(dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)).toLocalDateTime());
}</pre><h2 id="mcetoc_1gc8r84pi1ab">Making it reusable</h2><p>Let's further improve and optimize our existing classes and even make them reusable. We start by extracting the <em>save</em> method of the <em>PeopleRepository</em> class into a new class called <em>CRUDRepository.</em> Let's also extend the <em>PeopleRepository</em> class with the new <em>CRUDRepository</em> class.</p><p>As a starting point we just copy paste the save method to the new class. Now we want to see what parts of this method are the parts that would be unique to a class that might extend this? And what parts would be kind of boilerplate? You know, like the stuff that would be the same any time you had to create a repository class? One more goal of the refactoring is to replace all Person class calls with a capital T to make our new class capable to work with generics. Lets look at the result:</p><p>model/Entity.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.model;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">interface</span> <span class="hljs-title" style="color: #ffc66d;">Entity</span> </span>{
<span class="hljs-function">Long <span class="hljs-title" style="color: #ffc66d;">getId</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setId</span><span class="hljs-params">(Long id)</span></span>;
}
</pre><p>model/Person.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.model;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.math.BigDecimal;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZoneId;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.Objects;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">Person</span> <span class="hljs-keyword" style="color: #cc7832;">implements</span> <span class="hljs-title" style="color: #ffc66d;">Entity</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">private</span> Long id;
<span class="hljs-keyword" style="color: #cc7832;">private</span> String firstName;
<span class="hljs-keyword" style="color: #cc7832;">private</span> String lastName;
<span class="hljs-keyword" style="color: #cc7832;">private</span> ZonedDateTime dob;
<span class="hljs-keyword" style="color: #cc7832;">private</span> BigDecimal salary = BigDecimal.ZERO;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(String firstName, String lastName, ZonedDateTime odb)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.firstName = firstName;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.lastName = lastName;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.dob = odb;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(Long id, String firstName, String lastName, ZonedDateTime dob)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>(firstName, lastName, dob);
<span class="hljs-keyword" style="color: #cc7832;">this</span>.id = id;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(<span class="hljs-keyword" style="color: #cc7832;">long</span> id, String firstName, String lastName, ZonedDateTime dob, BigDecimal salary)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>(id, firstName, lastName, dob);
<span class="hljs-keyword" style="color: #cc7832;">this</span>.salary = salary;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Long <span class="hljs-title" style="color: #ffc66d;">getId</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> id;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setId</span><span class="hljs-params">(Long id)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.id = id;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">getFirstName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> firstName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setFirstName</span><span class="hljs-params">(String firstName)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.firstName = firstName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">getLastName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> lastName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setLastName</span><span class="hljs-params">(String lastName)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.lastName = lastName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> ZonedDateTime <span class="hljs-title" style="color: #ffc66d;">getDob</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> dob;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setDob</span><span class="hljs-params">(ZonedDateTime dob)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.dob = dob;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> BigDecimal <span class="hljs-title" style="color: #ffc66d;">getSalary</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> salary;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setSalary</span><span class="hljs-params">(BigDecimal salary)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.salary = salary;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-string" style="color: #6a8759;">"Person{"</span> +
<span class="hljs-string" style="color: #6a8759;">"id="</span> + id +
<span class="hljs-string" style="color: #6a8759;">", firstName='"</span> + firstName + <span class="hljs-string" style="color: #6a8759;">'\''</span> +
<span class="hljs-string" style="color: #6a8759;">", lastName='"</span> + lastName + <span class="hljs-string" style="color: #6a8759;">'\''</span> +
<span class="hljs-string" style="color: #6a8759;">", dob="</span> + dob +
<span class="hljs-string" style="color: #6a8759;">'}'</span>;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">boolean</span> <span class="hljs-title" style="color: #ffc66d;">equals</span><span class="hljs-params">(Object o)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">if</span> (<span class="hljs-keyword" style="color: #cc7832;">this</span> == o) <span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">true</span>;
<span class="hljs-keyword" style="color: #cc7832;">if</span> (!(o <span class="hljs-keyword" style="color: #cc7832;">instanceof</span> Person)) <span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">false</span>;
Person person = (Person) o;
<span class="hljs-keyword" style="color: #cc7832;">return</span> Objects.equals(id, person.id) && firstName.equals(person.firstName) && lastName.equals(person.lastName) &&
dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)).equals(person.dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)));
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">int</span> <span class="hljs-title" style="color: #ffc66d;">hashCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> Objects.hash(id, firstName, lastName, dob);
}
}
</pre><p>repository/CRUDRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.repository;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.Entity;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.Person;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.sql.*;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.ArrayList;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.Arrays;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.List;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.Optional;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.stream.Collectors;
<span class="hljs-keyword" style="color: #cc7832;">abstract</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">CRUDRepository</span><<span class="hljs-title" style="color: #ffc66d;">T</span> <span class="hljs-keyword" style="color: #cc7832;">extends</span> <span class="hljs-title" style="color: #ffc66d;">Entity</span>> </span>{
<span class="hljs-keyword" style="color: #cc7832;">protected</span> Connection connection;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">CRUDRepository</span><span class="hljs-params">(Connection connection)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.connection = connection;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> T <span class="hljs-title" style="color: #ffc66d;">save</span><span class="hljs-params">(T entity)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getSaveSql(), Statement.RETURN_GENERATED_KEYS);
mapForSave(entity, ps);
<span class="hljs-keyword" style="color: #cc7832;">int</span> recordsAffected = ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
<span class="hljs-keyword" style="color: #cc7832;">long</span> id = rs.getLong(<span class="hljs-number" style="color: #6897bb;">1</span>);
entity.setId(id);
System.out.println(entity);
}
System.out.printf(<span class="hljs-string" style="color: #6a8759;">"Records affected: %d%n"</span>, recordsAffected);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> entity;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Optional<T> <span class="hljs-title" style="color: #ffc66d;">findById</span><span class="hljs-params">(Long id)</span> </span>{
T entity = <span class="hljs-keyword" style="color: #cc7832;">null</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getFindByIdSql());
ps.setLong(<span class="hljs-number" style="color: #6897bb;">1</span>, id);
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
entity = extractEntityFromResultSet(rs);
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> Optional.ofNullable(entity);
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> <span class="hljs-keyword" style="color: #cc7832;">abstract</span> String <span class="hljs-title" style="color: #ffc66d;">getFindAllSql</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> List<T> <span class="hljs-title" style="color: #ffc66d;">findAll</span><span class="hljs-params">()</span> </span>{
List<T> entities = <span class="hljs-keyword" style="color: #cc7832;">new</span> ArrayList<>();
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getFindAllSql());
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
entities.add(extractEntityFromResultSet(rs));
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
e.printStackTrace();
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> entities;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">long</span> <span class="hljs-title" style="color: #ffc66d;">count</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">long</span> count = <span class="hljs-number" style="color: #6897bb;">0</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getCountSql());
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">if</span> (rs.next()) {
count = rs.getLong(<span class="hljs-number" style="color: #6897bb;">1</span>);
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
e.printStackTrace();
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> count;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">delete</span><span class="hljs-params">(T entity)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getDeleteSql());
ps.setLong(<span class="hljs-number" style="color: #6897bb;">1</span>, entity.getId());
<span class="hljs-keyword" style="color: #cc7832;">int</span> recordsAffected = ps.executeUpdate();
System.out.println(recordsAffected);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">delete</span><span class="hljs-params">(T...entities)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
Statement stmt = connection.createStatement();
String ids = Arrays.stream(entities).map(T::getId).map(String::valueOf).collect(Collectors.joining(<span class="hljs-string" style="color: #6a8759;">","</span>));
<span class="hljs-keyword" style="color: #cc7832;">int</span> affectedRecordCount = stmt.executeUpdate(getDeleteInSql().replace(<span class="hljs-string" style="color: #6a8759;">":ids"</span>, ids));
System.out.println(affectedRecordCount);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">update</span><span class="hljs-params">(T entity)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getUpdateSql());
mapForUpdate(entity, ps);
ps.setLong(<span class="hljs-number" style="color: #6897bb;">5</span>, entity.getId());
ps.executeUpdate();
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> <span class="hljs-keyword" style="color: #cc7832;">abstract</span> String <span class="hljs-title" style="color: #ffc66d;">getUpdateSql</span><span class="hljs-params">()</span></span>;
<span class="hljs-comment" style="color: grey;">/**
*
* <span class="hljs-doctag">@return</span> should return a SQL string like:
* "DELETE FROM PEOPLE WHERE ID IN (:ids)"
* Be sure to include the '(:ids)' named parameter & call it 'ids'
*/</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> <span class="hljs-keyword" style="color: #cc7832;">abstract</span> String <span class="hljs-title" style="color: #ffc66d;">getDeleteInSql</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> <span class="hljs-keyword" style="color: #cc7832;">abstract</span> String <span class="hljs-title" style="color: #ffc66d;">getDeleteSql</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> <span class="hljs-keyword" style="color: #cc7832;">abstract</span> String <span class="hljs-title" style="color: #ffc66d;">getCountSql</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">abstract</span> T <span class="hljs-title" style="color: #ffc66d;">extractEntityFromResultSet</span><span class="hljs-params">(ResultSet rs)</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException</span>;
<span class="hljs-comment" style="color: grey;">/**
*
* <span class="hljs-doctag">@return</span> Returns a String that represents the SQL needed to retrive one entity.
* The SQL must contain one SQL parameter, i.e. "?", that will bind to the
* entity's ID.
*/</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> <span class="hljs-keyword" style="color: #cc7832;">abstract</span> String <span class="hljs-title" style="color: #ffc66d;">getFindByIdSql</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">abstract</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">mapForSave</span><span class="hljs-params">(T entity, PreparedStatement ps)</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException</span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">abstract</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">mapForUpdate</span><span class="hljs-params">(T entity, PreparedStatement ps)</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException</span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">abstract</span> String <span class="hljs-title" style="color: #ffc66d;">getSaveSql</span><span class="hljs-params">()</span></span>;
}
</pre><p>repository/PeopleRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.repository;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.Person;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.math.BigDecimal;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.sql.*;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZoneId;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">PeopleRepository</span> <span class="hljs-keyword" style="color: #cc7832;">extends</span> <span class="hljs-title" style="color: #ffc66d;">CRUDRepository</span><<span class="hljs-title" style="color: #ffc66d;">Person</span>> </span>{
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> <span class="hljs-keyword" style="color: #cc7832;">final</span> String SAVE_PERSON_SQL = String.format(<span class="hljs-string" style="color: #6a8759;">"INSERT INTO PEOPLE (FIRST_NAME, LAST_NAME, DOB) VALUES(?,?,?)"</span>);
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> <span class="hljs-keyword" style="color: #cc7832;">final</span> String FIND_BY_ID_SQL = String.format(<span class="hljs-string" style="color: #6a8759;">"SELECT ID, FIRST_NAME, LAST_NAME, DOB, SALARY FROM PEOPLE WHERE ID=?"</span>);
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> <span class="hljs-keyword" style="color: #cc7832;">final</span> String FIND_ALL_SQL = String.format(<span class="hljs-string" style="color: #6a8759;">"SELECT ID, FIRST_NAME, LAST_NAME, DOB, SALARY FROM PEOPLE"</span>);
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> <span class="hljs-keyword" style="color: #cc7832;">final</span> String SELECT_COUNT_SQL = <span class="hljs-string" style="color: #6a8759;">"SELECT COUNT(*) FROM PEOPLE"</span>;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> <span class="hljs-keyword" style="color: #cc7832;">final</span> String DELETE_SQL = <span class="hljs-string" style="color: #6a8759;">"DELETE FROM PEOPLE WHERE ID=?"</span>;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> <span class="hljs-keyword" style="color: #cc7832;">final</span> String DELETE_IN_SQL = <span class="hljs-string" style="color: #6a8759;">"DELETE FROM PEOPLE WHERE ID IN (:ids)"</span>;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">static</span> <span class="hljs-keyword" style="color: #cc7832;">final</span> String UPDATE_SQL = <span class="hljs-string" style="color: #6a8759;">"UPDATE PEOPLE SET FIRST_NAME=?, LAST_NAME=?, DOB=?, SALARY=? WHERE ID=?"</span>;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">PeopleRepository</span><span class="hljs-params">(Connection connection)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">super</span>(connection);
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function">String <span class="hljs-title" style="color: #ffc66d;">getSaveSql</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> SAVE_PERSON_SQL;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">mapForSave</span><span class="hljs-params">(Person entity, PreparedStatement ps)</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException </span>{
ps.setString(<span class="hljs-number" style="color: #6897bb;">1</span>, entity.getFirstName());
ps.setString(<span class="hljs-number" style="color: #6897bb;">2</span>, entity.getLastName());
ps.setTimestamp(<span class="hljs-number" style="color: #6897bb;">3</span>, convertODBtoTimeStamp(entity.getDob()));
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function">Person <span class="hljs-title" style="color: #ffc66d;">extractEntityFromResultSet</span><span class="hljs-params">(ResultSet rs)</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException </span>{
<span class="hljs-keyword" style="color: #cc7832;">long</span> personID = rs.getLong(<span class="hljs-string" style="color: #6a8759;">"ID"</span>);
String firstName = rs.getString(<span class="hljs-string" style="color: #6a8759;">"FIRST_NAME"</span>);
String lastName = rs.getString(<span class="hljs-string" style="color: #6a8759;">"LAST_NAME"</span>);
ZonedDateTime dob = ZonedDateTime.of(rs.getTimestamp(<span class="hljs-string" style="color: #6a8759;">"DOB"</span>).toLocalDateTime(), ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>));
BigDecimal salary = rs.getBigDecimal(<span class="hljs-string" style="color: #6a8759;">"SALARY"</span>);
<span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(personID, firstName, lastName, dob, salary);
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">mapForUpdate</span><span class="hljs-params">(Person entity, PreparedStatement ps)</span> <span class="hljs-keyword" style="color: #cc7832;">throws</span> SQLException </span>{
ps.setString(<span class="hljs-number" style="color: #6897bb;">1</span>, entity.getFirstName());
ps.setString(<span class="hljs-number" style="color: #6897bb;">2</span>, entity.getLastName());
ps.setTimestamp(<span class="hljs-number" style="color: #6897bb;">3</span>, convertODBtoTimeStamp(entity.getDob()));
ps.setBigDecimal(<span class="hljs-number" style="color: #6897bb;">4</span>, entity.getSalary());
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> String <span class="hljs-title" style="color: #ffc66d;">getFindByIdSql</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> FIND_BY_ID_SQL;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> String <span class="hljs-title" style="color: #ffc66d;">getFindAllSql</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> FIND_ALL_SQL;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> String <span class="hljs-title" style="color: #ffc66d;">getCountSql</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> SELECT_COUNT_SQL;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> String <span class="hljs-title" style="color: #ffc66d;">getDeleteSql</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> DELETE_SQL;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> String <span class="hljs-title" style="color: #ffc66d;">getDeleteInSql</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> DELETE_IN_SQL;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">protected</span> String <span class="hljs-title" style="color: #ffc66d;">getUpdateSql</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> UPDATE_SQL;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">private</span> Timestamp <span class="hljs-title" style="color: #ffc66d;">convertODBtoTimeStamp</span><span class="hljs-params">(ZonedDateTime dob)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> Timestamp.valueOf(dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)).toLocalDateTime());
}
}
</pre><h2 id="mcetoc_1gc9c3hup1b5">Improve the SQL statement calls</h2><p>We had to pepper this class with these extra getter and setter methods to provider the SQL statements. But there are frameworks that enable us to do this kind of thing in a better way. We're going to give our <em>CRUDRepository</em> the ability to get the SQL queries without having to implement these abstract methods.<br><br>We can do this by using the Reflection API of Java. The Reflection API is pretty much only used by frameworks, but it just so happens that as we are creating this <em>CRUDRepository</em> functionality, we are basically creating a poor man's framework. So let's go a bit further down this rabbit hole and dig into the Reflection API a little bit.<br><br>This is the big picture: Instead of having to override and implement these various scatter methods to return the SQL, a more modern way of doing the equivalent to this with a lot of modern frameworks would be to actually make use of an annotation so we could have an annotation so we could introduce and create our own annotation. In that annotation, we could specify the SQL that we want, and then our <em>CRUDRepository</em> could dynamically, at runtime, learn the SQL that it needs from the annotation and thereby we would no longer need these methods.</p><p>The Reflection API allows us to write Java code to that allows us to analyze our Java code. This allows us to analyse our code in runtime and to things with it.</p><p>annotation/Id.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.annotation;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.lang.annotation.Retention;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.lang.annotation.RetentionPolicy;
<span class="hljs-meta" style="color: #bbb529;">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-meta" style="color: #bbb529;">@interface</span> Id {
}
</pre><p>annotation/MultiSQL.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.annotation;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.lang.annotation.Retention;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.lang.annotation.RetentionPolicy;
<span class="hljs-meta" style="color: #bbb529;">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-meta" style="color: #bbb529;">@interface</span> MultiSQL{
SQL[] value();
}
</pre><p>annotation/SQL.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.annotation;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.CrudOperation;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.lang.annotation.Repeatable;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.lang.annotation.Retention;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.lang.annotation.RetentionPolicy;
<span class="hljs-meta" style="color: #bbb529;">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta" style="color: #bbb529;">@Repeatable</span>(MultiSQL.class)
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-meta" style="color: #bbb529;">@interface</span> SQL {
<span class="hljs-function">String <span class="hljs-title" style="color: #ffc66d;">value</span><span class="hljs-params">()</span></span>;
<span class="hljs-function">CrudOperation <span class="hljs-title" style="color: #ffc66d;">operationType</span><span class="hljs-params">()</span></span>;
}
</pre><p>model/CrudOperation.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.model;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">enum</span> CrudOperation {
SAVE,
UPDATE,
FIND_BY_ID,
FIND_ALL,
DELETE_ONE,
DELETE_MANY,
COUNT
}
</pre><p>model/Person.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.model;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.annotation.Id;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.math.BigDecimal;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZoneId;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.time.ZonedDateTime;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.Objects;
<span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">Person</span> </span>{
<span class="hljs-meta" style="color: #bbb529;">@Id</span>
<span class="hljs-keyword" style="color: #cc7832;">private</span> Long id;
<span class="hljs-keyword" style="color: #cc7832;">private</span> String firstName;
<span class="hljs-keyword" style="color: #cc7832;">private</span> String lastName;
<span class="hljs-keyword" style="color: #cc7832;">private</span> ZonedDateTime dob;
<span class="hljs-keyword" style="color: #cc7832;">private</span> BigDecimal salary = BigDecimal.ZERO;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(String firstName, String lastName, ZonedDateTime odb)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.firstName = firstName;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.lastName = lastName;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.dob = odb;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(Long id, String firstName, String lastName, ZonedDateTime dob)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>(firstName, lastName, dob);
<span class="hljs-keyword" style="color: #cc7832;">this</span>.id = id;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">Person</span><span class="hljs-params">(<span class="hljs-keyword" style="color: #cc7832;">long</span> id, String firstName, String lastName, ZonedDateTime dob, BigDecimal salary)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>(id, firstName, lastName, dob);
<span class="hljs-keyword" style="color: #cc7832;">this</span>.salary = salary;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Long <span class="hljs-title" style="color: #ffc66d;">getId</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> id;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setId</span><span class="hljs-params">(Long id)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.id = id;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">getFirstName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> firstName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setFirstName</span><span class="hljs-params">(String firstName)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.firstName = firstName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">getLastName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> lastName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setLastName</span><span class="hljs-params">(String lastName)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.lastName = lastName;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> ZonedDateTime <span class="hljs-title" style="color: #ffc66d;">getDob</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> dob;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setDob</span><span class="hljs-params">(ZonedDateTime dob)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.dob = dob;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> BigDecimal <span class="hljs-title" style="color: #ffc66d;">getSalary</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> salary;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">setSalary</span><span class="hljs-params">(BigDecimal salary)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.salary = salary;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> String <span class="hljs-title" style="color: #ffc66d;">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-string" style="color: #6a8759;">"Person{"</span> +
<span class="hljs-string" style="color: #6a8759;">"id="</span> + id +
<span class="hljs-string" style="color: #6a8759;">", firstName='"</span> + firstName + <span class="hljs-string" style="color: #6a8759;">'\''</span> +
<span class="hljs-string" style="color: #6a8759;">", lastName='"</span> + lastName + <span class="hljs-string" style="color: #6a8759;">'\''</span> +
<span class="hljs-string" style="color: #6a8759;">", dob="</span> + dob +
<span class="hljs-string" style="color: #6a8759;">'}'</span>;
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">boolean</span> <span class="hljs-title" style="color: #ffc66d;">equals</span><span class="hljs-params">(Object o)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">if</span> (<span class="hljs-keyword" style="color: #cc7832;">this</span> == o) <span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">true</span>;
<span class="hljs-keyword" style="color: #cc7832;">if</span> (!(o <span class="hljs-keyword" style="color: #cc7832;">instanceof</span> Person)) <span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">false</span>;
Person person = (Person) o;
<span class="hljs-keyword" style="color: #cc7832;">return</span> Objects.equals(id, person.id) && firstName.equals(person.firstName) && lastName.equals(person.lastName) &&
dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)).equals(person.dob.withZoneSameInstant(ZoneId.of(<span class="hljs-string" style="color: #6a8759;">"+0"</span>)));
}
<span class="hljs-meta" style="color: #bbb529;">@Override</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">int</span> <span class="hljs-title" style="color: #ffc66d;">hashCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> Objects.hash(id, firstName, lastName, dob);
}
}
</pre><p>repository/CRUDRepository.java</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e none repeat scroll 0% 0%; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">package</span> ch.finecloud.peopledb.repository;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.annotation.Id;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.annotation.MultiSQL;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.annotation.SQL;
<span class="hljs-keyword" style="color: #cc7832;">import</span> ch.finecloud.peopledb.model.CrudOperation;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.sql.*;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.ArrayList;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.Arrays;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.List;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.Optional;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.function.Supplier;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.stream.Collectors;
<span class="hljs-keyword" style="color: #cc7832;">import</span> java.util.stream.Stream;
<span class="hljs-keyword" style="color: #cc7832;">abstract</span> <span class="hljs-class"><span class="hljs-keyword" style="color: #cc7832;">class</span> <span class="hljs-title" style="color: #ffc66d;">CRUDRepository</span><<span class="hljs-title" style="color: #ffc66d;">T</span>> </span>{
<span class="hljs-keyword" style="color: #cc7832;">protected</span> Connection connection;
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-title" style="color: #ffc66d;">CRUDRepository</span><span class="hljs-params">(Connection connection)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.connection = connection;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> T <span class="hljs-title" style="color: #ffc66d;">save</span><span class="hljs-params">(T entity)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getSqlByAnnotation(CrudOperation.SAVE, <span class="hljs-keyword" style="color: #cc7832;">this</span>::getSaveSql), Statement.RETURN_GENERATED_KEYS);
mapForSave(entity, ps);
<span class="hljs-keyword" style="color: #cc7832;">int</span> recordsAffected = ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
<span class="hljs-keyword" style="color: #cc7832;">long</span> id = rs.getLong(<span class="hljs-number" style="color: #6897bb;">1</span>);
setIdByAnnotation(id, entity);
System.out.println(entity);
}
System.out.printf(<span class="hljs-string" style="color: #6a8759;">"Records affected: %d%n"</span>, recordsAffected);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> entity;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> Optional<T> <span class="hljs-title" style="color: #ffc66d;">findById</span><span class="hljs-params">(Long id)</span> </span>{
T entity = <span class="hljs-keyword" style="color: #cc7832;">null</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getSqlByAnnotation(CrudOperation.FIND_BY_ID, <span class="hljs-keyword" style="color: #cc7832;">this</span>::getFindByIdSql));
ps.setLong(<span class="hljs-number" style="color: #6897bb;">1</span>, id);
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
entity = extractEntityFromResultSet(rs);
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> Optional.ofNullable(entity);
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> List<T> <span class="hljs-title" style="color: #ffc66d;">findAll</span><span class="hljs-params">()</span> </span>{
List<T> entities = <span class="hljs-keyword" style="color: #cc7832;">new</span> ArrayList<>();
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getSqlByAnnotation(CrudOperation.FIND_ALL, <span class="hljs-keyword" style="color: #cc7832;">this</span>::getFindAllSql));
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">while</span> (rs.next()) {
entities.add(extractEntityFromResultSet(rs));
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
e.printStackTrace();
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> entities;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">long</span> <span class="hljs-title" style="color: #ffc66d;">count</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">long</span> count = <span class="hljs-number" style="color: #6897bb;">0</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getSqlByAnnotation(CrudOperation.COUNT, <span class="hljs-keyword" style="color: #cc7832;">this</span>::getCountSql));
ResultSet rs = ps.executeQuery();
<span class="hljs-keyword" style="color: #cc7832;">if</span> (rs.next()) {
count = rs.getLong(<span class="hljs-number" style="color: #6897bb;">1</span>);
}
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
e.printStackTrace();
}
<span class="hljs-keyword" style="color: #cc7832;">return</span> count;
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">public</span> <span class="hljs-keyword" style="color: #cc7832;">void</span> <span class="hljs-title" style="color: #ffc66d;">delete</span><span class="hljs-params">(T entity)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
PreparedStatement ps = connection.prepareStatement(getSqlByAnnotation(CrudOperation.DELETE_ONE, <span class="hljs-keyword" style="color: #cc7832;">this</span>::getDeleteSql));
ps.setLong(<span class="hljs-number" style="color: #6897bb;">1</span>, getIdByAnnotation(entity));
<span class="hljs-keyword" style="color: #cc7832;">int</span> recordsAffected = ps.executeUpdate();
System.out.println(recordsAffected);
} <span class="hljs-keyword" style="color: #cc7832;">catch</span> (SQLException e) {
<span class="hljs-keyword" style="color: #cc7832;">throw</span> <span class="hljs-keyword" style="color: #cc7832;">new</span> RuntimeException(e);
}
}
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">private</span> Long <span class="hljs-title" style="color: #ffc66d;">getIdByAnnotation</span><span class="hljs-params">(T entity)</span> </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> Arrays.stream(entity.getClass().getDeclaredFields())
.filter(f -> f.isAnnotationPresent(Id.class))
.map(f -> {
f.setAccessible(<span class="hljs-keyword" style="color: #cc7832;">true</span>);
Long id = <span class="hljs-keyword" style="color: #cc7832;">null</span>;
<span class="hljs-keyword" style="color: #cc7832;">try</span> {
id = (<span class="hljs-keyword" style="color: #cc7832;">long</span>)f.get(entity);