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.Objects;
19  import java.util.Optional;
20  
21  import org.jspecify.annotations.Nullable;
22  import org.mybatis.dynamic.sql.TableExpression;
23  import org.mybatis.dynamic.sql.TableExpressionVisitor;
24  
25  public class SubQuery implements TableExpression {
26      private final SelectModel selectModel;
27      private final @Nullable String alias;
28  
29      private SubQuery(Builder builder) {
30          selectModel = Objects.requireNonNull(builder.selectModel);
31          alias = builder.alias;
32      }
33  
34      public SelectModel selectModel() {
35          return selectModel;
36      }
37  
38      public Optional<String> alias() {
39          return Optional.ofNullable(alias);
40      }
41  
42      @Override
43      public boolean isSubQuery() {
44          return true;
45      }
46  
47      @Override
48      public <R> R accept(TableExpressionVisitor<R> visitor) {
49          return visitor.visit(this);
50      }
51  
52      public static class Builder {
53          private @Nullable SelectModel selectModel;
54          private @Nullable String alias;
55  
56          public Builder withSelectModel(SelectModel selectModel) {
57              this.selectModel = selectModel;
58              return this;
59          }
60  
61          public Builder withAlias(@Nullable String alias) {
62              this.alias = alias;
63              return this;
64          }
65  
66          public SubQuery build() {
67              return new SubQuery(this);
68          }
69      }
70  }