Home > Software design >  Jooq 3.14.1 fetchLazy with postgres fetching all rows
Jooq 3.14.1 fetchLazy with postgres fetching all rows

Time:03-14

I am new to jooq and trying to use fetchLazy with postgres.

I modified the data access code as mentioned in this article like below

// BookService.java
public List<Book> getBooks(){
    final List<Book> books = new ArrayList<>();
    ResultQuery<BookRecord> resQuery = context.selectFrom(Tables.BOOK).fetchSize(2);
    transactionRunner.readOnlyTransaction(() -> {
        try(final Cursor<BookRecord> bookRecords = resQuery.fetchLazy()) {
            while (bookRecords.hasNext()) {
                List<Book> into = bookRecords.fetch().into(Book.class);
                System.out.println("Num Records: "   into.size());
                books.addAll(into);
            }
        }
    });
    return books;
}

My transaction code looks like below -

public class TransactionalRunner {
  private final PlatformTransactionManager manager;

  public void readOnlyTransaction(Runnable fn) {
    var template = new TransactionTemplate(manager);
    template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    template.execute(
        transactionStatus -> {
          fn.run();
          return null;
        });
  }
}

For testing, I have added 4 records in database. I am getting all 4 records in the single fetch even though fetchSize is set to 2.

Num Records: 4

All the modified code is placed in github.

Can someone let me know what is going wrong?

  • Jooq Version 3.14.1

Postgres is running as docker

docker run --name tuk-temp -p 58704:5432 -e POSTGRES_PASSWORD=postgres postgres

CodePudding user response:

Size needs to be specified in fetchNext.

// BookService.java
public List<Book> getBooks(){
    final List<Book> books = new ArrayList<>();
    ResultQuery<BookRecord> resQuery = context.selectFrom(Tables.BOOK).fetchSize(2);
    transactionRunner.readOnlyTransaction(() -> {
        try(final Cursor<BookRecord> bookRecords = resQuery.fetchLazy()) {
            while (bookRecords.hasNext()) {
                List<Book> into = bookRecords.fetchNext(2).into(Book.class);
                System.out.println("Num Records: "   into.size());
                books.addAll(into);
            }
        }
    });
    return books;
}
  • Related