1
2
3
4
5
6
7
8
9
10
11
12
13
14
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");
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 }