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.select;
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.render.RenderingStrategy;
25  import org.mybatis.dynamic.sql.select.render.MultiSelectRenderer;
26  import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
27  import org.mybatis.dynamic.sql.util.Validator;
28  
29  public class MultiSelectModel extends AbstractSelectModel {
30      private final SelectModel initialSelect;
31      private final List<UnionQuery> unionQueries;
32  
33      private MultiSelectModel(Builder builder) {
34          super(builder);
35          initialSelect = Objects.requireNonNull(builder.initialSelect);
36          unionQueries = builder.unionQueries;
37          Validator.assertNotEmpty(unionQueries, "ERROR.35"); //$NON-NLS-1$
38      }
39  
40      public SelectModel initialSelect() {
41          return initialSelect;
42      }
43  
44      public Stream<UnionQuery> unionQueries() {
45          return unionQueries.stream();
46      }
47  
48      public SelectStatementProvider render(RenderingStrategy renderingStrategy) {
49          return MultiSelectRenderer.withMultiSelectModel(this)
50                  .withRenderingStrategy(renderingStrategy)
51                  .build()
52                  .render();
53      }
54  
55      public static class Builder extends AbstractBuilder<Builder> {
56          private @Nullable SelectModel initialSelect;
57          private final List<UnionQuery> unionQueries = new ArrayList<>();
58  
59          public Builder withInitialSelect(SelectModel initialSelect) {
60              this.initialSelect = initialSelect;
61              return this;
62          }
63  
64          public Builder withUnionQueries(List<UnionQuery> unionQueries) {
65              this.unionQueries.addAll(unionQueries);
66              return this;
67          }
68  
69          @Override
70          protected Builder getThis() {
71              return this;
72          }
73  
74          public MultiSelectModel build() {
75              return new MultiSelectModel(this);
76          }
77      }
78  }