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.render;
17  
18  import java.util.Objects;
19  
20  import org.jspecify.annotations.Nullable;
21  import org.mybatis.dynamic.sql.insert.BatchInsertModel;
22  import org.mybatis.dynamic.sql.render.RenderingStrategy;
23  
24  public class BatchInsertRenderer<T> {
25  
26      private final BatchInsertModel<T> model;
27      private final MultiRowValuePhraseVisitor visitor;
28  
29      private BatchInsertRenderer(Builder<T> builder) {
30          model = Objects.requireNonNull(builder.model);
31          visitor = new MultiRowValuePhraseVisitor(Objects.requireNonNull(builder.renderingStrategy),
32                  "row"); //$NON-NLS-1$)
33      }
34  
35      public BatchInsert<T> render() {
36          FieldAndValueCollector collector = model.columnMappings()
37                  .map(m -> m.accept(visitor))
38                  .collect(FieldAndValueCollector.collect());
39  
40          String insertStatement = InsertRenderingUtilities.calculateInsertStatement(model.table(), collector);
41  
42          return BatchInsert.withRecords(model.records())
43                  .withInsertStatement(insertStatement)
44                  .build();
45      }
46  
47      public static <T> Builder<T> withBatchInsertModel(BatchInsertModel<T> model) {
48          return new Builder<T>().withBatchInsertModel(model);
49      }
50  
51      public static class Builder<T> {
52          private @Nullable BatchInsertModel<T> model;
53          private @Nullable RenderingStrategy renderingStrategy;
54  
55          public Builder<T> withBatchInsertModel(BatchInsertModel<T> model) {
56              this.model = model;
57              return this;
58          }
59  
60          public Builder<T> withRenderingStrategy(RenderingStrategy renderingStrategy) {
61              this.renderingStrategy = renderingStrategy;
62              return this;
63          }
64  
65          public BatchInsertRenderer<T> build() {
66              return new BatchInsertRenderer<>(this);
67          }
68      }
69  }