1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.dynamic.sql.insert;
17
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.Objects;
21 import java.util.stream.Stream;
22
23 import org.jspecify.annotations.Nullable;
24 import org.mybatis.dynamic.sql.SqlTable;
25 import org.mybatis.dynamic.sql.insert.render.InsertRenderer;
26 import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider;
27 import org.mybatis.dynamic.sql.render.RenderingStrategy;
28 import org.mybatis.dynamic.sql.util.AbstractColumnMapping;
29 import org.mybatis.dynamic.sql.util.Validator;
30
31 public class InsertModel<T> {
32 private final SqlTable table;
33 private final T row;
34 private final List<AbstractColumnMapping> columnMappings;
35
36 private InsertModel(Builder<T> builder) {
37 table = Objects.requireNonNull(builder.table);
38 row = Objects.requireNonNull(builder.row);
39 columnMappings = Objects.requireNonNull(builder.columnMappings);
40 Validator.assertNotEmpty(columnMappings, "ERROR.7");
41 }
42
43 public Stream<AbstractColumnMapping> columnMappings() {
44 return columnMappings.stream();
45 }
46
47 public T row() {
48 return row;
49 }
50
51 public SqlTable table() {
52 return table;
53 }
54
55 public InsertStatementProvider<T> render(RenderingStrategy renderingStrategy) {
56 return InsertRenderer.withInsertModel(this)
57 .withRenderingStrategy(renderingStrategy)
58 .build()
59 .render();
60 }
61
62 public static <T> Builder<T> withRow(T row) {
63 return new Builder<T>().withRow(row);
64 }
65
66 public static class Builder<T> {
67 private @Nullable SqlTable table;
68 private @Nullable T row;
69 private final List<AbstractColumnMapping> columnMappings = new ArrayList<>();
70
71 public Builder<T> withTable(SqlTable table) {
72 this.table = table;
73 return this;
74 }
75
76 public Builder<T> withRow(T row) {
77 this.row = row;
78 return this;
79 }
80
81 public Builder<T> withColumnMappings(List<? extends AbstractColumnMapping> columnMappings) {
82 this.columnMappings.addAll(columnMappings);
83 return this;
84 }
85
86 public InsertModel<T> build() {
87 return new InsertModel<>(this);
88 }
89 }
90 }