001package com.mybatisflex.spring.batch;
002
003import com.mybatisflex.core.BaseMapper;
004import com.mybatisflex.core.paginate.Page;
005import com.mybatisflex.core.query.QueryWrapper;
006import org.mybatis.spring.batch.MyBatisPagingItemReader;
007import org.springframework.batch.item.database.AbstractPagingItemReader;
008
009import java.util.concurrent.CopyOnWriteArrayList;
010
011import static org.springframework.util.Assert.notNull;
012import static org.springframework.util.ClassUtils.getShortName;
013
014/**
015 * mybatis-flex的分页读取器
016 * @author zhangjian
017 * @param <T> 实体类型
018 */
019public class MybatisFlexPagingItemReader<T> extends AbstractPagingItemReader<T>  {
020
021    /**
022     * 当前的mapper
023     */
024    private BaseMapper<T> mapper;
025
026    /**
027     * 拼接的入参列表
028     */
029    private QueryWrapper queryWrapper;
030
031    public MybatisFlexPagingItemReader() {
032        setName(getShortName(MyBatisPagingItemReader.class));
033    }
034
035    /**
036     * 当前的mapper对象
037     * @param mapper
038     */
039    public void setMapper(BaseMapper<T> mapper) {
040        this.mapper = mapper;
041    }
042
043    /**
044     * 当前的参数对象
045     * @param queryWrapper
046     */
047    public void setQueryWrapper(QueryWrapper queryWrapper) {
048        this.queryWrapper = queryWrapper;
049    }
050
051    /**
052     * Check mandatory properties.
053     *
054     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
055     */
056    @Override
057    public void afterPropertiesSet() throws Exception {
058        super.afterPropertiesSet();
059        notNull(mapper, "mapper is required.");
060        notNull(queryWrapper, "querywrapper is required.");
061    }
062
063    @Override
064    protected void doReadPage() {
065        if (results == null) {
066            results = new CopyOnWriteArrayList<>();
067        } else {
068            results.clear();
069        }
070        Page<T> paginate = mapper.paginate(getPage() + 1, getPageSize(), queryWrapper);
071        results.addAll(paginate.getRecords());
072    }
073
074    @Override
075    protected void doJumpToPage(int itemIndex) {
076        if (results == null) {
077            results = new CopyOnWriteArrayList<>();
078        } else {
079            results.clear();
080        }
081        Page<T> paginate = mapper.paginate(itemIndex + 1, getPageSize(), queryWrapper);
082        results.addAll(paginate.getRecords());
083    }
084}