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.Objects;
19  import java.util.Optional;
20  
21  import org.mybatis.dynamic.sql.exception.InvalidSqlException;
22  import org.mybatis.dynamic.sql.render.RenderedParameterInfo;
23  import org.mybatis.dynamic.sql.render.RenderingContext;
24  import org.mybatis.dynamic.sql.util.FragmentAndParameters;
25  import org.mybatis.dynamic.sql.util.Messages;
26  
27  /**
28   * BoundValues are added to rendered SQL as a parameter marker only.
29   *
30   * <p>BoundValues are most useful in the context of functions. For example, a column value could be
31   * incremented with an update statement like this:
32   * <code>
33   *         UpdateStatementProvider updateStatement = update(person)
34   *                 .set(age).equalTo(add(age, value(1)))
35   *                 .where(id, isEqualTo(5))
36   *                 .build()
37   *                 .render(RenderingStrategies.MYBATIS3);
38   * </code>
39   *
40   * @param <T> the column type
41   * @since 1.5.1
42   */
43  public class BoundValue<T> implements BindableColumn<T> {
44      private final T value;
45  
46      private BoundValue(T value) {
47          this.value = Objects.requireNonNull(value);
48      }
49  
50      @Override
51      public FragmentAndParameters render(RenderingContext renderingContext) {
52          RenderedParameterInfo rpi = renderingContext.calculateParameterInfo(this);
53          return FragmentAndParameters.withFragment(rpi.renderedPlaceHolder())
54                  .withParameter(rpi.parameterMapKey(), value)
55                  .build();
56      }
57  
58      @Override
59      public Optional<String> alias() {
60          return Optional.empty();
61      }
62  
63      @Override
64      public BoundValue<T> as(String alias) {
65          throw new InvalidSqlException(Messages.getString("ERROR.38")); //$NON-NLS-1$
66      }
67  
68      public static <T> BoundValue<T> of(T value) {
69          return new BoundValue<>(value);
70      }
71  }