View Javadoc
1   /*
2    * Copyright 2010-2024 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.item.Chunk;
28  import org.springframework.batch.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   * @since 1.1.0
51   */
52  public class MyBatisBatchItemWriter<T> implements ItemWriter<T>, InitializingBean {
53  
54    private static final Logger LOGGER = LoggerFactory.getLogger(MyBatisBatchItemWriter.class);
55  
56    private SqlSessionTemplate sqlSessionTemplate;
57  
58    private String statementId;
59  
60    private boolean assertUpdates = true;
61  
62    private Converter<T, ?> itemToParameterConverter = new PassThroughConverter<>();
63  
64    /**
65     * Public setter for the flag that determines whether an assertion is made that number of BatchResult objects returned
66     * is one and all items cause at least one row to be updated.
67     *
68     * @param assertUpdates
69     *          the flag to set. Defaults to true;
70     */
71    public void setAssertUpdates(boolean assertUpdates) {
72      this.assertUpdates = assertUpdates;
73    }
74  
75    /**
76     * Public setter for {@link SqlSessionFactory} for injection purposes.
77     *
78     * @param sqlSessionFactory
79     *          a factory object for the {@link SqlSession}.
80     */
81    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
82      if (sqlSessionTemplate == null) {
83        this.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
84      }
85    }
86  
87    /**
88     * Public setter for the {@link SqlSessionTemplate}.
89     *
90     * @param sqlSessionTemplate
91     *          a template object for use the {@link SqlSession} on the Spring managed transaction
92     */
93    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
94      this.sqlSessionTemplate = sqlSessionTemplate;
95    }
96  
97    /**
98     * Public setter for the statement id identifying the statement in the SqlMap configuration file.
99     *
100    * @param statementId
101    *          the id for the statement
102    */
103   public void setStatementId(String statementId) {
104     this.statementId = statementId;
105   }
106 
107   /**
108    * Public setter for a converter that converting item to parameter object.
109    * <p>
110    * By default implementation, an item does not convert.
111    *
112    * @param itemToParameterConverter
113    *          a converter that converting item to parameter object
114    *
115    * @since 2.0.0
116    */
117   public void setItemToParameterConverter(Converter<T, ?> itemToParameterConverter) {
118     this.itemToParameterConverter = itemToParameterConverter;
119   }
120 
121   /**
122    * Check mandatory properties - there must be an SqlSession and a statementId.
123    */
124   @Override
125   public void afterPropertiesSet() {
126     notNull(sqlSessionTemplate, "A SqlSessionFactory or a SqlSessionTemplate is required.");
127     isTrue(ExecutorType.BATCH == sqlSessionTemplate.getExecutorType(),
128         "SqlSessionTemplate's executor type must be BATCH");
129     notNull(statementId, "A statementId is required.");
130     notNull(itemToParameterConverter, "A itemToParameterConverter is required.");
131   }
132 
133   @Override
134   public void write(final Chunk<? extends T> items) {
135 
136     if (!items.isEmpty()) {
137       LOGGER.debug(() -> "Executing batch with " + items.size() + " items.");
138 
139       for (T item : items) {
140         sqlSessionTemplate.update(statementId, itemToParameterConverter.convert(item));
141       }
142 
143       var results = sqlSessionTemplate.flushStatements();
144 
145       if (assertUpdates) {
146         if (results.size() != 1) {
147           throw new InvalidDataAccessResourceUsageException("Batch execution returned invalid results. "
148               + "Expected 1 but number of BatchResult objects returned was " + results.size());
149         }
150 
151         var updateCounts = results.get(0).getUpdateCounts();
152 
153         for (var i = 0; i < updateCounts.length; i++) {
154           var value = updateCounts[i];
155           if (value == 0) {
156             throw new EmptyResultDataAccessException("Item " + i + " of " + updateCounts.length
157                 + " did not update any rows: [" + items.getItems().get(i) + "]", 1);
158           }
159         }
160       }
161     }
162   }
163 
164   private static class PassThroughConverter<T> implements Converter<T, T> {
165 
166     @Override
167     public T convert(T source) {
168       return source;
169     }
170 
171   }
172 
173 }