0
# Row-Based Database Operations
1
2
Direct database operations without entity classes using the Row and Db utilities. Ideal for dynamic queries, reporting, data migration, and working with unknown table structures where entity mapping is not feasible or desired.
3
4
## Capabilities
5
6
### Db Utility Class
7
8
Static utility class providing direct database operations without requiring entity classes or mapper interfaces. Supports schema-aware operations, multi-datasource environments, batch processing, and comprehensive CRUD operations.
9
10
```java { .api }
11
/**
12
* Static utility class for entity-free database operations
13
* Provides comprehensive database access with Row objects
14
*/
15
public class Db {
16
// Environment and invoker management
17
public static RowMapperInvoker invoker();
18
public static RowMapperInvoker invoker(String environmentId);
19
20
// INSERT OPERATIONS
21
22
/**
23
* Insert row into table
24
* @param tableName table name
25
* @param row row data
26
* @return number of affected rows
27
*/
28
public static int insert(String tableName, Row row);
29
30
/**
31
* Insert row into schema.table
32
* @param schema database schema name
33
* @param tableName table name
34
* @param row row data
35
* @return number of affected rows
36
*/
37
public static int insert(String schema, String tableName, Row row);
38
39
/**
40
* Execute raw SQL insert
41
* @param sql SQL insert statement
42
* @param args SQL parameters
43
* @return number of affected rows
44
*/
45
public static int insertBySql(String sql, Object... args);
46
47
/**
48
* Batch insert rows
49
* @param tableName table name
50
* @param rows collection of rows
51
* @return array of update counts
52
*/
53
public static int[] insertBatch(String tableName, Collection<Row> rows);
54
55
/**
56
* Batch insert rows into schema.table
57
* @param schema database schema name
58
* @param tableName table name
59
* @param rows collection of rows
60
* @return array of update counts
61
*/
62
public static int[] insertBatch(String schema, String tableName, Collection<Row> rows);
63
64
/**
65
* Batch insert rows with batch size control
66
* @param tableName table name
67
* @param rows collection of rows
68
* @param batchSize number of rows per batch
69
* @return array of update counts
70
*/
71
public static int[] insertBatch(String tableName, Collection<Row> rows, int batchSize);
72
73
/**
74
* Batch insert rows into schema.table with batch size control
75
* @param schema database schema name
76
* @param tableName table name
77
* @param rows collection of rows
78
* @param batchSize number of rows per batch
79
* @return array of update counts
80
*/
81
public static int[] insertBatch(String schema, String tableName, Collection<Row> rows, int batchSize);
82
83
/**
84
* High-performance batch insert using first row's columns
85
* @param tableName table name
86
* @param rows list of rows
87
* @return number of affected rows
88
*/
89
public static int insertBatchWithFirstRowColumns(String tableName, List<Row> rows);
90
91
/**
92
* High-performance batch insert using first row's columns into schema.table
93
* @param schema database schema name
94
* @param tableName table name
95
* @param rows list of rows
96
* @return number of affected rows
97
*/
98
public static int insertBatchWithFirstRowColumns(String schema, String tableName, List<Row> rows);
99
100
// DELETE OPERATIONS
101
102
/**
103
* Execute raw SQL delete
104
* @param sql SQL delete statement
105
* @param args SQL parameters
106
* @return number of affected rows
107
*/
108
public static int deleteBySql(String sql, Object... args);
109
110
/**
111
* Delete by primary key
112
* @param tableName table name
113
* @param row row with primary key values
114
* @return number of affected rows
115
*/
116
public static int deleteById(String tableName, Row row);
117
118
/**
119
* Delete by primary key from schema.table
120
* @param schema database schema name
121
* @param tableName table name
122
* @param row row with primary key values
123
* @return number of affected rows
124
*/
125
public static int deleteById(String schema, String tableName, Row row);
126
127
/**
128
* Delete by single primary key
129
* @param tableName table name
130
* @param primaryKey primary key column name
131
* @param id primary key value
132
* @return number of affected rows
133
*/
134
public static int deleteById(String tableName, String primaryKey, Object id);
135
136
/**
137
* Delete by single primary key from schema.table
138
* @param schema database schema name
139
* @param tableName table name
140
* @param primaryKey primary key column name
141
* @param id primary key value
142
* @return number of affected rows
143
*/
144
public static int deleteById(String schema, String tableName, String primaryKey, Object id);
145
146
/**
147
* Batch delete by primary key values
148
* @param tableName table name
149
* @param primaryKey primary key column name
150
* @param ids collection of primary key values
151
* @return number of affected rows
152
*/
153
public static int deleteBatchByIds(String tableName, String primaryKey, Collection<?> ids);
154
155
/**
156
* Batch delete by primary key values from schema.table
157
* @param schema database schema name
158
* @param tableName table name
159
* @param primaryKey primary key column name
160
* @param ids collection of primary key values
161
* @return number of affected rows
162
*/
163
public static int deleteBatchByIds(String schema, String tableName, String primaryKey, Collection<?> ids);
164
165
/**
166
* Delete by Map-based WHERE conditions
167
* @param tableName table name
168
* @param whereColumns map of column-value pairs for WHERE clause
169
* @return number of affected rows
170
*/
171
public static int deleteByMap(String tableName, Map<String, Object> whereColumns);
172
173
/**
174
* Delete by Map-based WHERE conditions from schema.table
175
* @param schema database schema name
176
* @param tableName table name
177
* @param whereColumns map of column-value pairs for WHERE clause
178
* @return number of affected rows
179
*/
180
public static int deleteByMap(String schema, String tableName, Map<String, Object> whereColumns);
181
182
/**
183
* Delete by QueryCondition
184
* @param tableName table name
185
* @param condition query condition
186
* @return number of affected rows
187
*/
188
public static int deleteByCondition(String tableName, QueryCondition condition);
189
190
/**
191
* Delete by QueryCondition from schema.table
192
* @param schema database schema name
193
* @param tableName table name
194
* @param condition query condition
195
* @return number of affected rows
196
*/
197
public static int deleteByCondition(String schema, String tableName, QueryCondition condition);
198
199
/**
200
* Delete by QueryWrapper
201
* @param tableName table name
202
* @param queryWrapper query wrapper with conditions
203
* @return number of affected rows
204
*/
205
public static int deleteByQuery(String tableName, QueryWrapper queryWrapper);
206
207
/**
208
* Delete by QueryWrapper from schema.table
209
* @param schema database schema name
210
* @param tableName table name
211
* @param queryWrapper query wrapper with conditions
212
* @return number of affected rows
213
*/
214
public static int deleteByQuery(String schema, String tableName, QueryWrapper queryWrapper);
215
216
// UPDATE OPERATIONS
217
218
/**
219
* Execute raw SQL update
220
* @param sql SQL update statement
221
* @param args SQL parameters
222
* @return number of affected rows
223
*/
224
public static int updateBySql(String sql, Object... args);
225
226
/**
227
* Batch update using SQL with parameter setter
228
* @param sql SQL update statement
229
* @param batchArgsSetter batch arguments setter
230
* @return array of update counts
231
*/
232
public static int[] updateBatch(String sql, BatchArgsSetter batchArgsSetter);
233
234
/**
235
* Update by primary key
236
* @param tableName table name
237
* @param row row with primary key and update data
238
* @return number of affected rows
239
*/
240
public static int updateById(String tableName, Row row);
241
242
/**
243
* Update by primary key in schema.table
244
* @param schema database schema name
245
* @param tableName table name
246
* @param row row with primary key and update data
247
* @return number of affected rows
248
*/
249
public static int updateById(String schema, String tableName, Row row);
250
251
/**
252
* Update by Map-based WHERE conditions
253
* @param tableName table name
254
* @param data row with update data
255
* @param whereColumns map of column-value pairs for WHERE clause
256
* @return number of affected rows
257
*/
258
public static int updateByMap(String tableName, Row data, Map<String, Object> whereColumns);
259
260
/**
261
* Update by Map-based WHERE conditions in schema.table
262
* @param schema database schema name
263
* @param tableName table name
264
* @param data row with update data
265
* @param whereColumns map of column-value pairs for WHERE clause
266
* @return number of affected rows
267
*/
268
public static int updateByMap(String schema, String tableName, Row data, Map<String, Object> whereColumns);
269
270
/**
271
* Update by QueryCondition
272
* @param tableName table name
273
* @param data row with update data
274
* @param condition query condition
275
* @return number of affected rows
276
*/
277
public static int updateByCondition(String tableName, Row data, QueryCondition condition);
278
279
/**
280
* Update by QueryCondition in schema.table
281
* @param schema database schema name
282
* @param tableName table name
283
* @param data row with update data
284
* @param condition query condition
285
* @return number of affected rows
286
*/
287
public static int updateByCondition(String schema, String tableName, Row data, QueryCondition condition);
288
289
/**
290
* Update by QueryWrapper
291
* @param tableName table name
292
* @param data row with update data
293
* @param queryWrapper query wrapper with conditions
294
* @return number of affected rows
295
*/
296
public static int updateByQuery(String tableName, Row data, QueryWrapper queryWrapper);
297
298
/**
299
* Update by QueryWrapper in schema.table
300
* @param schema database schema name
301
* @param tableName table name
302
* @param data row with update data
303
* @param queryWrapper query wrapper with conditions
304
* @return number of affected rows
305
*/
306
public static int updateByQuery(String schema, String tableName, Row data, QueryWrapper queryWrapper);
307
308
/**
309
* Batch update by primary keys
310
* @param tableName table name
311
* @param rows list of rows with primary keys and update data
312
* @return number of affected rows
313
*/
314
public static int updateBatchById(String tableName, List<Row> rows);
315
316
/**
317
* Batch update by primary keys in schema.table
318
* @param schema database schema name
319
* @param tableName table name
320
* @param rows list of rows with primary keys and update data
321
* @return number of affected rows
322
*/
323
public static int updateBatchById(String schema, String tableName, List<Row> rows);
324
325
/**
326
* Batch update entities with batch size control
327
* @param entities collection of entities
328
* @param batchSize batch size
329
* @return number of affected rows
330
*/
331
public static <T> int updateEntitiesBatch(Collection<T> entities, int batchSize);
332
333
/**
334
* Batch update entities with default batch size
335
* @param entities collection of entities
336
* @return number of affected rows
337
*/
338
public static <T> int updateEntitiesBatch(Collection<T> entities);
339
340
// SELECT OPERATIONS
341
342
/**
343
* Execute raw SQL select query
344
* @param sql SQL query string
345
* @param args query parameters
346
* @return single Row object or null
347
*/
348
public static Row selectOneBySql(String sql, Object... args);
349
350
/**
351
* Select one row by primary key
352
* @param tableName table name
353
* @param row row with primary key values
354
* @return single Row object or null
355
*/
356
public static Row selectOneById(String tableName, Row row);
357
358
/**
359
* Select one row by primary key from schema.table
360
* @param schema database schema name
361
* @param tableName table name
362
* @param row row with primary key values
363
* @return single Row object or null
364
*/
365
public static Row selectOneById(String schema, String tableName, Row row);
366
367
/**
368
* Select one row by single primary key
369
* @param tableName table name
370
* @param primaryKey primary key column name
371
* @param id primary key value
372
* @return single Row object or null
373
*/
374
public static Row selectOneById(String tableName, String primaryKey, Object id);
375
376
/**
377
* Select one row by single primary key from schema.table
378
* @param schema database schema name
379
* @param tableName table name
380
* @param primaryKey primary key column name
381
* @param id primary key value
382
* @return single Row object or null
383
*/
384
public static Row selectOneById(String schema, String tableName, String primaryKey, Object id);
385
386
/**
387
* Select one row by Map-based conditions
388
* @param tableName table name
389
* @param whereColumns map of column-value pairs for WHERE clause
390
* @return single Row object or null
391
*/
392
public static Row selectOneByMap(String tableName, Map whereColumns);
393
394
/**
395
* Select one row by Map-based conditions from schema.table
396
* @param schema database schema name
397
* @param tableName table name
398
* @param whereColumns map of column-value pairs for WHERE clause
399
* @return single Row object or null
400
*/
401
public static Row selectOneByMap(String schema, String tableName, Map whereColumns);
402
403
/**
404
* Select one row by QueryCondition
405
* @param tableName table name
406
* @param condition query condition
407
* @return single Row object or null
408
*/
409
public static Row selectOneByCondition(String tableName, QueryCondition condition);
410
411
/**
412
* Select one row by QueryCondition from schema.table
413
* @param schema database schema name
414
* @param tableName table name
415
* @param condition query condition
416
* @return single Row object or null
417
*/
418
public static Row selectOneByCondition(String schema, String tableName, QueryCondition condition);
419
420
/**
421
* Select one row by QueryWrapper
422
* @param tableName table name
423
* @param queryWrapper query wrapper with conditions
424
* @return single Row object or null
425
*/
426
public static Row selectOneByQuery(String tableName, QueryWrapper queryWrapper);
427
428
/**
429
* Select one row by QueryWrapper from schema.table
430
* @param schema database schema name
431
* @param tableName table name
432
* @param queryWrapper query wrapper with conditions
433
* @return single Row object or null
434
*/
435
public static Row selectOneByQuery(String schema, String tableName, QueryWrapper queryWrapper);
436
437
/**
438
* Select one row by QueryWrapper with table included
439
* @param queryWrapper query wrapper with FROM clause
440
* @return single Row object or null
441
*/
442
public static Row selectOneByQuery(QueryWrapper queryWrapper);
443
444
/**
445
* Execute raw SQL select query returning multiple rows
446
* @param sql SQL query string
447
* @param args query parameters
448
* @return list of Row objects
449
*/
450
public static List<Row> selectListBySql(String sql, Object... args);
451
452
/**
453
* Select rows by Map-based conditions
454
* @param tableName table name
455
* @param whereColumns map of column-value pairs for WHERE clause
456
* @return list of Row objects
457
*/
458
public static List<Row> selectListByMap(String tableName, Map<String, Object> whereColumns);
459
460
/**
461
* Select rows by Map-based conditions from schema.table
462
* @param schema database schema name
463
* @param tableName table name
464
* @param whereColumns map of column-value pairs for WHERE clause
465
* @return list of Row objects
466
*/
467
public static List<Row> selectListByMap(String schema, String tableName, Map<String, Object> whereColumns);
468
469
/**
470
* Select rows by Map-based conditions with limit
471
* @param tableName table name
472
* @param whereColumns map of column-value pairs for WHERE clause
473
* @param count maximum number of rows to return
474
* @return list of Row objects
475
*/
476
public static List<Row> selectListByMap(String tableName, Map<String, Object> whereColumns, Long count);
477
478
/**
479
* Select rows by Map-based conditions with limit from schema.table
480
* @param schema database schema name
481
* @param tableName table name
482
* @param whereColumns map of column-value pairs for WHERE clause
483
* @param count maximum number of rows to return
484
* @return list of Row objects
485
*/
486
public static List<Row> selectListByMap(String schema, String tableName, Map<String, Object> whereColumns, Long count);
487
488
/**
489
* Select rows by QueryCondition
490
* @param tableName table name
491
* @param condition query condition
492
* @return list of Row objects
493
*/
494
public static List<Row> selectListByCondition(String tableName, QueryCondition condition);
495
496
/**
497
* Select rows by QueryCondition from schema.table
498
* @param schema database schema name
499
* @param tableName table name
500
* @param condition query condition
501
* @return list of Row objects
502
*/
503
public static List<Row> selectListByCondition(String schema, String tableName, QueryCondition condition);
504
505
/**
506
* Select rows by QueryCondition with limit
507
* @param tableName table name
508
* @param condition query condition
509
* @param count maximum number of rows to return
510
* @return list of Row objects
511
*/
512
public static List<Row> selectListByCondition(String tableName, QueryCondition condition, Long count);
513
514
/**
515
* Select rows by QueryCondition with limit from schema.table
516
* @param schema database schema name
517
* @param tableName table name
518
* @param condition query condition
519
* @param count maximum number of rows to return
520
* @return list of Row objects
521
*/
522
public static List<Row> selectListByCondition(String schema, String tableName, QueryCondition condition, Long count);
523
524
/**
525
* Select rows by QueryWrapper
526
* @param tableName table name
527
* @param queryWrapper query wrapper with conditions
528
* @return list of Row objects
529
*/
530
public static List<Row> selectListByQuery(String tableName, QueryWrapper queryWrapper);
531
532
/**
533
* Select rows by QueryWrapper from schema.table
534
* @param schema database schema name
535
* @param tableName table name
536
* @param queryWrapper query wrapper with conditions
537
* @return list of Row objects
538
*/
539
public static List<Row> selectListByQuery(String schema, String tableName, QueryWrapper queryWrapper);
540
541
/**
542
* Select rows by QueryWrapper with table included
543
* @param queryWrapper query wrapper with FROM clause
544
* @return list of Row objects
545
*/
546
public static List<Row> selectListByQuery(QueryWrapper queryWrapper);
547
548
/**
549
* Select all rows from table
550
* @param tableName table name
551
* @return list of all rows
552
*/
553
public static List<Row> selectAll(String tableName);
554
555
/**
556
* Select all rows from schema.table
557
* @param schema database schema name
558
* @param tableName table name
559
* @return list of all rows
560
*/
561
public static List<Row> selectAll(String schema, String tableName);
562
563
// OBJECT SELECTION OPERATIONS
564
565
/**
566
* Select single object value from SQL query (1 row, 1 column)
567
* @param sql SQL query string
568
* @param args query parameters
569
* @return single object value
570
*/
571
public static Object selectObject(String sql, Object... args);
572
573
/**
574
* Select single object value by QueryWrapper from table
575
* @param tableName table name
576
* @param queryWrapper query wrapper
577
* @return single object value
578
*/
579
public static Object selectObject(String tableName, QueryWrapper queryWrapper);
580
581
/**
582
* Select single object value by QueryWrapper from schema.table
583
* @param schema database schema name
584
* @param tableName table name
585
* @param queryWrapper query wrapper
586
* @return single object value
587
*/
588
public static Object selectObject(String schema, String tableName, QueryWrapper queryWrapper);
589
590
/**
591
* Select single object value by QueryWrapper with table included
592
* @param queryWrapper query wrapper with FROM clause
593
* @return single object value
594
*/
595
public static Object selectObject(QueryWrapper queryWrapper);
596
597
/**
598
* Select first and second columns as Map (key-value pairs)
599
* @param sql SQL query string
600
* @param args query parameters
601
* @return Map with first column as keys, second column as values
602
*/
603
public static Map selectFirstAndSecondColumnsAsMap(String sql, Object... args);
604
605
/**
606
* Select first and second columns as Map by QueryWrapper from table
607
* @param tableName table name
608
* @param queryWrapper query wrapper
609
* @return Map with first column as keys, second column as values
610
*/
611
public static Map selectFirstAndSecondColumnsAsMap(String tableName, QueryWrapper queryWrapper);
612
613
/**
614
* Select first and second columns as Map by QueryWrapper from schema.table
615
* @param schema database schema name
616
* @param tableName table name
617
* @param queryWrapper query wrapper
618
* @return Map with first column as keys, second column as values
619
*/
620
public static Map selectFirstAndSecondColumnsAsMap(String schema, String tableName, QueryWrapper queryWrapper);
621
622
/**
623
* Select first and second columns as Map by QueryWrapper with table included
624
* @param queryWrapper query wrapper with FROM clause
625
* @return Map with first column as keys, second column as values
626
*/
627
public static Map selectFirstAndSecondColumnsAsMap(QueryWrapper queryWrapper);
628
629
/**
630
* Select multiple object values from SQL query (multiple rows, 1 column)
631
* @param sql SQL query string
632
* @param args query parameters
633
* @return list of object values
634
*/
635
public static List<Object> selectObjectList(String sql, Object... args);
636
637
/**
638
* Select multiple object values by QueryWrapper from table
639
* @param tableName table name
640
* @param queryWrapper query wrapper
641
* @return list of object values
642
*/
643
public static List<Object> selectObjectList(String tableName, QueryWrapper queryWrapper);
644
645
/**
646
* Select multiple object values by QueryWrapper from schema.table
647
* @param schema database schema name
648
* @param tableName table name
649
* @param queryWrapper query wrapper
650
* @return list of object values
651
*/
652
public static List<Object> selectObjectList(String schema, String tableName, QueryWrapper queryWrapper);
653
654
/**
655
* Select multiple object values by QueryWrapper with table included
656
* @param queryWrapper query wrapper with FROM clause
657
* @return list of object values
658
*/
659
public static List<Object> selectObjectList(QueryWrapper queryWrapper);
660
661
// COUNT OPERATIONS
662
663
/**
664
* Execute count query using SQL
665
* @param sql SQL count query
666
* @param args query parameters
667
* @return count value
668
*/
669
public static long selectCount(String sql, Object... args);
670
671
/**
672
* Count rows by QueryCondition
673
* @param tableName table name
674
* @param condition query condition
675
* @return count value
676
*/
677
public static long selectCountByCondition(String tableName, QueryCondition condition);
678
679
/**
680
* Count rows by QueryCondition from schema.table
681
* @param schema database schema name
682
* @param tableName table name
683
* @param condition query condition
684
* @return count value
685
*/
686
public static long selectCountByCondition(String schema, String tableName, QueryCondition condition);
687
688
/**
689
* Count rows by QueryWrapper
690
* @param tableName table name
691
* @param queryWrapper query wrapper with conditions
692
* @return count value
693
*/
694
public static long selectCountByQuery(String tableName, QueryWrapper queryWrapper);
695
696
/**
697
* Count rows by QueryWrapper from schema.table
698
* @param schema database schema name
699
* @param tableName table name
700
* @param queryWrapper query wrapper with conditions
701
* @return count value
702
*/
703
public static long selectCountByQuery(String schema, String tableName, QueryWrapper queryWrapper);
704
705
/**
706
* Count rows by QueryWrapper with table included
707
* @param queryWrapper query wrapper with FROM clause
708
* @return count value
709
*/
710
public static long selectCountByQuery(QueryWrapper queryWrapper);
711
712
// PAGINATION OPERATIONS
713
714
/**
715
* Paginate results by QueryCondition
716
* @param tableName table name
717
* @param pageNumber current page number (1-based)
718
* @param pageSize number of rows per page
719
* @param condition query condition
720
* @return Page object with results
721
*/
722
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, QueryCondition condition);
723
724
/**
725
* Paginate results by QueryCondition from schema.table
726
* @param schema database schema name
727
* @param tableName table name
728
* @param pageNumber current page number (1-based)
729
* @param pageSize number of rows per page
730
* @param condition query condition
731
* @return Page object with results
732
*/
733
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, QueryCondition condition);
734
735
/**
736
* Paginate results by QueryCondition with total count provided
737
* @param tableName table name
738
* @param pageNumber current page number (1-based)
739
* @param pageSize number of rows per page
740
* @param totalRow total number of rows (skips count query if provided)
741
* @param condition query condition
742
* @return Page object with results
743
*/
744
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryCondition condition);
745
746
/**
747
* Paginate results by QueryCondition with total count provided from schema.table
748
* @param schema database schema name
749
* @param tableName table name
750
* @param pageNumber current page number (1-based)
751
* @param pageSize number of rows per page
752
* @param totalRow total number of rows (skips count query if provided)
753
* @param condition query condition
754
* @return Page object with results
755
*/
756
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryCondition condition);
757
758
/**
759
* Paginate results by QueryWrapper
760
* @param tableName table name
761
* @param pageNumber current page number (1-based)
762
* @param pageSize number of rows per page
763
* @param queryWrapper query wrapper with conditions
764
* @return Page object with results
765
*/
766
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, QueryWrapper queryWrapper);
767
768
/**
769
* Paginate results by QueryWrapper from schema.table
770
* @param schema database schema name
771
* @param tableName table name
772
* @param pageNumber current page number (1-based)
773
* @param pageSize number of rows per page
774
* @param queryWrapper query wrapper with conditions
775
* @return Page object with results
776
*/
777
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, QueryWrapper queryWrapper);
778
779
/**
780
* Paginate results by QueryWrapper with total count provided
781
* @param tableName table name
782
* @param pageNumber current page number (1-based)
783
* @param pageSize number of rows per page
784
* @param totalRow total number of rows (skips count query if provided)
785
* @param queryWrapper query wrapper with conditions
786
* @return Page object with results
787
*/
788
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryWrapper queryWrapper);
789
790
/**
791
* Paginate results by QueryWrapper with total count provided from schema.table
792
* @param schema database schema name
793
* @param tableName table name
794
* @param pageNumber current page number (1-based)
795
* @param pageSize number of rows per page
796
* @param totalRow total number of rows (skips count query if provided)
797
* @param queryWrapper query wrapper with conditions
798
* @return Page object with results
799
*/
800
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryWrapper queryWrapper);
801
802
/**
803
* Paginate results using Page object
804
* @param tableName table name
805
* @param page page configuration (with totalCount for optimization)
806
* @param queryWrapper query wrapper with conditions
807
* @return Page object with results
808
*/
809
public static Page<Row> paginate(String tableName, Page<Row> page, QueryWrapper queryWrapper);
810
811
/**
812
* Paginate results using Page object from schema.table
813
* @param schema database schema name
814
* @param tableName table name
815
* @param page page configuration (with totalCount for optimization)
816
* @param queryWrapper query wrapper with conditions
817
* @return Page object with results
818
*/
819
public static Page<Row> paginate(String schema, String tableName, Page<Row> page, QueryWrapper queryWrapper);
820
821
// BATCH EXECUTION UTILITIES
822
823
/**
824
* Generic batch execution with total size and batch size control
825
* @param totalSize total number of operations
826
* @param batchSize number of operations per batch
827
* @param mapperClass mapper class to use
828
* @param consumer operation consumer
829
* @return array of execution results
830
*/
831
public static <M> int[] executeBatch(int totalSize, int batchSize, Class<M> mapperClass, BiConsumer<M, Integer> consumer);
832
833
/**
834
* Generic batch execution with data collection
835
* @param datas collection of data items
836
* @param mapperClass mapper class to use
837
* @param consumer operation consumer
838
* @return array of execution results
839
*/
840
public static <M, D> int[] executeBatch(Collection<D> datas, Class<M> mapperClass, BiConsumer<M, D> consumer);
841
842
/**
843
* Generic batch execution with data collection and batch size control
844
* @param datas collection of data items
845
* @param batchSize number of items per batch
846
* @param mapperClass mapper class to use
847
* @param consumer operation consumer
848
* @return array of execution results
849
*/
850
public static <M, E> int[] executeBatch(Collection<E> datas, int batchSize, Class<M> mapperClass, BiConsumer<M, E> consumer);
851
852
// TRANSACTION OPERATIONS
853
854
/**
855
* Execute operation in transaction (returns false/null or throws exception to rollback)
856
* @param supplier operation that returns boolean result
857
* @return true if transaction committed successfully
858
*/
859
public static boolean tx(Supplier<Boolean> supplier);
860
861
/**
862
* Execute operation in transaction with propagation control
863
* @param supplier operation that returns boolean result
864
* @param propagation transaction propagation behavior
865
* @return true if transaction committed successfully
866
*/
867
public static boolean tx(Supplier<Boolean> supplier, Propagation propagation);
868
869
/**
870
* Execute operation in transaction and return result (only rollback on exception)
871
* @param supplier operation that returns result
872
* @return operation result
873
*/
874
public static <T> T txWithResult(Supplier<T> supplier);
875
876
/**
877
* Execute operation in transaction with propagation control and return result
878
* @param supplier operation that returns result
879
* @param propagation transaction propagation behavior
880
* @return operation result
881
*/
882
public static <T> T txWithResult(Supplier<T> supplier, Propagation propagation);
883
}
884
```
885
886
**Comprehensive Insert Operations:**
887
888
```java
889
import com.mybatisflex.core.row.Db;
890
import com.mybatisflex.core.row.Row;
891
import com.mybatisflex.core.query.QueryWrapper;
892
import com.mybatisflex.core.paginate.Page;
893
import java.util.*;
894
895
public class DbOperationsExample {
896
public void demonstrateInsertOperations() {
897
// Basic insert operations
898
Row userRow = Row.ofMap(Map.of(
899
"name", "Alice",
900
"age", 25,
901
"email", "alice@example.com",
902
"active", true
903
));
904
int inserted = Db.insert("users", userRow);
905
906
// Schema-aware insert
907
int insertedWithSchema = Db.insert("public", "users", userRow);
908
909
// Raw SQL insert
910
int sqlInserted = Db.insertBySql(
911
"INSERT INTO users (name, age, email) VALUES (?, ?, ?)",
912
"Diana", 32, "diana@example.com"
913
);
914
915
// Batch insert with different approaches
916
List<Row> userRows = Arrays.asList(
917
Row.ofMap(Map.of("name", "Bob", "age", 30, "email", "bob@example.com")),
918
Row.ofMap(Map.of("name", "Charlie", "age", 28, "email", "charlie@example.com"))
919
);
920
921
// Standard batch insert
922
int[] batchResults = Db.insertBatch("users", userRows);
923
924
// Batch insert with custom batch size
925
int[] controlledBatch = Db.insertBatch("users", userRows, 500);
926
927
// High-performance batch insert (uses first row's columns)
928
int highPerfBatch = Db.insertBatchWithFirstRowColumns("users", userRows);
929
930
// Schema-aware batch operations
931
int[] schemaBatch = Db.insertBatch("public", "users", userRows, 1000);
932
}
933
}
934
```
935
936
### Row Data Structure
937
938
Flexible data structure representing a database row with Map-like interface for dynamic column access.
939
940
```java { .api }
941
/**
942
* Represents a database row with flexible column access
943
*/
944
public class Row extends LinkedHashMap<String, Object> {
945
/**
946
* Create Row from Map
947
* @param map source map with column-value pairs
948
* @return new Row instance
949
*/
950
public static Row ofMap(Map<String, Object> map);
951
952
/**
953
* Create empty Row
954
* @return new empty Row instance
955
*/
956
public static Row create();
957
958
/**
959
* Set column value
960
* @param column column name
961
* @param value column value
962
* @return this Row for chaining
963
*/
964
public Row set(String column, Object value);
965
966
/**
967
* Get column value
968
* @param column column name
969
* @return column value
970
*/
971
public Object get(String column);
972
973
/**
974
* Get column value with type casting
975
* @param column column name
976
* @param clazz target type class
977
* @return typed column value
978
*/
979
public <T> T get(String column, Class<T> clazz);
980
981
/**
982
* Get string value
983
* @param column column name
984
* @return string value or null
985
*/
986
public String getString(String column);
987
988
/**
989
* Get integer value
990
* @param column column name
991
* @return integer value or null
992
*/
993
public Integer getInt(String column);
994
995
/**
996
* Get long value
997
* @param column column name
998
* @return long value or null
999
*/
1000
public Long getLong(String column);
1001
1002
/**
1003
* Get boolean value
1004
* @param column column name
1005
* @return boolean value or null
1006
*/
1007
public Boolean getBoolean(String column);
1008
1009
/**
1010
* Get date value
1011
* @param column column name
1012
* @return date value or null
1013
*/
1014
public Date getDate(String column);
1015
1016
/**
1017
* Check if column exists
1018
* @param column column name
1019
* @return true if column exists
1020
*/
1021
public boolean hasColumn(String column);
1022
1023
/**
1024
* Remove column
1025
* @param column column name
1026
* @return removed value
1027
*/
1028
public Object remove(String column);
1029
1030
/**
1031
* Convert to Map
1032
* @return Map representation
1033
*/
1034
public Map<String, Object> toMap();
1035
}
1036
```
1037
1038
**Row Usage Examples:**
1039
1040
```java
1041
public void demonstrateRowOperations() {
1042
// Create Row from Map
1043
Row user = Row.ofMap(Map.of(
1044
"id", 1L,
1045
"name", "Alice",
1046
"age", 25,
1047
"email", "alice@example.com",
1048
"active", true,
1049
"create_time", new Date()
1050
));
1051
1052
// Create Row with chaining
1053
Row product = Row.create()
1054
.set("name", "Laptop")
1055
.set("price", 999.99)
1056
.set("category", "Electronics")
1057
.set("in_stock", true);
1058
1059
// Type-safe value retrieval
1060
String name = user.getString("name");
1061
Integer age = user.getInt("age");
1062
Boolean active = user.getBoolean("active");
1063
Date createTime = user.getDate("create_time");
1064
1065
// Generic type casting
1066
Long id = user.get("id", Long.class);
1067
Double price = product.get("price", Double.class);
1068
1069
// Check column existence
1070
if (user.hasColumn("email")) {
1071
String email = user.getString("email");
1072
System.out.println("Email: " + email);
1073
}
1074
1075
// Convert back to Map
1076
Map<String, Object> userMap = user.toMap();
1077
}
1078
```
1079
1080
### Advanced Delete Operations
1081
1082
Comprehensive delete operations with multiple condition types and schema support.
1083
1084
**Delete Examples:**
1085
1086
```java
1087
public void demonstrateDeleteOperations() {
1088
// Raw SQL delete
1089
int deleted = Db.deleteBySql(
1090
"DELETE FROM users WHERE active = ? AND last_login < ?",
1091
false, thirtyDaysAgo
1092
);
1093
1094
// Delete by primary key (Row)
1095
Row pkRow = Row.ofKey(RowKey.of("id"), 123L);
1096
int deletedById = Db.deleteById("users", pkRow);
1097
1098
// Delete by single primary key
1099
int singlePkDelete = Db.deleteById("users", "id", 123L);
1100
1101
// Schema-aware delete
1102
int schemaDelete = Db.deleteById("public", "users", "id", 123L);
1103
1104
// Batch delete by IDs
1105
List<Long> idsToDelete = Arrays.asList(1L, 2L, 3L, 4L);
1106
int batchDeleted = Db.deleteBatchByIds("users", "id", idsToDelete);
1107
1108
// Delete by Map conditions
1109
Map<String, Object> deleteConditions = Map.of(
1110
"active", false,
1111
"account_type", "trial"
1112
);
1113
int mapDeleted = Db.deleteByMap("users", deleteConditions);
1114
1115
// Delete by QueryCondition
1116
QueryCondition condition = USER.AGE.ge(65).and(USER.LAST_LOGIN.lt(sixMonthsAgo));
1117
int conditionDeleted = Db.deleteByCondition("users", condition);
1118
1119
// Delete by QueryWrapper
1120
QueryWrapper deleteQuery = QueryWrapper.create()
1121
.where(USER.ACTIVE.eq(false))
1122
.and(USER.CREATED_TIME.lt(oneYearAgo));
1123
int queryDeleted = Db.deleteByQuery("users", deleteQuery);
1124
}
1125
```
1126
1127
### Advanced Update Operations
1128
1129
Comprehensive update operations with various condition types and batch support.
1130
1131
**Update Examples:**
1132
1133
```java
1134
public void demonstrateUpdateOperations() {
1135
// Raw SQL update
1136
int updated = Db.updateBySql(
1137
"UPDATE users SET age = ?, last_login = ? WHERE id = ?",
1138
26, new Date(), 1L
1139
);
1140
1141
// Update by primary key
1142
Row updateRow = Row.create()
1143
.set("id", 1L) // Primary key
1144
.set("name", "Alice Updated")
1145
.set("email", "alice.updated@example.com")
1146
.set("last_modified", new Date());
1147
int pkUpdated = Db.updateById("users", updateRow);
1148
1149
// Schema-aware update
1150
int schemaUpdated = Db.updateById("public", "users", updateRow);
1151
1152
// Update by Map conditions
1153
Row updateData = Row.create()
1154
.set("status", "verified")
1155
.set("verified_date", new Date());
1156
Map<String, Object> whereConditions = Map.of(
1157
"email_verified", true,
1158
"account_type", "premium"
1159
);
1160
int mapUpdated = Db.updateByMap("users", updateData, whereConditions);
1161
1162
// Update by QueryCondition
1163
QueryCondition condition = USER.AGE.ge(18).and(USER.ACTIVE.eq(true));
1164
Row adultUserUpdate = Row.create().set("adult_flag", true);
1165
int conditionUpdated = Db.updateByCondition("users", adultUserUpdate, condition);
1166
1167
// Update by QueryWrapper
1168
QueryWrapper updateQuery = QueryWrapper.create()
1169
.where(USER.LAST_LOGIN.lt(thirtyDaysAgo))
1170
.and(USER.ACTIVE.eq(true));
1171
Row inactiveUpdate = Row.create().set("status", "inactive");
1172
int queryUpdated = Db.updateByQuery("users", inactiveUpdate, updateQuery);
1173
1174
// Batch update by primary keys
1175
List<Row> batchUpdateRows = Arrays.asList(
1176
Row.create().set("id", 1L).set("status", "active"),
1177
Row.create().set("id", 2L).set("status", "inactive"),
1178
Row.create().set("id", 3L).set("status", "pending")
1179
);
1180
int batchUpdated = Db.updateBatchById("users", batchUpdateRows);
1181
1182
// Schema-aware batch update
1183
int schemaBatchUpdated = Db.updateBatchById("public", "users", batchUpdateRows);
1184
}
1185
```
1186
1187
### Comprehensive Select Operations
1188
1189
Advanced select operations with multiple approaches and schema support.
1190
1191
**Select Examples:**
1192
1193
```java
1194
public void demonstrateSelectOperations() {
1195
// Raw SQL select returning Rows
1196
List<Row> users = Db.selectListBySql(
1197
"SELECT id, name, age, email FROM users WHERE age >= ?",
1198
18
1199
);
1200
1201
// Single row by SQL
1202
Row user = Db.selectOneBySql(
1203
"SELECT * FROM users WHERE id = ?",
1204
1L
1205
);
1206
1207
// Select by primary key
1208
Row pkRow = Row.ofKey(RowKey.of("id"), 1L);
1209
Row selectedById = Db.selectOneById("users", pkRow);
1210
1211
// Select by single primary key
1212
Row singlePkSelect = Db.selectOneById("users", "id", 1L);
1213
1214
// Schema-aware select
1215
Row schemaSelect = Db.selectOneById("public", "users", "id", 1L);
1216
1217
// Select by Map conditions
1218
Map<String, Object> selectConditions = Map.of(
1219
"active", true,
1220
"account_type", "premium"
1221
);
1222
List<Row> mapSelected = Db.selectListByMap("users", selectConditions);
1223
1224
// Select by Map with limit
1225
List<Row> limitedMapSelect = Db.selectListByMap("users", selectConditions, 10L);
1226
1227
// Select by QueryCondition
1228
QueryCondition condition = USER.AGE.between(25, 35).and(USER.ACTIVE.eq(true));
1229
List<Row> conditionSelected = Db.selectListByCondition("users", condition);
1230
1231
// Select by QueryCondition with limit
1232
List<Row> limitedCondition = Db.selectListByCondition("users", condition, 5L);
1233
1234
// Select by QueryWrapper
1235
QueryWrapper selectQuery = QueryWrapper.create()
1236
.select(USER.ID, USER.NAME, USER.EMAIL)
1237
.from(USER)
1238
.where(USER.ACTIVE.eq(true))
1239
.orderBy(USER.CREATED_TIME.desc())
1240
.limit(20);
1241
List<Row> querySelected = Db.selectListByQuery("users", selectQuery);
1242
1243
// Select with QueryWrapper containing FROM clause
1244
List<Row> fullQuerySelect = Db.selectListByQuery(selectQuery);
1245
1246
// Select all rows
1247
List<Row> allUsers = Db.selectAll("users");
1248
List<Row> allSchemaUsers = Db.selectAll("public", "users");
1249
}
1250
1251
private List<Row> generateLargeDataSet() {
1252
// Helper method for batch examples
1253
List<Row> data = new ArrayList<>();
1254
for (int i = 0; i < 5000; i++) {
1255
data.add(Row.create()
1256
.set("id", i)
1257
.set("status", "pending")
1258
.set("created_time", new Date()));
1259
}
1260
return data;
1261
}
1262
1263
private String generateAccountNumber() {
1264
return "ACC" + System.currentTimeMillis();
1265
}
1266
```
1267
1268
### Object Selection and Specialized Queries
1269
1270
Specialized selection methods for single values, object lists, and key-value mappings.
1271
1272
**Object Selection Examples:**
1273
1274
```java
1275
public void demonstrateObjectSelection() {
1276
// Select single object (1 row, 1 column)
1277
Long userCount = (Long) Db.selectObject(
1278
"SELECT COUNT(*) FROM users WHERE active = ?",
1279
true
1280
);
1281
1282
// Select object by QueryWrapper
1283
QueryWrapper countQuery = QueryWrapper.create()
1284
.select(Functions.count())
1285
.from(USER)
1286
.where(USER.ACTIVE.eq(true));
1287
Long countByQuery = (Long) Db.selectObject("users", countQuery);
1288
1289
// Select with schema
1290
Long schemaCount = (Long) Db.selectObject("public", "users", countQuery);
1291
1292
// Select first and second columns as Map (key-value pairs)
1293
Map<String, String> userNameEmailMap = Db.selectFirstAndSecondColumnsAsMap(
1294
"SELECT name, email FROM users WHERE active = ?",
1295
true
1296
);
1297
1298
// Key-value mapping by QueryWrapper
1299
QueryWrapper kvQuery = QueryWrapper.create()
1300
.select(USER.NAME, USER.EMAIL)
1301
.from(USER)
1302
.where(USER.ACTIVE.eq(true));
1303
Map<String, String> kvByQuery = Db.selectFirstAndSecondColumnsAsMap("users", kvQuery);
1304
1305
// Select multiple object values (multiple rows, 1 column)
1306
List<Object> userIds = Db.selectObjectList(
1307
"SELECT id FROM users WHERE active = ?",
1308
true
1309
);
1310
1311
// Object list by QueryWrapper
1312
QueryWrapper listQuery = QueryWrapper.create()
1313
.select(USER.ID)
1314
.from(USER)
1315
.where(USER.ACTIVE.eq(true));
1316
List<Object> idsByQuery = Db.selectObjectList("users", listQuery);
1317
1318
// Schema-aware object selection
1319
List<Object> schemaIds = Db.selectObjectList("public", "users", listQuery);
1320
1321
// Full query object selection
1322
QueryWrapper fullListQuery = QueryWrapper.create()
1323
.select(USER.EMAIL)
1324
.from(USER)
1325
.where(USER.ACTIVE.eq(true))
1326
.orderBy(USER.CREATED_TIME.desc())
1327
.limit(100);
1328
List<Object> fullQueryIds = Db.selectObjectList(fullListQuery);
1329
}
1330
```
1331
```
1332
1333
### Count Operations and Statistics
1334
1335
Efficient counting and statistical operations with various condition types.
1336
1337
**Count Examples:**
1338
1339
```java
1340
public void demonstrateCountOperations() {
1341
// Raw SQL count
1342
long totalUsers = Db.selectCount(
1343
"SELECT COUNT(*) FROM users WHERE active = ?",
1344
true
1345
);
1346
1347
// Count by QueryCondition
1348
QueryCondition ageCondition = USER.AGE.between(18, 65);
1349
long adultCount = Db.selectCountByCondition("users", ageCondition);
1350
1351
// Schema-aware count
1352
long schemaCount = Db.selectCountByCondition("public", "users", ageCondition);
1353
1354
// Count by QueryWrapper
1355
QueryWrapper countQuery = QueryWrapper.create()
1356
.from(USER)
1357
.where(USER.ACTIVE.eq(true))
1358
.and(USER.EMAIL_VERIFIED.eq(true));
1359
long verifiedActiveCount = Db.selectCountByQuery("users", countQuery);
1360
1361
// Schema-aware QueryWrapper count
1362
long schemaQueryCount = Db.selectCountByQuery("public", "users", countQuery);
1363
1364
// Count with QueryWrapper containing FROM clause
1365
QueryWrapper fullCountQuery = QueryWrapper.create()
1366
.select(Functions.count())
1367
.from(USER)
1368
.where(USER.REGISTRATION_DATE.ge(thisYear));
1369
long fullQueryCount = Db.selectCountByQuery(fullCountQuery);
1370
}
1371
```
1372
1373
### Pagination Operations
1374
1375
Comprehensive pagination support with automatic count optimization and flexible configurations.
1376
1377
**Pagination Examples:**
1378
1379
```java
1380
public void demonstratePaginationOperations() {
1381
// Basic pagination by QueryCondition
1382
QueryCondition activeCondition = USER.ACTIVE.eq(true);
1383
Page<Row> page1 = Db.paginate("users", 1, 20, activeCondition);
1384
1385
System.out.println("Page: " + page1.getPageNumber());
1386
System.out.println("Size: " + page1.getPageSize());
1387
System.out.println("Total: " + page1.getTotalRow());
1388
System.out.println("Pages: " + page1.getTotalPage());
1389
1390
// Schema-aware pagination
1391
Page<Row> schemaPage = Db.paginate("public", "users", 1, 20, activeCondition);
1392
1393
// Pagination with known total count (skips count query for performance)
1394
long knownTotal = 1000L;
1395
Page<Row> optimizedPage = Db.paginate("users", 2, 20, knownTotal, activeCondition);
1396
1397
// Pagination by QueryWrapper
1398
QueryWrapper pageQuery = QueryWrapper.create()
1399
.select(USER.ID, USER.NAME, USER.EMAIL, USER.CREATED_TIME)
1400
.from(USER)
1401
.where(USER.ACTIVE.eq(true))
1402
.and(USER.EMAIL_VERIFIED.eq(true))
1403
.orderBy(USER.CREATED_TIME.desc());
1404
1405
Page<Row> queryPage = Db.paginate("users", 1, 25, pageQuery);
1406
1407
// Schema-aware QueryWrapper pagination
1408
Page<Row> schemaQueryPage = Db.paginate("public", "users", 1, 25, pageQuery);
1409
1410
// Pagination with QueryWrapper and known total
1411
Page<Row> optimizedQueryPage = Db.paginate("users", 3, 25, 2500L, pageQuery);
1412
1413
// Advanced pagination using Page object
1414
Page<Row> customPage = new Page<>(2, 30);
1415
customPage.setTotalRow(5000L); // Set known total for optimization
1416
Page<Row> advancedPage = Db.paginate("users", customPage, pageQuery);
1417
1418
// Schema-aware advanced pagination
1419
Page<Row> schemaAdvancedPage = Db.paginate("public", "users", customPage, pageQuery);
1420
1421
// Process paginated results
1422
for (Row user : queryPage.getRecords()) {
1423
System.out.println("User: " + user.getString("name") +
1424
", Email: " + user.getString("email"));
1425
}
1426
}
1427
```
1428
```
1429
1430
### Advanced Batch Operations
1431
1432
Powerful batch processing utilities with generic mapper support and flexible execution patterns.
1433
1434
**Batch Execution Examples:**
1435
1436
```java
1437
public void demonstrateBatchExecutionUtilities() {
1438
// Generic batch execution with total size control
1439
int totalOperations = 10000;
1440
int batchSize = 500;
1441
int[] results = Db.executeBatch(totalOperations, batchSize, RowMapper.class,
1442
(mapper, index) -> {
1443
// Execute operation for each index
1444
Row data = Row.create()
1445
.set("batch_id", index / batchSize)
1446
.set("item_index", index)
1447
.set("processed_time", new Date());
1448
return mapper.insert(null, "batch_log", data);
1449
});
1450
1451
// Batch execution with data collection
1452
List<String> emailsToProcess = Arrays.asList(
1453
"user1@example.com", "user2@example.com", "user3@example.com"
1454
);
1455
1456
int[] emailResults = Db.executeBatch(emailsToProcess, RowMapper.class,
1457
(mapper, email) -> {
1458
Row emailLog = Row.create()
1459
.set("email", email)
1460
.set("status", "processed")
1461
.set("processed_time", new Date());
1462
return mapper.insert(null, "email_log", emailLog);
1463
});
1464
1465
// Batch execution with data collection and batch size control
1466
List<Row> dataToProcess = generateLargeDataSet();
1467
int[] controlledResults = Db.executeBatch(dataToProcess, 1000, RowMapper.class,
1468
(mapper, row) -> {
1469
// Process each row
1470
row.set("processed", true);
1471
row.set("process_time", new Date());
1472
return mapper.updateById(null, "processing_queue", row);
1473
});
1474
1475
System.out.println("Processed " + controlledResults.length + " items");
1476
}
1477
1478
// Custom batch arguments setter example
1479
public void demonstrateCustomBatchUpdate() {
1480
BatchArgsSetter batchSetter = new BatchArgsSetter() {
1481
private final List<Object[]> batchArgs = Arrays.asList(
1482
new Object[]{"active", new Date(), 1L},
1483
new Object[]{"inactive", new Date(), 2L},
1484
new Object[]{"pending", new Date(), 3L}
1485
);
1486
1487
@Override
1488
public int getBatchSize() {
1489
return batchArgs.size();
1490
}
1491
1492
@Override
1493
public Object[] getSqlArgs(int index) {
1494
return batchArgs.get(index);
1495
}
1496
};
1497
1498
int[] updateResults = Db.updateBatch(
1499
"UPDATE users SET status = ?, last_updated = ? WHERE id = ?",
1500
batchSetter
1501
);
1502
}
1503
```
1504
1505
### Multi-Datasource and Environment Support
1506
1507
Support for multiple datasources and environment-specific database operations.
1508
1509
**Multi-Environment Examples:**
1510
1511
```java
1512
public void demonstrateMultiEnvironmentOperations() {
1513
// Get invoker for specific environment
1514
RowMapperInvoker primaryInvoker = Db.invoker(); // Default environment
1515
RowMapperInvoker analyticsInvoker = Db.invoker("analytics"); // Analytics DB
1516
RowMapperInvoker reportingInvoker = Db.invoker("reporting"); // Reporting DB
1517
1518
// All Db methods work with default environment
1519
// For specific environments, you would use the invokers directly
1520
// or configure the FlexGlobalConfig appropriately
1521
1522
// Example of cross-environment data synchronization
1523
List<Row> primaryData = Db.selectAll("users"); // From primary DB
1524
1525
// Process and insert into analytics environment
1526
// (This would require using the specific invoker or environment configuration)
1527
for (Row user : primaryData) {
1528
Row analyticsRow = Row.create()
1529
.set("user_id", user.get("id"))
1530
.set("name", user.getString("name"))
1531
.set("registration_date", user.getDate("created_time"))
1532
.set("sync_time", new Date());
1533
1534
// Insert would use analytics environment configuration
1535
// analyticsInvoker.insert(null, "user_analytics", analyticsRow);
1536
}
1537
}
1538
```
1539
```
1540
1541
### Advanced Transaction Management
1542
1543
Comprehensive transaction support with propagation control and flexible execution patterns.
1544
1545
**Transaction API:**
1546
1547
```java { .api }
1548
// Basic transaction operations
1549
public static boolean tx(Supplier<Boolean> supplier);
1550
public static boolean tx(Supplier<Boolean> supplier, Propagation propagation);
1551
public static <T> T txWithResult(Supplier<T> supplier);
1552
public static <T> T txWithResult(Supplier<T> supplier, Propagation propagation);
1553
1554
// Transaction propagation types
1555
public enum Propagation {
1556
REQUIRED, // Join existing or create new transaction
1557
REQUIRES_NEW, // Always create new transaction
1558
SUPPORTS, // Join existing, no transaction if none exists
1559
NOT_SUPPORTED, // Execute without transaction
1560
NEVER, // Throw exception if transaction exists
1561
MANDATORY // Throw exception if no transaction exists
1562
}
1563
```
1564
1565
**Advanced Transaction Examples:**
1566
1567
```java
1568
public void demonstrateAdvancedTransactions() {
1569
// Basic transaction with boolean result (rollback on false/null or exception)
1570
boolean success = Db.tx(() -> {
1571
// Complex business logic
1572
Row newUser = Row.create()
1573
.set("name", "Transaction User")
1574
.set("email", "tx.user@example.com")
1575
.set("balance", 1000.00);
1576
1577
int userInserted = Db.insert("users", newUser);
1578
1579
// Create account
1580
Row account = Row.create()
1581
.set("user_id", newUser.get("id"))
1582
.set("account_number", generateAccountNumber())
1583
.set("balance", 1000.00)
1584
.set("status", "active");
1585
1586
int accountInserted = Db.insert("accounts", account);
1587
1588
// Log transaction
1589
Row transactionLog = Row.create()
1590
.set("action", "account_creation")
1591
.set("user_id", newUser.get("id"))
1592
.set("amount", 1000.00)
1593
.set("timestamp", new Date());
1594
1595
int logInserted = Db.insert("transaction_log", transactionLog);
1596
1597
// Return false to rollback, true to commit
1598
return userInserted > 0 && accountInserted > 0 && logInserted > 0;
1599
});
1600
1601
// Transaction with result (only rollback on exception)
1602
String processResult = Db.txWithResult(() -> {
1603
// Process payments
1604
List<Row> pendingPayments = Db.selectListByMap("payments",
1605
Map.of("status", "pending"));
1606
1607
int processedCount = 0;
1608
for (Row payment : pendingPayments) {
1609
// Update payment status
1610
Row updateData = Row.create().set("status", "processed");
1611
Map<String, Object> whereCondition = Map.of("id", payment.get("id"));
1612
1613
int updated = Db.updateByMap("payments", updateData, whereCondition);
1614
if (updated > 0) {
1615
processedCount++;
1616
}
1617
}
1618
1619
return "Processed " + processedCount + " payments";
1620
});
1621
1622
// Transaction with propagation control
1623
boolean nestedResult = Db.tx(() -> {
1624
// Outer transaction
1625
Row outerData = Row.create().set("level", "outer").set("timestamp", new Date());
1626
Db.insert("transaction_test", outerData);
1627
1628
// Inner transaction with REQUIRES_NEW (creates separate transaction)
1629
String innerResult = Db.txWithResult(() -> {
1630
Row innerData = Row.create().set("level", "inner").set("timestamp", new Date());
1631
Db.insert("transaction_test", innerData);
1632
return "Inner transaction completed";
1633
}, Propagation.REQUIRES_NEW);
1634
1635
// This will commit/rollback independently of inner transaction
1636
return innerResult != null;
1637
}, Propagation.REQUIRED);
1638
1639
// Complex transaction with error handling
1640
try {
1641
boolean complexResult = Db.tx(() -> {
1642
// Multiple related operations
1643
1644
// 1. Create order
1645
Row order = Row.create()
1646
.set("customer_id", 123L)
1647
.set("total_amount", 299.99)
1648
.set("status", "pending")
1649
.set("created_time", new Date());
1650
int orderCreated = Db.insert("orders", order);
1651
1652
// 2. Update inventory
1653
Row inventoryUpdate = Row.create().set("quantity",
1654
Functions.subtract(INVENTORY.QUANTITY, 1));
1655
int inventoryUpdated = Db.updateByMap("inventory", inventoryUpdate,
1656
Map.of("product_id", 456L));
1657
1658
// 3. Create payment record
1659
Row payment = Row.create()
1660
.set("order_id", order.get("id"))
1661
.set("amount", 299.99)
1662
.set("payment_method", "credit_card")
1663
.set("status", "pending");
1664
int paymentCreated = Db.insert("payments", payment);
1665
1666
// All operations must succeed
1667
return orderCreated > 0 && inventoryUpdated > 0 && paymentCreated > 0;
1668
});
1669
1670
if (complexResult) {
1671
System.out.println("Order processing completed successfully");
1672
} else {
1673
System.out.println("Order processing failed and was rolled back");
1674
}
1675
} catch (Exception e) {
1676
System.err.println("Transaction failed with exception: " + e.getMessage());
1677
// Transaction was automatically rolled back
1678
}
1679
}
1680
```
1681
```
1682
1683
## Types and Supporting Classes
1684
1685
```java { .api }
1686
// Core Row operations
1687
public class Row extends LinkedHashMap<String, Object> {
1688
public static Row ofMap(Map<String, Object> map);
1689
public static Row ofKey(RowKey rowKey, Object value);
1690
public static Row create();
1691
public Row set(String column, Object value);
1692
public <T> T get(String column, Class<T> clazz);
1693
public String getString(String column);
1694
public Integer getInt(String column);
1695
public Long getLong(String column);
1696
public Boolean getBoolean(String column);
1697
public Date getDate(String column);
1698
}
1699
1700
// Primary key support
1701
public class RowKey {
1702
public static RowKey of(String keyColumn);
1703
public static RowKey of(String... keyColumns);
1704
}
1705
1706
// Pagination support
1707
public class Page<T> {
1708
public Page(Number pageNumber, Number pageSize);
1709
public Page(Number pageNumber, Number pageSize, Number totalRow);
1710
public int getPageNumber();
1711
public int getPageSize();
1712
public long getTotalRow();
1713
public int getTotalPage();
1714
public List<T> getRecords();
1715
public void setTotalRow(long totalRow);
1716
}
1717
1718
// Query building
1719
public class QueryWrapper {
1720
public static QueryWrapper create();
1721
public QueryWrapper select(QueryColumn... columns);
1722
public QueryWrapper from(QueryTable table);
1723
public QueryWrapper where(QueryCondition condition);
1724
public QueryWrapper where(Map<String, Object> whereColumns);
1725
public QueryWrapper and(QueryCondition condition);
1726
public QueryWrapper orderBy(QueryColumn column);
1727
public QueryWrapper limit(Long limit);
1728
}
1729
1730
// Query conditions
1731
public class QueryCondition {
1732
// Created through QueryColumn methods
1733
}
1734
1735
// Batch processing
1736
public interface BatchArgsSetter {
1737
int getBatchSize();
1738
Object[] getSqlArgs(int index);
1739
}
1740
1741
// Transaction propagation
1742
public enum Propagation {
1743
REQUIRED, REQUIRES_NEW, SUPPORTS, NOT_SUPPORTED, NEVER, MANDATORY
1744
}
1745
1746
// Multi-environment support
1747
public class RowMapperInvoker {
1748
// Used for environment-specific operations
1749
// Accessible via Db.invoker() and Db.invoker(environmentId)
1750
}
1751
1752
// Functional interfaces
1753
@FunctionalInterface
1754
public interface Supplier<T> {
1755
T get();
1756
}
1757
1758
@FunctionalInterface
1759
public interface BiConsumer<T, U> {
1760
void accept(T t, U u);
1761
}
1762
1763
// Standard Java collections
1764
public interface Collection<E> {
1765
int size();
1766
boolean isEmpty();
1767
Iterator<E> iterator();
1768
}
1769
1770
public interface List<E> extends Collection<E> {
1771
E get(int index);
1772
int size();
1773
boolean isEmpty();
1774
}
1775
1776
public interface Map<K, V> {
1777
V get(Object key);
1778
V put(K key, V value);
1779
Set<K> keySet();
1780
Collection<V> values();
1781
}
1782
```