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;
17  
18  import java.util.ArrayList;
19  import java.util.Collections;
20  import java.util.List;
21  import java.util.Objects;
22  import java.util.Optional;
23  
24  import org.jspecify.annotations.Nullable;
25  
26  /**
27   * This class represents a criteria group with either an AND or an OR connector.
28   * This class is intentionally NOT derived from SqlCriterion because we only want it to be
29   * available where an AND or an OR condition is appropriate.
30   *
31   * @author Jeff Butler
32   *
33   * @since 1.4.0
34   */
35  public class AndOrCriteriaGroup {
36      private final String connector;
37      private final @Nullable SqlCriterion initialCriterion;
38      private final List<AndOrCriteriaGroup> subCriteria;
39  
40      private AndOrCriteriaGroup(Builder builder) {
41          connector = Objects.requireNonNull(builder.connector);
42          initialCriterion = builder.initialCriterion;
43          subCriteria = builder.subCriteria;
44      }
45  
46      public String connector() {
47          return connector;
48      }
49  
50      public Optional<SqlCriterion> initialCriterion() {
51          return Optional.ofNullable(initialCriterion);
52      }
53  
54      public List<AndOrCriteriaGroup> subCriteria() {
55          return Collections.unmodifiableList(subCriteria);
56      }
57  
58      public static class Builder {
59          private @Nullable String connector;
60          private @Nullable SqlCriterion initialCriterion;
61          private final List<AndOrCriteriaGroup> subCriteria = new ArrayList<>();
62  
63          public Builder withConnector(String connector) {
64              this.connector = connector;
65              return this;
66          }
67  
68          public Builder withInitialCriterion(@Nullable SqlCriterion initialCriterion) {
69              this.initialCriterion = initialCriterion;
70              return this;
71          }
72  
73          public Builder withSubCriteria(List<AndOrCriteriaGroup> subCriteria) {
74              this.subCriteria.addAll(subCriteria);
75              return this;
76          }
77  
78          public AndOrCriteriaGroup build() {
79              return new AndOrCriteriaGroup(this);
80          }
81      }
82  }