Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a jOOQ query that selects the ids and totals of orders over 100 for a customer, newest first, limited to 20, using generated classes. What does jOOQ check at compile time that JPQL strings do not?

With jOOQ's generated classes the query reads ctx.select(ORDERS.ID, ORDERS.TOTAL).from(ORDERS).where(ORDERS.CUSTOMER_ID.eq(customerId).and(ORDERS.TOTAL.gt(new BigDecimal("100")))).orderBy(ORDERS.CREATED_AT.desc()).limit(20).fetch(). Because the classes are generated from the real schema, a wrong table, a misspelled column or a type mismatch fails at compile time, while a JPQL string fails only when it is parsed. jOOQ also renders the SQL for each dialect, binds values as parameters, and needs its code generation to run against the migrated schema.

Why this question is asked

jOOQ is the most common SQL-first library in the Java world, and many teams use it next to JPA for reporting and complex reads. Interviewers ask for a concrete query because it shows whether we have actually used generated classes, and ask about compile-time checks because that is the main reason to adopt jOOQ at all. In this answer, we will recap what jOOQ generates, write the query step by step, compare what the compiler catches with a JPQL string, look at the SQL jOOQ renders, and finish with how to set up code generation from Flyway migrations.

1A Quick Recap of jOOQ's Generated Classes

jOOQ reads the database schema at build time and generates Java code for it. For a table called orders it generates a constant ORDERS of a class Orders, with one typed field per column: ORDERS.ID is a TableField<OrdersRecord, Long>, ORDERS.TOTAL is a field of BigDecimal, ORDERS.CREATED_AT a field of LocalDateTime or OffsetDateTime depending on the column type and settings. It also generates a record class, OrdersRecord, for rows of the table.

Queries are built with a DSLContext, usually called ctx, which Spring Boot's jOOQ starter provides as a bean wired to the application's DataSource and transactions.

Java
// Generated (simplified): com.example.db.tables.Orders
public class Orders extends TableImpl<OrdersRecord> {
public static final Orders ORDERS = new Orders();
public final TableField<OrdersRecord, Long> ID = ...;
public final TableField<OrdersRecord, Long> CUSTOMER_ID = ...;
public final TableField<OrdersRecord, BigDecimal> TOTAL = ...;
public final TableField<OrdersRecord, OffsetDateTime> CREATED_AT = ...;
}

2Writing the Query

The query follows the shape of SQL: select the fields, from the table, where a condition, order, limit. Each method returns a type that only offers the methods valid at that point, so the IDE guides us through a valid statement.

Java
import static com.example.db.Tables.ORDERS;
public List<OrderTotal> largeOrders(DSLContext ctx, long customerId) {
Result<Record2<Long, BigDecimal>> rows = ctx
.select(ORDERS.ID, ORDERS.TOTAL)
.from(ORDERS)
.where(ORDERS.CUSTOMER_ID.eq(customerId)
.and(ORDERS.TOTAL.gt(new BigDecimal("100"))))
.orderBy(ORDERS.CREATED_AT.desc(), ORDERS.ID.desc()) // id as a tiebreaker
.limit(20)
.fetch(); // up to 20 rows
return rows.map(r -> new OrderTotal(r.value1(), r.value2())); // e.g. OrderTotal[id=905, total=240.00]
}
record OrderTotal(Long id, BigDecimal total) {}

Notice the result type, Record2<Long, BigDecimal>. jOOQ knows we selected exactly two fields, of those types, so r.value1() is a Long without a cast. We also used new BigDecimal("100") rather than 100.0, because the column is a BigDecimal field and a decimal from a string keeps the exact value. fetchInto(OrderTotal.class) would map the rows to the record by position or name in one call as well. The extra ORDERS.ID.desc() is not required by the question, but it makes the order deterministic when two orders share a timestamp.

3What the Compiler Catches That JPQL Strings Do Not

A JPQL query is a string. The Java compiler cannot look inside it, so mistakes in it are found when Hibernate parses it: at startup for @Query and named queries, or only when the line runs for queries built with createQuery. jOOQ moves those mistakes into the type system.

Java
ORDERS.TOTL // compile error: cannot find symbol TOTL
ORDERS.TOTAL.gt("abc") // compile error: no gt(String) for Field<BigDecimal>
ORDERS.CUSTOMER_ID.eq("42") // compile error: Field<Long> expects a Long
select(ORDERS.ID).from(CUSTOMERS) // compiles, but the database rejects it: jOOQ checks types, not SQL semantics
// After a migration renames orders.total to orders.amount and code is regenerated:
// every use of ORDERS.TOTAL becomes a compile error, so schema drift is caught in the build
Where each mistake is caught
MistakeJPQL stringjOOQ generated classes
Misspelled column or fieldStartup or first runCompile time
Comparing a number with a stringParse time or database errorCompile time
Column renamed in the schemaRuntime, if the mapping is not updatedCompile time after codegen
Value spliced into the SQL textPossible with concatenationBound as parameters by default

The last point is the one teams value most. With JPQL, a renamed column breaks the entity mapping, which we must update by hand and which tests may or may not catch. With jOOQ, regenerating the classes after the migration makes every affected query fail to compile, a complete list of what to fix. Notice the limit too: jOOQ checks names and types, but a query that selects a column from a table not in the from clause still compiles, and the database rejects it at runtime.

4The SQL jOOQ Renders

jOOQ turns the query into SQL for the configured dialect. Values are not pasted into the SQL text; they become bind parameters, the question marks of a prepared statement, which protects against SQL injection without any effort on our side.

SQL
-- PostgreSQL dialect (formatting simplified)
select "orders"."id", "orders"."total"
from "orders"
where ("orders"."customer_id" = ? and "orders"."total" > ?) -- binds: 42, 100
order by "orders"."created_at" desc, "orders"."id" desc
limit ? -- binds: 20
-- Oracle 12c+ or SQL Server: the same Java code renders
-- ... fetch next ? rows only (or offset ... fetch, depending on dialect and version)

So limit(20) is written once in Java and rendered as LIMIT, FETCH FIRST or the equivalent for each database. The exact text varies with the dialect and jOOQ version, which is why we assert on results in tests rather than on SQL strings.

5Running Code Generation Against the Migrated Schema

The generated classes are only as good as the schema they were generated from. The reliable approach is to generate them from the same migrations that build production: start a throwaway database, apply the Flyway scripts, and run jOOQ's generator against it. Testcontainers makes the throwaway database easy, and there are build plugins that combine the steps.

Step throughGenerating jOOQ classes in the build
  1. Start PostgreSQL in a containersame major version as production
  2. Apply Flyway migrationsV1 ... V57, exactly as in production
  3. Run the jOOQ code generatorreads tables, columns and types
  4. Compile application coderenamed columns now fail here
  5. Run tests against the same containerresults checked on the real engine

5 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Can jOOQ generate classes without a running database?

Yes. jOOQ can parse DDL scripts directly, so it can read Flyway migration files without a database. That is faster, but it depends on jOOQ understanding every statement in the scripts; generating from a real database migrated by Flyway is the most faithful option.

Should we commit the generated classes to the repository?

Teams do both. Generating in the build keeps the repository clean and always in sync with the migrations. Committing them makes builds faster and changes visible in code review. The key rule is that they are never edited by hand.

Does jOOQ work with Spring transactions?

Yes. With the Spring Boot jOOQ starter, the DSLContext uses the application's DataSource through Spring's transaction-aware connection handling, so jOOQ queries inside a @Transactional method run on the same connection and transaction as JPA calls there.

7Conclusion

In this answer, we wrote a jOOQ query with generated classes that selects order ids and totals above 100 for a customer, newest first, limited to 20, with a typed Record2 result. We saw that generated classes turn misspelled columns, type mismatches and schema drift into compile errors that JPQL strings only reveal at parse time or runtime, that jOOQ renders the right SQL per dialect with values bound as parameters, and that code generation should run against a schema migrated by Flyway, for example in a Testcontainers database.

What to say in the interviewAbout 70 seconds aloud

Open with

With the generated ORDERS table class I would write ctx.select(ORDERS.ID, ORDERS.TOTAL).from(ORDERS).where(ORDERS.CUSTOMER_ID.eq(customerId).and(ORDERS.TOTAL.gt(new BigDecimal("100")))).orderBy(ORDERS.CREATED_AT.desc()).limit(20).fetch(). I would usually add ORDERS.ID.desc() as a tiebreaker so the order is stable, and map the Record2<Long, BigDecimal> rows into a small record.

Then, if they want more

The main difference from JPQL is what the compiler checks.

JPQL is a string, so a misspelled field or a type mismatch is only found when Hibernate parses it, at startup or at runtime. jOOQ's classes are generated from the real schema, so ORDERS.TOTL does not compile, comparing a Long column with a String does not compile, and when a migration renames a column and we regenerate, every affected query breaks in the build instead of in production. jOOQ checks names and types, though, not every SQL rule.

It also renders SQL for the configured dialect, so limit becomes LIMIT on PostgreSQL or FETCH FIRST where that is the syntax, and all values are bound as parameters, which prevents SQL injection. The one setup requirement is that code generation runs against the migrated schema, for example Flyway applied to a Testcontainers PostgreSQL during the build.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a jOOQ query that selects the ids and totals of orders over 100 for a customer...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/6821bdb9ba/