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  import java.util.Optional;
20  
21  import org.jspecify.annotations.Nullable;
22  import org.mybatis.dynamic.sql.insert.InsertModel;
23  import org.mybatis.dynamic.sql.render.RenderingStrategy;
24  import org.mybatis.dynamic.sql.util.Validator;
25  
26  public class InsertRenderer<T> {
27  
28      private final InsertModel<T> model;
29      private final ValuePhraseVisitor visitor;
30  
31      private InsertRenderer(Builder<T> builder) {
32          model = Objects.requireNonNull(builder.model);
33          visitor = new ValuePhraseVisitor(Objects.requireNonNull(builder.renderingStrategy));
34      }
35  
36      public InsertStatementProvider<T> render() {
37          FieldAndValueCollector collector = model.columnMappings()
38                  .map(m -> m.accept(visitor))
39                  .flatMap(Optional::stream)
40                  .collect(FieldAndValueCollector.collect());
41  
42          Validator.assertFalse(collector.isEmpty(), "ERROR.10"); //$NON-NLS-1$
43  
44          String insertStatement = InsertRenderingUtilities.calculateInsertStatement(model.table(), collector);
45  
46          return DefaultInsertStatementProvider.withRow(model.row())
47                  .withInsertStatement(insertStatement)
48                  .build();
49      }
50  
51      public static <T> Builder<T> withInsertModel(InsertModel<T> model) {
52          return new Builder<T>().withInsertModel(model);
53      }
54  
55      public static class Builder<T> {
56          private @Nullable InsertModel<T> model;
57          private @Nullable RenderingStrategy renderingStrategy;
58  
59          public Builder<T> withInsertModel(InsertModel<T> model) {
60              this.model = model;
61              return this;
62          }
63  
64          public Builder<T> withRenderingStrategy(RenderingStrategy renderingStrategy) {
65              this.renderingStrategy = renderingStrategy;
66              return this;
67          }
68  
69          public InsertRenderer<T> build() {
70              return new InsertRenderer<>(this);
71          }
72      }
73  }