springspring-batchlimitjparepository

Spring Batch, JpaRepository, RepositoryItemReader - How to limit the whole results set in the reader?


I am new to springBatch, and I am looking how to do a SQL query Limit. In the reading process, I am getting my ResultSet from a DB entry. I tried setMaxItemCount to limit the number of rows but it did not work. It still reading all DB entries.

public class PeopleReader extends RepositoryItemReader<Product>  {

        public People read () throws Exception {
            DataSourceContextHolder.set("people");
            return this.doRead();
        }

    public PeopleReader(final PeopleRepository peopleRepository) {
        DataSourceContextHolder.set("people");
        this.setRepository(peopleRepository);
        this.setMaxItemCount(100);
        this.setSort(new HashMap<>());
        this.setPageSize(100);
    } 
}
@Repository
public interface PeopleRepository extends JpaRepository<People, String> {
}

How to limit the whole resultset from the DataSource to 100 for example (as SQL query Limit 100)?


Solution

  • Finally, to limit the whole results sets in the reader, I added a counter

    public class PeopleReader extends RepositoryItemPeople<People>  {
    
        private int counter = 0;
    
        public People read () throws Exception {
            DataSourceContextHolder.set("people");
            if(counter<100)
            {   counter++;
                return this.doRead();
            }
            else
               return null;
        }
    }