View Javadoc
1   /*
2    * Copyright 2010-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.spring.batch;
17  
18  import static org.springframework.util.Assert.isTrue;
19  import static org.springframework.util.Assert.notNull;
20  
21  import org.apache.ibatis.session.ExecutorType;
22  import org.apache.ibatis.session.SqlSession;
23  import org.apache.ibatis.session.SqlSessionFactory;
24  import org.mybatis.logging.Logger;
25  import org.mybatis.logging.LoggerFactory;
26  import org.mybatis.spring.SqlSessionTemplate;
27  import org.springframework.batch.infrastructure.item.Chunk;
28  import org.springframework.batch.infrastructure.item.ItemWriter;
29  import org.springframework.beans.factory.InitializingBean;
30  import org.springframework.core.convert.converter.Converter;
31  import org.springframework.dao.EmptyResultDataAccessException;
32  import org.springframework.dao.InvalidDataAccessResourceUsageException;
33  
34  /**
35   * {@code ItemWriter} that uses the batching features from {@code SqlSessionTemplate} to execute a batch of statements
36   * for all items provided.
37   * <p>
38   * Provided to facilitate the migration from Spring-Batch iBATIS 2 writers to MyBatis 3.
39   * <p>
40   * The user must provide a MyBatis statement id that points to the SQL statement defined in the MyBatis.
41   * <p>
42   * It is expected that {@link #write(Chunk)} is called inside a transaction. If it is not each statement call will be
43   * autocommitted and flushStatements will return no results.
44   * <p>
45   * The writer is thread safe after its properties are set (normal singleton behavior), so it can be used to write in
46   * multiple concurrent transactions.
47   *
48   * @author Eduardo Macarron
49   *
50   * @param <T>
51   *          the generic type
52   *
53   * @since 1.1.0
54   */
55  public class MyBatisBatchItemWriter<T> implements ItemWriter<T>, InitializingBean {
56  
57    private static final Logger LOGGER = LoggerFactory.getLogger(MyBatisBatchItemWriter.class);
58  
59    private SqlSessionTemplate sqlSessionTemplate;
60  
61    private String statementId;
62  
63    private boolean assertUpdates = true;
64  
65    private Converter<T, ?> itemToParameterConverter = new PassThroughConverter<>();
66  
67    /**
68     * Public setter for the flag that determines whether an assertion is made that number of BatchResult objects returned
69     * is one and all items cause at least one row to be updated.
70     *
71     * @param assertUpdates
72     *          the flag to set. Defaults to true;
73     */
74    public void setAssertUpdates(boolean assertUpdates) {
75      this.assertUpdates = assertUpdates;
76    }
77  
78    /**
79     * Public setter for {@link SqlSessionFactory} for injection purposes.
80     *
81     * @param sqlSessionFactory
82     *          a factory object for the {@link SqlSession}.
83     */
84    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
85      if (sqlSessionTemplate == null) {
86        this.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
87      }
88    }
89  
90    /**
91     * Public setter for the {@link SqlSessionTemplate}.
92     *
93     * @param sqlSessionTemplate
94     *          a template object for use the {@link SqlSession} on the Spring managed transaction
95     */
96    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
97      this.sqlSessionTemplate = sqlSessionTemplate;
98    }
99  
100   /**
101    * Public setter for the statement id identifying the statement in the SqlMap configuration file.
102    *
103    * @param statementId
104    *          the id for the statement
105    */
106   public void setStatementId(String statementId) {
107     this.statementId = statementId;
108   }
109 
110   /**
111    * Public setter for a converter that converting item to parameter object.
112    * <p>
113    * By default implementation, an item does not convert.
114    *
115    * @param itemToParameterConverter
116    *          a converter that converting item to parameter object
117    *
118    * @since 2.0.0
119    */
120   public void setItemToParameterConverter(Converter<T, ?> itemToParameterConverter) {
121     this.itemToParameterConverter = itemToParameterConverter;
122   }
123 
124   /**
125    * Check mandatory properties - there must be an SqlSession and a statementId.
126    */
127   @Override
128   public void afterPropertiesSet() {
129     notNull(sqlSessionTemplate, "A SqlSessionFactory or a SqlSessionTemplate is required.");
130     isTrue(ExecutorType.BATCH == sqlSessionTemplate.getExecutorType(),
131         "SqlSessionTemplate's executor type must be BATCH");
132     notNull(statementId, "A statementId is required.");
133     notNull(itemToParameterConverter, "A itemToParameterConverter is required.");
134   }
135 
136   @Override
137   public void write(final Chunk<? extends T> items) {
138 
139     if (!items.isEmpty()) {
140       LOGGER.debug(() -> "Executing batch with " + items.size() + " items.");
141 
142       for (T item : items) {
143         sqlSessionTemplate.update(statementId, itemToParameterConverter.convert(item));
144       }
145 
146       var results = sqlSessionTemplate.flushStatements();
147 
148       if (assertUpdates) {
149         if (results.size() != 1) {
150           throw new InvalidDataAccessResourceUsageException("Batch execution returned invalid results. "
151               + "Expected 1 but number of BatchResult objects returned was " + results.size());
152         }
153 
154         var updateCounts = results.get(0).getUpdateCounts();
155 
156         for (var i = 0; i < updateCounts.length; i++) {
157           var value = updateCounts[i];
158           if (value == 0) {
159             throw new EmptyResultDataAccessException("Item " + i + " of " + updateCounts.length
160                 + " did not update any rows: [" + items.getItems().get(i) + "]", 1);
161           }
162         }
163       }
164     }
165   }
166 
167   private static class PassThroughConverter<T> implements Converter<T, T> {
168 
169     @Override
170     public T convert(T source) {
171       return source;
172     }
173 
174   }
175 
176 }