-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathkotlinMyBatis3.html
996 lines (887 loc) · 56.6 KB
/
kotlinMyBatis3.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
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 2.0.0-M18 from src/site/markdown/docs/kotlinMyBatis3.md at 03 Jun 2024
| Rendered using Apache Maven Fluido Skin 2.0.0-M9
-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="generator" content="Apache Maven Doxia Site Renderer 2.0.0-M18" />
<title>MyBatis Dynamic SQL</title>
<link rel="stylesheet" href="../css/apache-maven-fluido-2.0.0-M9.min.css" />
<link rel="stylesheet" href="../css/site.css" />
<link rel="stylesheet" href="../css/print.css" media="print" />
<script src="../js/apache-maven-fluido-2.0.0-M9.min.js"></script>
</head>
<body>
<div class="container-fluid container-fluid-top">
<header>
<div id="banner">
<div class="pull-left"><div id="bannerLeft"><h1><a href="../docs/introduction.html">MyBatis Dynamic SQL</a></h1></div></div>
<div class="pull-right"><div id="bannerRight"><h1><a href="http://www.mybatis.org/" class="externalLink"><img class="imageLink" src="https://mybatis.org/images/mybatis-logo.png" alt="MyBatis logo" /> MyBatis</a></h1></div></div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 03 Jun 2024<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 1.5.2</li>
</ul>
</div>
</header>
<div class="row-fluid">
<header id="leftColumn" class="span2">
<nav class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">User's Guide</li>
<li><a href="../docs/introduction.html">Introduction</a></li>
<li><a href="../docs/CHANGELOG.html">Change Log</a></li>
<li><a href="../docs/quickStart.html">Quick Start</a></li>
<li><a href="../docs/exceptions.html">Exceptions thrown by the Library</a></li>
<li><a href="../docs/configuration.html">Configuration of the Library</a></li>
<li><a href="../docs/databaseObjects.html">Modeling Database Objects</a></li>
<li><a href="../docs/whereClauses.html"><span class="icon-chevron-down"></span>WHERE Clause Support</a>
<ul class="nav nav-list">
<li><a href="../docs/conditions.html">WHERE Conditions</a></li>
</ul></li>
<li><a href="../docs/select.html"><span class="icon-chevron-down"></span>SELECT Statements</a>
<ul class="nav nav-list">
<li><a href="../docs/caseExpressions.html">Case Expressions</a></li>
<li><a href="../docs/complexQueries.html">Complex Queries</a></li>
</ul></li>
<li><a href="../docs/delete.html">DELETE Statements</a></li>
<li><a href="../docs/insert.html">INSERT Statements</a></li>
<li><a href="../docs/update.html">UPDATE Statements</a></li>
<li><a href="../docs/subQueries.html">SubQuery Support</a></li>
<li><a href="../docs/functions.html">Database Functions</a></li>
<li><a href="../docs/mybatis3.html">MyBatis3 Support</a></li>
<li><a href="../docs/spring.html">Spring Support</a></li>
<li><a href="../docs/springBatch.html">Spring Batch Support</a></li>
<li><a href="../docs/kotlinOverview.html"><span class="icon-chevron-down"></span>Kotlin Support</a>
<ul class="nav nav-list">
<li><a href="../docs/kotlinCaseExpressions.html">Kotlin Case Expressions</a></li>
<li><a href="../docs/kotlinWhereClauses.html">Kotlin Where Clauses</a></li>
<li class="active"><a>Kotlin Support for MyBatis3</a></li>
<li><a href="../docs/kotlinSpring.html">Kotlin Support for Spring</a></li>
</ul></li>
<li><a href="../docs/howItWorks.html">How it Works</a></li>
<li><a href="../docs/extending.html">Extending the Library</a></li>
<li><a href="../docs/codingStandards.html">Coding Standards</a></li>
<li><a href="../docs/motivation.html">Motivation</a></li>
<li class="nav-header">Project Documentation</li>
<li><a href="../project-info.html"><span class="icon-chevron-right"></span>Project Information</a></li>
<li><a href="../project-reports.html"><span class="icon-chevron-right"></span>Project Reports</a></li>
</ul>
</nav>
<div class="well sidebar-nav">
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<a href="https://maven.apache.org/" class="builtBy" target="_blank"><img class="builtBy" alt="Built by Maven" src="../images/logos/maven-feather.png" /></a>
</div>
</div>
</header>
<main id="bodyColumn" class="span10">
<section><a id="Kotlin_Support_for_MyBatis3"></a>
<h1>Kotlin Support for MyBatis3</h1>
<p>MyBatis Dynamic SQL includes Kotlin extensions for MyBatis3 that simplify execution of statements generated by the
library.</p>
<p>The standard usage patterns for MyBatis Dynamic SQL and MyBatis3 in Java must be modified somewhat for Kotlin.
Kotlin interfaces can contain both abstract and non-abstract methods (somewhat similar to Java's default methods in
an interface). Using these methods in Kotlin based mapper interfaces will cause a failure with MyBatis because of the
underlying Kotlin implementation.</p>
<p>This page will show our recommended pattern for using the MyBatis Dynamic SQL with Kotlin and MyBatis3.
The code shown on this page is from the <code>src/test/kotlin/examples/kotlin/mybatis3/canonical</code> directory in this
repository. That directory contains a complete example of using this library with Kotlin.</p>
<p>All Kotlin support is available in the following packages:</p>
<ul>
<li><code>org.mybatis.dynamic.sql.util.kotlin</code> - contains DSL support classes</li>
<li><code>org.mybatis.dynamic.sql.util.kotlin.elements</code> - contains the basic DSL elements common to all runtimes</li>
<li><code>org.mybatis.dynamic.sql.util.kotlin.mybatis3</code> - contains utilities specifically to simplify MyBatis3 based clients</li>
</ul>
<p>Using the support in these packages, it is possible to create reusable Kotlin classes, interfaces, and extension methods
that simplify usage of the library with MyBatis3.</p>
<p>The Kotlin support for MyBatis3 is implemented as utility functions that can be used with MyBatis3 mapper interfaces.
There are functions to support count, delete, insert, select, and update operations based on SQL generated by this
library. For each operation, there are two different methods of executing SQL:</p>
<ol style="list-style-type: decimal;">
<li>The first method is a two-step method. With this method you build SQL provider objects as shown on the Kotlin
overview page and then execute the generated SQL by passing the provider to a MyBatis3 mapper method</li>
<li>The second method is a one-step method that uses utility functions to combine these operations into a single step.
With this method it is common to build extension methods for MyBatis3 mappers that are specific to a table
(this is the code that MyBatis Generator will create)</li>
</ol>
<p>We will illustrate both approaches below.</p><section><a id="Kotlin_Dynamic_SQL_Support_Objects"></a>
<h2>Kotlin Dynamic SQL Support Objects</h2>
<p>The pattern for the meta-model is the same as shown on the Kotlin overview page. We'll repeat it here to show some
specifics for MyBatis3.</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.AlisableSqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column
import java.sql.JDBCType
import java.util.Date
object PersonDynamicSqlSupport {
val person = Person()
val id = person.id
val firstName = person.firstName
val lastName = person.lastName
val birthDate = person.birthDate
val employed = person.employed
val occupation = person.occupation
val addressId = person.addressId
class Person : AlisableSqlTable<Person>("Person", ::Person) {
val id = column<Int>(name = "id", jdbcType = JDBCType.INTEGER)
val firstName = column<String>(name = "first_name", jdbcType = JDBCType.VARCHAR)
val lastName = column(
name = "last_name",
jdbcType = JDBCType.VARCHAR,
typeHandler = "foo.bar.LastNameTypeHandler"
)
val birthDate = column<Date>(name = "birth_date", jdbcType = JDBCType.DATE)
val employed = column(
name = "employed",
jdbcType = JDBCType.VARCHAR,
typeHandler = "foo.bar.StringToBooleanTypeHandler"
)
val occupation = column<String>(name = "occupation", jdbcType = JDBCType.VARCHAR)
val addressId = column<Int>(name = "address_id", jdbcType = JDBCType.INTEGER)
}
}
</code></pre>
<p>Note the use of a “type handler” on the <code>employed</code> and <code>lastName</code> columns. This allows us to use the column as a Boolean in
Kotlin, but store the values “Yes” or “No” on the database. This uses the MyBatis3 standard type handler support.</p>
<p>Also note that we specify the “jdbcType” for each column. This is a best practice with MyBatis3 and will avoid errors
will nullable fields.</p></section><section><a id="About_MyBatis_Mappers"></a>
<h2>About MyBatis Mappers</h2>
<p>Many MyBatis operations can be standardized, and you can use functionality in this library to dramatically reduce the
amount of boilerplate code you need to write. In particular, all COUNT, DELETE, and UPDATE statements can be executed
with utilities built into the library. The examples below will show how this works.</p>
<p>Many INSERT statements can also be executed with built-in utilities. The only INSERT statements that require custom
coding are INSERT statements that return generated keys. For these statements, you must code a custom mapper method
with the MyBatis <code>@Options</code> annotation specifying how to retrieve generated keys.</p>
<p>SELECT statements present unique challenges. One of the key functions of MyBatis is the mapping of result sets to
objects. This is a very useful capability, but it requires that the mapping between result set and object be predefined
and hard coded. Some SELECT statements can be executed without coding custom result maps. This library includes common
SELECT support with the following capabilities:</p>
<ul>
<li>Execute arbitrary SELECT statements and return <code>List<Map<String, Object>></code> as the return value. This support
essentially bypasses MyBatis' result mapping capabilities and returns a low level list of results.</li>
<li>Execute SELECT statements that return a single column of various types (String, Integer, BigDecimal, etc.)</li>
</ul>
<p>The bottom line is this - if your query returns more than one column, and you want to utilize MyBatis' result mapping
functionality, you will need to code a custom result mapping.</p>
<p>This library was initially conceived as a tool to improve the code created by MyBatis Generator - and the “one step”
methods shown below are based on the convention used by MyBatis generator where a set of mapper methods is created
for each table individually. If you are not using MyBatis generator, or are adding custom queries such as join
queries to an application bootstrapped with MyBatis Generator, then it is likely you will need to code custom
SELECT methods with custom result maps.</p></section><section><a id="Kotlin_Mappers_for_MyBatis"></a>
<h2>Kotlin Mappers for MyBatis</h2>
<p>The pattern we recommend involves two types of mapper methods: standard MyBatis mapper methods and extension methods.</p>
<p>The standard MyBatis mapper abstract methods accept Provider objects created by the library. These methods use the
normal MyBatis annotations to specify result mappings, generated key mappings, statement types, etc. Using these
methods directly involves two steps: create the provider object, then execute the MyBatis call.</p>
<p>The extension methods will reuse the abstract methods and add functionality to mappers that will build and
execute the SQL statements in a one-step process. The extension methods shown below assume that you will create
a set of CRUD methods for each table you are accessing (as is the case with code created by MyBatis Generator).</p>
<p>If you create a Kotlin mapper interface that includes both abstract and non-abstract methods, MyBatis will
throw errors. By default, Kotlin does not create Java default methods in an interface. For this reason, Kotlin
mapper interfaces should only contain the actual MyBatis mapper abstract interface methods. What would normally be coded
as default or static methods in a Java mapper interface should be coded as extension methods in Kotlin. For example,
a simple MyBatis mapper could be coded like this:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@SelectProvider(type = SqlProviderAdapter::class, method = "select")
@Results(id = "PersonRecordResult", value = [
Result(column = "a_id", property = "id"),
Result(column = "first_name", property = "firstName"),
Result(column = "last_name", property = "lastName"),
Result(column = "birth_date", property = "birthDate"),
Result(column = "employed", property = "employed", typeHandler = YesNoTypeHandler::class),
Result(column = "occupation", property = "occupation"),
Result(column = "address_id", property = "addressId")
])
fun selectMany(selectStatement: SelectStatementProvider): List<PersonRecord>
}
</code></pre>
<p>Then extensions could be added to make a shortcut method as follows:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectList
import org.mybatis.dynamic.sql.util.kotlin.elements.`as`
private val columnList = listOf(id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId)
fun PersonMapper.select(completer: SelectCompleter) =
selectList(this::selectMany, columnList, Person, completer)
</code></pre>
<p>The extension method shows the use of the <code>SelectCompleter</code> type alias. This is a DSL extension supplied with the
library. We will detail its use below. For now see that the extension method can be used in client code to supply a
where clause and an order by clause as follows:</p>
<pre><code class="language-kotlin">val rows = mapper.select {
where { id isLessThan 100 }
or {
employed.isTrue()
and { occupation isEqualTo "Developer" }
}
orderBy(id)
}
</code></pre></section><section><a id="Count_Statements"></a>
<h2>Count Statements</h2><section><a id="Two-Step_Method"></a>
<h3>Two-Step Method</h3>
<p>Count statements are constructed as shown on the Kotlin overview page. These methods create a
<code>SelectStatementProvider</code> that can be executed with a MyBatis3 mapper method. MyBatis3 mappers should declare
a <code>count</code> method as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@SelectProvider(type = SqlProviderAdapter::class, method = "select")
fun count(selectStatement: SelectStatementProvider): Long
}
</code></pre>
<p>This is a standard method for MyBatis Dynamic SQL that executes a query and returns a <code>Long</code>. This method can also be
implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonCountMapper
</code></pre>
<p><code>CommonCountMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">val countStatement = count() // not shown... see the overview page for examples
val mapper: PersonMapper = getMapper() // not shown
val rows: Long = mapper.count(countStatement)
</code></pre></section><section><a id="One-Step_Method"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of count statements.
The extension functions will reuse the abstract method and supply everything needed to build the select statement
except the where clause:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.CountCompleter
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.count
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countDistinct
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
fun PersonMapper.count(completer: CountCompleter) = // count(*)
countFrom(this::count, person, completer)
fun PersonMapper.count(column: BasicColumn, completer: CountCompleter) = // count(column)
count(this::count, column, person, completer)
fun PersonMapper.countDistinct(column: BasicColumn, completer: CountCompleter) = // count(distinct column)
countDistinct(this::count, column, person, completer)
</code></pre>
<p>The methods are constructed to execute count queries on one specific table - <code>person</code> in this case.</p>
<p>The methods show the use of <code>CountCompleter</code> which is a Kotlin typealias for a function with a receiver that will
allow a user to supply a where clause. This also shows use of the Kotlin <code>countFrom</code>, <code>count</code>, and <code>countDistinct</code>
methods which are supplied by the library. Those methods will build and execute the select count statements with the
supplied where clause. Clients can use the methods as follows:</p>
<pre><code class="language-kotlin">val rows = mapper.count {
where { occupation.isNull() }
and { employed.isFalse() }
}
</code></pre>
<p>There is also a method that can be used to count all rows in a table:</p>
<pre><code class="language-kotlin">val rows = mapper.count { allRows() }
</code></pre></section></section><section><a id="Delete_Method_Support"></a>
<h2>Delete Method Support</h2><section><a id="Two-Step_Method_1"></a>
<h3>Two-Step Method</h3>
<p>Delete statements are constructed as shown on the Kotlin overview page. This method creates a
<code>DeleteStatementProvider</code> that can be executed with a MyBatis3 mapper method. MyBatis3 mappers should declare
a <code>delete</code> method as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@DeleteProvider(type = SqlProviderAdapter::class, method = "delete")
fun delete(deleteStatement: DeleteStatementProvider): Int
}
</code></pre>
<p>This is a standard method for MyBatis Dynamic SQL that executes a query and returns an <code>Int</code> - the number of rows
deleted. This method can also be implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonDeleteMapper
</code></pre>
<p><code>CommonDeleteMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">val deleteStatement = deleteFrom() // not shown... see the overview page for examples
val mapper: PersonMapper = getMapper() // not shown
val rows: Int = mapper.delete(deleteStatement)
</code></pre></section><section><a id="One-Step_Method_1"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of delete statements.
The extension functions will reuse the abstract method and supply everything needed to build the delete statement
except the where clause:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.DeleteCompleter
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.deleteFrom
fun PersonMapper.delete(completer: DeleteCompleter) =
deleteFrom(this::delete, person, completer)
</code></pre>
<p>The method is constructed to execute delete statements on one specific table - <code>person</code> in this case.</p>
<p>The method shows the use of <code>DeleteCompleter</code> which is a Kotlin typealias for a function with a receiver that will
allow a user to supply a where clause. This also shows use of the Kotlin <code>deleteFrom</code> method which are supplied by the
library. Those methods will build and execute the delete statement with the supplied where clause. Clients can use the
method as follows:</p>
<pre><code class="language-kotlin">val rows = mapper.delete {
where { occupation.isNull() }
}
</code></pre>
<p>There is an extension method that can be used to delete all rows in a table:</p>
<pre><code class="language-kotlin">val rows = mapper.delete { allRows() }
</code></pre></section></section><section><a id="Single_Row_Insert_Statement"></a>
<h2>Single Row Insert Statement</h2><section><a id="Two-Step_Method_2"></a>
<h3>Two-Step Method</h3>
<p>Single row insert statements are constructed as shown on the Kotlin overview page. This method creates
an <code>InsertStatementProvider</code> that can be executed with a MyBatis3 mapper method. MyBatis3 mappers should declare
an <code>insert</code> method as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "insert")
fun insert(insertStatement: InsertStatementProvider<PersonRecord>): Int
}
</code></pre>
<p>This is a standard method for MyBatis Dynamic SQL that executes an insert and returns a <code>Int</code> - the number of rows
inserted. This method can also be implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonInsertMapper<T>
</code></pre>
<p><code>CommonInsertMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">val insertStatement = insert() // not shown, see overview page
val mapper: PersonMapper = getMapper() // not shown
val rows: Int = mapper.insert(insertStatement)
</code></pre></section><section><a id="One-Step_Method_2"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of single record
insert statements. The extension functions will reuse the abstract method and supply everything needed to build the
insert statement:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insert
fun PersonMapper.insert(row: PersonRecord) =
insert(this::insert, row, Person) {
map(id) toProperty "id"
map(firstName) toProperty "firstName"
map(lastName) toProperty "lastName"
map(birthDate) toProperty "birthDate"
map(employed) toProperty "employed"
map(occupation) toProperty "occupation"
map(addressId) toProperty "addressId"
}
</code></pre>
<p>This extension method reuses the mapper method and supplies all the column mappings. Clients can use the method
as follows:</p>
<pre><code class="language-kotlin">val record = PersonRecord(100, "Joe", LastName("Jones"), Date(), true, "Developer", 1)
val mapper: PersonMapper = getMapper() // not shown
val rows = mapper.insert(record)
</code></pre></section><section><a id="Generated_Key_Support"></a>
<h3>Generated Key Support</h3>
<p>Single record insert statements support returning a generated key using normal MyBatis generated key support. When
generated keys are expected you must code the mapper method manually and supply the <code>@Options</code> annotation that
configures generated key support. You cannot use the built-in base interface when there are generated keys. For example:</p>
<pre><code class="language-kotlin">interface GeneratedAlwaysMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "insert")
@Options(useGeneratedKeys = true, keyProperty = "row.id,row.fullName", keyColumn = "id,full_name")
fun insert(insertStatement: InsertStatementProvider<GeneratedAlwaysRecord>): Int
}
</code></pre>
<p>This method will return two generated values in each row: <code>id</code> and <code>full_name</code>. The values will be placed into the
row properties <code>id</code> and <code>fullName</code> respectively.</p></section></section><section><a id="General_Insert_Statement"></a>
<h2>General Insert Statement</h2><section><a id="Two-Step_Method_3"></a>
<h3>Two-Step Method</h3>
<p>General insert statements are constructed as shown on the Kotlin overview page. This method creates
a <code>GeneralInsertStatementProvider</code> that can be executed with a MyBatis3 mapper method. MyBatis3 mappers should declare
a <code>generalInsert</code> method as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "generalInsert")
fun generalInsert(insertStatement: GeneralInsertStatementProvider): Int
}
</code></pre>
<p>This is a standard method for MyBatis Dynamic SQL that executes an insert and returns a <code>Int</code> - the number of rows
inserted. This method can also be implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonInsertMapper<T>
</code></pre>
<p><code>CommonInsertMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">val insertStatement = insertInto() // not shown, see overview page
val mapper: PersonMapper = getMapper() // not shown
val rows: Int = mapper.generalInsert(insertStatement)
</code></pre></section><section><a id="One-Step_Method_3"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of general
insert statements. The extension functions will reuse the abstract method and supply everything needed to build the
insert statement except the values to insert:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.GeneralInsertCompleter
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertInto
fun PersonMapper.generalInsert(completer: GeneralInsertCompleter) =
insertInto(this::generalInsert, person, completer)
</code></pre>
<p>The method is constructed to execute insert statements on one specific table - <code>person</code> in this case.</p>
<p>The method shows the use of <code>GeneralInsertCompleter</code> which is a Kotlin typealias for a function with a receiver that will
allow a user to supply values to insert. This also shows use of the Kotlin <code>insertInto</code> method which are supplied by the
library. Those methods will build and execute the insert statement with the supplied values. Clients can use the
method as follows:</p>
<pre><code class="language-kotlin">val rows = mapper.generalInsert {
set(id) toValue 100
set(firstName) toValue "Joe"
set(lastName) toValue LastName("Jones")
set(employed) toValue true
set(occupation) toValue "Developer"
set(addressId) toValue 1
set(birthDate) toValue Date()
}
</code></pre></section><section><a id="Generated_Key_Support_1"></a>
<h3>Generated Key Support</h3>
<p>You cen retrieve generated keys from general insert statements if you use the two-step method.
You cannot use the built-in base interface when there are generated keys. First, code the
abstract mapper method as follows:</p>
<pre><code class="language-kotlin">interface GeneratedAlwaysMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "generalInsert")
@Options(useGeneratedKeys = true, keyProperty="parameters.id,parameters.fullName", keyColumn = "id,full_name")
fun generalInsert(insertStatement: GeneralInsertStatementProvider): Int
}
</code></pre>
<p>This method will return two generated values: <code>id</code> and <code>full_name</code>. The values will be placed into the
parameter map in the <code>GeneralInsertStatementProvider</code> with keys <code>id</code> and <code>fullName</code> respectively.</p>
<p>The method can be used as follows:</p>
<pre><code class="language-kotlin">val mapper = getMapper() // not shown
val insertStatement = insertInto(generatedAlways) {
set(firstName).toValue("Fred")
set(lastName).toValue("Flintstone")
}
val rows = mapper.generalInsert(insertStatement)
</code></pre>
<p>After the statement completes, then generated keys are available in the mapper:</p>
<pre><code class="language-kotlin">val id = insertStatement.parameters["id"] as Int
val fullName = insertStatement.parameters["fullName"] as String
</code></pre></section></section><section><a id="Multi-Row_Insert_Statement"></a>
<h2>Multi-Row Insert Statement</h2><section><a id="Two-Step_Method_4"></a>
<h3>Two-Step Method</h3>
<p>Multi-row insert statements are constructed as shown on the Kotlin overview page. This method creates
a <code>MultiRowInsertStatementProvider</code> that can be executed with a MyBatis3 mapper method. MyBatis3 mappers should declare
an <code>insertMultiple</code> method as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "insertMultiple")
fun insertMultiple(insertStatement: MultiRowInsertStatementProvider<PersonRecord>): Int
}
</code></pre>
<p>This is a standard method for MyBatis Dynamic SQL that executes an insert and returns a <code>Int</code> - the number of rows
inserted. This method can also be implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonInsertMapper<T>
</code></pre>
<p><code>CommonInsertMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">val insertStatement = insertMultiple() // not shown, see overview page
val mapper: PersonMapper = getMapper() // not shown
val rows: Int = mapper.insertMultiple(insertStatement)
</code></pre></section><section><a id="One-Step_Method_4"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of multi-row
insert statements. The extension functions will reuse the abstract method and supply everything needed to build the
insert statement except the values to insert:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertMultiple
fun PersonMapper.insertMultiple(vararg records: PersonRecord) =
insertMultiple(records.toList())
fun PersonMapper.insertMultiple(records: Collection<PersonRecord>) =
insertMultiple(this::insertMultiple, records, person) {
map(id) toProperty "id"
map(firstName) toProperty "firstName"
map(lastName) toProperty "lastName"
map(birthDate) toProperty "birthDate"
map(employed) toProperty "employed"
map(occupation) toProperty "occupation"
map(addressId) toProperty "addressId"
}
</code></pre>
<p>The method is constructed to execute multi-row insert statements on one specific table - <code>person</code> in this case.</p>
<p>This extension method reuses the mapper method and supplies all the column mappings. Clients can use the method
as follows:</p>
<pre><code class="language-kotlin">val record1 = PersonRecord(100, "Joe", LastName("Jones"), Date(), true, "Developer", 1)
val record2 = PersonRecord(101, "Sarah", LastName("Smith"), Date(), true, "Architect", 2)
val rows = mapper.insertMultiple(record1, record2)
</code></pre></section><section><a id="Generated_Key_Support_2"></a>
<h3>Generated Key Support</h3>
<p>Multi-row insert statements support returning a generated key using normal MyBatis generated key support. However,
generated keys require some care for multi-row insert statements. In this section we will show how to use the
library's built-in support. When generated keys are expected you must code the mapper method manually and supply the
<code>@Options</code> annotation that configures generated key support. You cannot use the built-in base interface when there are
generated keys. For example:</p>
<pre><code class="language-kotlin">interface GeneratedAlwaysMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "insertMultipleWithGeneratedKeys")
@Options(useGeneratedKeys = true, keyProperty="records.id,records.fullName", keyColumn = "id,full_name")
fun insertMultiple(insertStatement: String, @Param("records") records: List<GeneratedAlwaysRecord>): Int
}
</code></pre>
<p>Note that this method uses a different <code>SQLProviderAdapter</code> method and also uses a decomposed version of the
provider class. This is done to code around some limitations in MyBatis3. This method will return two generated values
in each row: <code>id</code> and <code>full_name</code>. The values will be placed into the record properties <code>id</code> and <code>fullName</code> respectively.</p>
<p>For the one-step method, the mapper extension method should use a different utility function as shown below:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertMultipleWithGeneratedKeys
fun GeneratedAlwaysMapper.insertMultiple(records: Collection<GeneratedAlwaysRecord>): Int {
return insertMultipleWithGeneratedKeys(this::insertMultiple, records, generatedAlways) {
map(firstName).toProperty("firstName")
map(lastName).toProperty("lastName")
}
}
</code></pre></section></section><section><a id="Batch_Insert_Statement"></a>
<h2>Batch Insert Statement</h2><section><a id="Two-Step_Method_5"></a>
<h3>Two-Step Method</h3>
<p>Batch insert statements are constructed as shown on the Kotlin overview page. This method creates
a <code>BatchInsert</code> that can be executed with a MyBatis3 mapper method.</p>
<p>Batch inserts will reuse the regular <code>insert</code> method created for single record inserts. It is also convenient to create
a method to flush the batch statements - this causes a commit and returns detailed information about the
batch such as update counts. The methods are coded as follows:</p>
<pre><code class="language-kotlin">import org.apache.ibatis.annotations.Flush
import org.apache.ibatis.annotations.InsertProvider
import org.apache.ibatis.executor.BatchResult
@Mapper
interface PersonMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "insert")
fun insert(insertStatement: InsertStatementProvider<PersonRecord>): Int
@Flush
fun flush(): List<BatchResult>
}
</code></pre>
<p>These are standard methods for MyBatis. Note that the return value of the “insert” statement will NOT be the number of
rows when using batch mode operations. In batch mode the rows are not actually inserted until the statements
are flushed, or the session is committed. In batch mode, the return value is a constant with no actual meaning.
The methods can also be implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonInsertMapper<T>
</code></pre>
<p><code>CommonInsertMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>MyBatis batch executions are coded as multiple invocations of a simple insert method. The difference is in the
construction of the mapper. The <code>SqlSession</code> associated with the mapper must be in “batch mode”. This is accomplished
when opening the session. For example:</p>
<pre><code class="language-kotlin">import org.apache.ibatis.session.ExecutorType
import org.apache.ibatis.session.SqlSession
import org.apache.ibatis.session.SqlSessionFactory
val sqlSessionFactory: SqlSessionFactory = getSessionFactory() // not shown
val sqlSession: SqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)
val mapper: PersonMaper = sqlSession.getMapper(PersonMapper::class.java)
</code></pre>
<p>The mapper is now associated with a BATCH session. The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">import org.apache.ibatis.executor.BatchResult
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertBatch
val sqlSessionFactory: SqlSessionFactory = getSessionFactory() // not shown
val sqlSession: SqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)
val mapper: PersonMapper = sqlSession.getMapper(PersonMapper::class.java)
val batchInsert = insertBatch() // not shown, see overview page
batchInsert.execute(mapper) // see note below about return value
val batchResults = mapper.flush()
</code></pre>
<p>Note the use of the extension function <code>BatchInsert.execute(mapper)</code>. This function simply loops over all
insert statements in the batch and executes them with the supplied mapper. Note also that
<code>BatchInsert.execute(mapper)</code> will return a <code>List<Int></code>. However, when the mapper is in batch mode the
values in the list will not be useful. In batch mode you must execute the flush method (or <code>sqlSession.flushStatements()</code>)
to obtain update counts. The <code>flush</code> call will also commit the batch. Note that this built-in support executes all inserts
as a single transaction. If you have a large batch of records and want to process intermediate commits, you can do so
by writing code to loop through the list of insert statements obtained from <code>BatchInsert.insertStatements()</code> and execute
flush/commit as desired.</p></section><section><a id="One-Step_Method_5"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of batch
insert statements. The extension functions will reuse the abstract method and supply everything needed to build the
insert statement except the values to insert:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertBatch
fun PersonMapper.insertBatch(vararg records: PersonRecord): List<Int> =
insertBatch(records.toList())
fun PersonMapper.insertBatch(records: Collection<PersonRecord>): List<Int> =
insertBatch(this::insert, records, person) {
map(id) toProperty "id"
map(firstName) toProperty "firstName"
map(lastName) toProperty "lastName"
map(birthDate) toProperty "birthDate"
map(employed) toProperty "employed"
map(occupation) toProperty "occupation"
map(addressId) toProperty "addressId"
}
</code></pre>
<p>The method is constructed to execute batch insert statements on one specific table - <code>person</code> in this case.</p>
<p>This extension method reuses the mapper method and supplies all the column mappings. Clients can use the method
as follows:</p>
<pre><code class="language-kotlin">val record1 = PersonRecord(100, "Joe", LastName("Jones"), Date(), true, "Developer", 1)
val record2 = PersonRecord(101, "Sarah", LastName("Smith"), Date(), true, "Architect", 2)
val sqlSessionFactory: SqlSessionFactory = getSessionFactory() // not shown
val sqlSession: SqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)
val mapper: PersonMapper = sqlSession.getMapper(PersonMapper::class.java)
mapper.insertBatch(record1, record2)
val batchResults = mapper.flush()
</code></pre></section><section><a id="Generated_Key_Support_3"></a>
<h3>Generated Key Support</h3>
<p>Batch insert statements support returning a generated key using normal MyBatis generated key support. If you code
the <code>@Options</code> annotation on the <code>insert</code> statement, then the generated keys will be populated into the input records
when the transaction is committed or flushed. When generated keys are expected you must code the mapper method manually
and supply the <code>@Options</code> annotation that configures generated key support. You cannot use the built-in base interface
when there are generated keys. For example:</p>
<pre><code class="language-kotlin">interface GeneratedAlwaysMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "insert")
@Options(useGeneratedKeys = true, keyProperty="record.id,record.fullName", keyColumn = "id,full_name")
fun insert(insertStatement: InsertStatementProvider<GeneratedAlwaysRecord>): Int
}
</code></pre>
<p>This insert method can be used with mappers in batch mode as shown above.</p></section></section><section><a id="Insert_Select_Statement"></a>
<h2>Insert Select Statement</h2><section><a id="Two-Step_Method_6"></a>
<h3>Two-Step Method</h3>
<p>Insert select statements are constructed as shown on the Kotlin overview page. This method creates
an <code>InsertSelectStatementProvider</code> that can be executed with a MyBatis3 mapper method. MyBatis3 mappers should declare
a <code>generalInsert</code> method as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@InsertProvider(type = SqlProviderAdapter::class, method = "insertSelect")
fun insertSelect(insertSelectStatement: InsertSelectStatementProvider): Int
}
</code></pre>
<p>This is a standard method for MyBatis Dynamic SQL that executes an insert and returns a <code>Int</code> - the number of rows
inserted. This method can also be implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonInsertMapper<T>
</code></pre>
<p><code>CommonInsertMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">val insertStatement = insertSelect() // not shown, see overview page
val mapper: PersonMapper = getMapper() // not shown
val rows: Int = mapper.insertSelect(insertStatement)
</code></pre></section><section><a id="One-Step_Method_6"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of insert select
statements. The extension functions will reuse the abstract method and supply everything needed to build the
insert statement except the values to insert:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.InsertSelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertSelect
fun PersonMapper.insertSelect(completer: InsertSelectCompleter) =
insertSelect(this::insertSelect, person, completer)
</code></pre>
<p>The method is constructed to execute insert statements on one specific table - <code>person</code> in this case.</p>
<p>The method shows the use of <code>InsertSelectCompleter</code> which is a Kotlin typealias for a function with a receiver that will
allow a user to supply value column list ans select statement. This also shows use of the Kotlin <code>insertSelect</code> method
which is supplied by the library. This method will build and execute the insert statement with the supplied column
list and select statement. Clients can use the method as follows:</p>
<pre><code class="language-kotlin">val mapper = getMapper() // not shown
val rows = mapper.insertSelect {
columns(id, firstName, lastName, employed, occupation, addressId, birthDate)
select(add(id, constant<Int>("100")), firstName, lastName, employed, occupation, addressId, birthDate) {
from(person)
orderBy(id)
}
}
</code></pre></section><section><a id="Generated_Key_Support_4"></a>
<h3>Generated Key Support</h3>
<p>Generated keys with insert select are not directly supported by library utilities and can be quite challenging.
There are examples in the source repository if you have a need to do this.</p></section></section><section><a id="Select_Method_Support"></a>
<h2>Select Method Support</h2><section><a id="Two-Step_Method_7"></a>
<h3>Two-Step Method</h3>
<p>Select statements are constructed as shown on the Kotlin overview page. Those methods create a
<code>SelectStatementProvider</code> that can be executed with MyBatis3 mapper methods. We recommend creating two mapper methods:
one that returns a list of records, and another that returns a single record or null:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@SelectProvider(type = SqlProviderAdapter::class, method = "select")
@Results(id = "PersonResult", value = [
Result(column = "A_ID", property = "id", jdbcType = JdbcType.INTEGER, id = true),
Result(column = "first_name", property = "firstName", jdbcType = JdbcType.VARCHAR),
Result(column = "last_name", property = "lastName", jdbcType = JdbcType.VARCHAR,
typeHandler = LastNameTypeHandler::class),
Result(column = "birth_date", property = "birthDate", jdbcType = JdbcType.DATE),
Result(column = "employed", property = "employed", jdbcType = JdbcType.VARCHAR,
typeHandler = YesNoTypeHandler::class),
Result(column = "occupation", property = "occupation", jdbcType = JdbcType.VARCHAR),
Result(column = "address_id", property = "addressId", jdbcType = JdbcType.INTEGER)])
fun selectMany(selectStatement: SelectStatementProvider): List<PersonRecord>
@SelectProvider(type = SqlProviderAdapter::class, method = "select")
@ResultMap("PersonResult")
fun selectOne(selectStatement: SelectStatementProvider): PersonRecord?
}
</code></pre>
<p>Note that the result map is shared between the two methods.</p>
<p>The methods can be used as follows:</p>
<pre><code class="language-kotlin">val mapper: PersonMapper = getMapper() // not shown
val selectStatement = select() // not shown... see the overview page for examples
val rows: List<PersonRecord> = mapper.selectMany(selectStatement)
val selectOneStatement = select() // not shown... see the overview page for examples
val row: PersonRecord? = mapper.selectOne(selectStatement)
</code></pre>
<p>Note that the select statement is the same whether multiple or single rows are expected. Also note that a select
distinct can be executed with the <code>selectMany</code> method.</p></section><section><a id="One-Step_Method_7"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of select statements.
The extension functions will reuse the abstract methods and supply the table and column list for the statement.
We recommend three extension methods for select multiple records, select multiple records with the distinct keyword,
and selecting a single record:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.elements.`as`
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectDistinct
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectList
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectOne
private val columnList = listOf(id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId)
fun PersonMapper.selectOne(completer: SelectCompleter) =
selectOne(this::selectOne, columnList, Person, completer)
fun PersonMapper.select(completer: SelectCompleter) =
selectList(this::selectMany, columnList, Person, completer)
fun PersonMapper.selectDistinct(completer: SelectCompleter) =
selectDistinct(this::selectMany, columnList, Person, completer)
</code></pre>
<p>The methods are constructed to execute select statements on one specific table - <code>person</code> in this case - and with a fixed
column list that matches the MyBatis result mapping.</p>
<p>The methods show the use of <code>SelectCompleter</code> which is a Kotlin typealias for a function with a receiver that will
allow a user to supply a where clause. This also shows use of the Kotlin <code>selectDistinct</code>, <code>selectList</code>, and <code>selectOne</code>
methods which are supplied by the library. Those methods will build and execute the select statement. Clients can use
the methods as follows:</p>
<pre><code class="language-kotlin">val mapper = getMapper() // not shown
val distinctRecords = mapper.selectDistinct {
where { id isGreaterThan 5 }
}
val rows = mapper.select {
where { firstName.isIn("Fred", "Barney") }
orderBy(id)
limit(3)
}
val record = mapper.selectOne {
where { id isEqualTo 1 }
}
</code></pre>
<p>The general <code>selectOne</code> method can also be used to implement a <code>selectByPrimaryKey</code> method:</p>
<pre><code class="language-kotlin">fun PersonMapper.selectByPrimaryKey(id_: Int) =
selectOne {
where { id isEqualTo id_ }
}
</code></pre>
<p>There is a utility method that will select all rows in a table:</p>
<pre><code class="language-kotlin">val rows = mapper.select { allRows() }
</code></pre>
<p>The following query will select all rows in a specified order:</p>
<pre><code class="language-kotlin">val rows = mapper.select {
allRows()
orderBy(lastName, firstName)
}
</code></pre></section><section><a id="Join_Support"></a>
<h3>Join Support</h3>
<p>You can implement functions that support a reusable select method based on a join. In this way, you can create
the start of the select statement (the column list and join specifications) and allow the user to supply where clauses
and other parts of a select statement. For example, you could code a mapper extension method like this:</p>
<pre><code class="language-kotlin">fun PersonWithAddressMapper.select(completer: SelectCompleter): List<PersonWithAddress> =
select(
id `as` "A_ID", firstName, lastName, birthDate,
employed, occupation, address.id, address.streetAddress, address.city, address.state
) {
from(person, "p")
fullJoin(address) {
on(person.addressId) equalTo address.id
}
completer()
}.run(this::selectMany)
</code></pre>
<p>This method creates the start of a select statement with a join, and accepts user input to complete the statement.
This shows reuse of a regular MyBatis mapper method - <code>selectMany</code> as shown above - with a result map that matches the
select list. Like other select methods, this method can be used as follows:</p>
<pre><code class="language-kotlin">val records = mapper.select {
where { id isLessThan 100 }
limit(5)
}
</code></pre></section></section><section><a id="Multi-Select_Statement_Support"></a>
<h2>Multi-Select Statement Support</h2>
<p>Multi-select statements are a special case of select statement. All the above information about MyBatis mappers applies
equally to multi-select statements.</p>
<p>The library does not provide a “one-step” shortcut for multi-select queries. You can execute a multi-select query
with the two-step method using either a “selectMany” or “selectOne” mapper method as shown above.</p></section><section><a id="Update_Method_Support"></a>
<h2>Update Method Support</h2><section><a id="Two-Step_Method_8"></a>
<h3>Two-Step Method</h3>
<p>Update statements are constructed as shown on the Kotlin overview page. This method creates an
<code>UpdateStatementProvider</code> that can be executed with a MyBatis3 mapper method. MyBatis3 mappers should declare
an <code>update</code> method as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper {
@UpdateProvider(type = SqlProviderAdapter::class, method = "update")
fun update(updateStatement: UpdateStatementProvider): Int
}
</code></pre>
<p>This is a standard method for MyBatis Dynamic SQL that executes an update and returns an <code>Int</code> - the number of rows
updated. This method can also be implemented by using a built-in base interface as follows:</p>
<pre><code class="language-kotlin">@Mapper
interface PersonMapper : CommonUpdateMapper
</code></pre>
<p><code>CommonUpdateMapper</code> can also be used on its own if you inject it into a MyBatis configuration.</p>
<p>The mapper method can be used as follows:</p>
<pre><code class="language-kotlin">val updateStatement = update() // not shown... see the overview page for examples
val mapper: PersonMapper = getMapper() // not shown
val rows: Int = mapper.update(updateStatement)
</code></pre></section><section><a id="One-Step_Method_8"></a>
<h3>One-Step Method</h3>
<p>You can use built-in utility functions to create mapper extension functions that simplify execution of update statements.
The extension functions will reuse the abstract method and supply everything needed to build the update statement
except the set and where clauses:</p>
<pre><code class="language-kotlin">import org.mybatis.dynamic.sql.util.kotlin.UpdateCompleter
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.update
fun PersonMapper.update(completer: UpdateCompleter) =
update(this::update, person, completer)
</code></pre>
<p>The method is constructed to execute update statements on one specific table - <code>person</code> in this case.</p>
<p>The method shows the use of <code>UpdateCompleter</code> which is a Kotlin typealias for a function with a receiver that will
allow a user to supply set phrases and a where clause. This also shows use of the Kotlin <code>update</code> method which is
supplied by the library. Those methods will build and execute the update statement with the supplied set phrases and
where clause. Clients can use the method as follows:</p>
<pre><code class="language-kotlin">val rows = mapper.update {
set(occupation).equalTo("Programmer")
where { id isEqualTo 100 }
and(firstName, isEqualTo("Joe"))
}
</code></pre>
<p>If you wish to update all rows in a table, you can simply omit the where clause as follows:</p>
<pre><code class="language-kotlin">// update all rows...
val rows = mapper.update {
set(occupation) equalTo "Programmer"
}
</code></pre>
<p>It is also possible to write utility methods that will set values. For example:</p>
<pre><code class="language-kotlin">fun KotlinUpdateBuilder.updateSelectiveColumns(record: PersonRecord) =
apply {
set(id) equalToWhenPresent record::id
set(firstName) equalToWhenPresent record::firstName
set(lastName) equalToWhenPresent record::lastName
set(birthDate) equalToWhenPresent record::birthDate
set(employed) equalToWhenPresent record::employed
set(occupation) equalToWhenPresent record::occupation
set(addressId) equalToWhenPresent record::addressId
}
</code></pre>
<p>This method will selectively set values if corresponding fields in a record are non-null. This method can be used as
follows:</p>
<pre><code class="language-kotlin">val rows = mapper.update {
updateSelectiveColumns(updateRecord)
where { id isEqualTo 100 }
}
</code></pre>
<p>If you wish to implement an “update by primary key” method, you can reuse the extension method as follows:</p>
<pre><code class="language-kotlin">fun PersonMapper.updateByPrimaryKey(record: PersonRecord) =
update {
set(firstName) equalToOrNull record::firstName
set(lastName) equalToOrNull record::lastName
set(birthDate) equalToOrNull record::birthDate
set(employed) equalToOrNull record::employed
set(occupation) equalToOrNull record::occupation
set(addressId) equalToOrNull record::addressId
where { id isEqualTo record.id!! }
}
fun PersonMapper.updateByPrimaryKeySelective(record: PersonRecord) =
update {
set(firstName) equalToWhenPresent record::firstName
set(lastName) equalToWhenPresent record::lastName
set(birthDate) equalToWhenPresent record::birthDate
set(employed) equalToWhenPresent record::employed
set(occupation) equalToWhenPresent record::occupation
set(addressId) equalToWhenPresent record::addressId
where { id isEqualTo record.id!! }
}
</code></pre>
<p>The method <code>updateByPrimaryKey</code> will update every column - if a property in the record is null, the column will be set
to null.</p>
<p>The method <code>updateByPrimaryKeySelective</code> will update every column that has a non-null corresponding property
in the record. If a property in the record is null, the column will not be updated.</p></section></section></section>
</main>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<p>© 2016–2024
<a href="https://www.mybatis.org/">MyBatis.org</a>
</p>
</div>
</div>
</footer>
<script>
if(anchors) {
anchors.add();
}
</script>
</body>
</html>