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.util.spring;
17  
18  import java.util.List;
19  
20  import org.springframework.jdbc.core.namedparam.SqlParameterSource;
21  import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
22  
23  /**
24   * Utility class for converting a list of rows to an array or SqlParameterSources.
25   *
26   * <p>This class is necessary due to the way that the library generates bindings for batch insert
27   * statements. The bindings will be of the form <code>:row.propertyName</code>. The <code>createBatch</code> method
28   * in this class will wrap all input rows in a class - RowHolder - with a single property named "row".
29   * This will allow the generated bindings to function properly with a Spring batch insert.
30   */
31  public class BatchInsertUtility {
32      private BatchInsertUtility() {}
33  
34      public static <T> SqlParameterSource[] createBatch(List<T> rows) {
35          List<RowHolder<T>> tt = rows.stream()
36                  .map(RowHolder::new)
37                  .toList();
38  
39          return SqlParameterSourceUtils.createBatch(tt);
40      }
41  
42      public record RowHolder<T>(T row) {}
43  }