001package com.mybatisflex.spring.batch;
002
003import com.mybatisflex.core.BaseMapper;
004import org.mybatis.logging.Logger;
005import org.mybatis.logging.LoggerFactory;
006import org.springframework.batch.item.ItemWriter;
007import org.springframework.beans.factory.InitializingBean;
008import org.springframework.dao.EmptyResultDataAccessException;
009
010import java.util.List;
011import java.util.Objects;
012
013import static org.springframework.util.Assert.notNull;
014
015/**
016 * mybatisflex实现的数据写入工具
017 * @author zhangjian
018 * @param <T>
019 */
020public class MybatisFlexBatchItemWriter<T> implements ItemWriter<T>, InitializingBean {
021
022    private static final Logger LOGGER = LoggerFactory.getLogger(MybatisFlexBatchItemWriter.class);
023
024    private BaseMapper<T> mapper;
025
026    private boolean assertUpdates = true;
027
028    /**
029     * Public setter for the flag that determines whether an assertion is made that number of BatchResult objects returned
030     * is one and all items cause at least one row to be updated.
031     *
032     * @param assertUpdates the flag to set. Defaults to true;
033     */
034    public void setAssertUpdates(boolean assertUpdates) {
035        this.assertUpdates = assertUpdates;
036    }
037
038    /**
039     * mapper对象
040     * @param mapper
041     */
042    public void setMapper(BaseMapper<T> mapper) {
043        if (Objects.isNull(mapper))
044            throw new RuntimeException("MybatisFlex Mapper can't be null!");
045
046        this.mapper = mapper;
047    }
048
049    /**
050     * Check mandatory properties - there must be an SqlSession and a statementId.
051     */
052    @Override
053    public void afterPropertiesSet() {
054        notNull(mapper, "A Mapper is required.");
055    }
056
057    /**
058     * {@inheritDoc}
059     */
060    @Override
061    public void write(final List<? extends T> items) {
062
063        if (!items.isEmpty()) {
064            LOGGER.debug(() -> "Executing batch with " + items.size() + " items.");
065            int results = this.mapper.insertBatch((List<T>) items);
066
067            if (assertUpdates) {
068                if (results != items.size()) {
069                    throw new EmptyResultDataAccessException(
070                            "Items.size + " + items.size() + " doesn't match the number of updated rows: " + results, 1);
071
072                }
073            }
074        }
075    }
076}