View Javadoc
1   /*
2    *    Copyright 2016-2025 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.dynamic.sql.insert;
17  
18  import java.util.ArrayList;
19  import java.util.Collection;
20  import java.util.Collections;
21  import java.util.List;
22  import java.util.Objects;
23  import java.util.stream.Stream;
24  
25  import org.jspecify.annotations.Nullable;
26  import org.mybatis.dynamic.sql.SqlTable;
27  import org.mybatis.dynamic.sql.util.AbstractColumnMapping;
28  
29  public abstract class AbstractMultiRowInsertModel<T> {
30      private final SqlTable table;
31      private final List<T> records;
32      protected final List<AbstractColumnMapping> columnMappings;
33  
34      protected AbstractMultiRowInsertModel(AbstractBuilder<T, ?> builder) {
35          table = Objects.requireNonNull(builder.table);
36          records = Collections.unmodifiableList(Objects.requireNonNull(builder.records));
37          columnMappings = Objects.requireNonNull(builder.columnMappings);
38      }
39  
40      public Stream<AbstractColumnMapping> columnMappings() {
41          return columnMappings.stream();
42      }
43  
44      public List<T> records() {
45          return records;
46      }
47  
48      public SqlTable table() {
49          return table;
50      }
51  
52      public int recordCount() {
53          return records.size();
54      }
55  
56      public abstract static class AbstractBuilder<T, S extends AbstractBuilder<T, S>> {
57          private @Nullable SqlTable table;
58          private final List<T> records = new ArrayList<>();
59          private final List<AbstractColumnMapping> columnMappings = new ArrayList<>();
60  
61          public S withTable(SqlTable table) {
62              this.table = table;
63              return getThis();
64          }
65  
66          public S withRecords(Collection<T> records) {
67              this.records.addAll(records);
68              return getThis();
69          }
70  
71          public S withColumnMappings(List<AbstractColumnMapping> columnMappings) {
72              this.columnMappings.addAll(columnMappings);
73              return getThis();
74          }
75  
76          protected abstract S getThis();
77      }
78  }