Kotlin › Practice

Type-safe dynamic JPA queries with Kotlin JDSL 3 and Spring Data

Write type-safe dynamic JPA queries in Kotlin JDSL 3.x without QueryDSL kapt code generation, how JPQL rendering works, and when to choose other tools.

Type-safe dynamic JPA queries with Kotlin JDSL 3 and Spring Data

When building a book search API with optional filter parameters, I didn’t want fragile JPQL string concatenation or QueryDSL’s kapt code-generation overhead. I adopted Kotlin JDSL 3.x instead, which builds type-safe JPQL directly from Kotlin property references. This post walks through the setup, dynamic query implementation, internal rendering flow, and where other tools fit better.

Tested with Kotlin JDSL 3.3.1, Spring Boot 3.2.2, Kotlin 1.9.22, Hibernate ORM 6.4, and Java 17. Kotlin JDSL 3.0.0 shipped in October 2023 with completely new packages and APIs compared to 2.x.

Why Kotlin JDSL 3

In a semester book-rental project, I needed a search endpoint that combined optional filters for title, author name, minimum price, and publication date. Every filter was optional, so encoding every combination into Spring Data derived query method names was out of the question.

My first attempt stitched JPQL strings together with StringBuilder. As soon as I renamed an entity field, the project compiled cleanly and blew up at runtime with a query syntax error. QueryDSL was my next candidate, but generating Q-classes in Kotlin requires kapt. Kotlin’s official documentation already puts kapt in maintenance mode, and I didn’t want to slow down every build for code generation. Kotlin JDSL 3 solved both problems by using standard Kotlin property references like Book::title with zero generated sources.

ApproachType safetyCode generationKotlin ergonomicsBest fit
String JPQLNoneNoneFairFixed, simple queries
JPA Criteria APIHigh (with metamodel)Metamodel generationLow (verbose)Environments restricted to standard JPA APIs
QueryDSLHighQ-classes (kapt)FairMixed Java/Kotlin codebases with existing QueryDSL
Kotlin JDSL 3.xHighNoneHighKotlin-only projects needing dynamic queries

Project setup

To integrate Kotlin JDSL 3 with Spring Data JPA, add three dependencies: the DSL module, the JPQL renderer, and the Spring Data JPA support module. Your JPA entities should be plain class definitions configured with the all-open and no-arg compiler plugins, as covered in my post on Kotlin JPA entity design.

1
2
3
4
5
6
7
// build.gradle.kts (dependencies excerpt)
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("com.linecorp.kotlin-jdsl:jpql-dsl:3.3.1")
    implementation("com.linecorp.kotlin-jdsl:jpql-render:3.3.1")
    implementation("com.linecorp.kotlin-jdsl:spring-data-jpa-support:3.3.1")
}

Auto-configuration in spring-data-jpa-support registers the JpqlRenderContext bean automatically. Once your repository interface extends KotlinJdslJpqlExecutor, Spring Data wires the executor fragment implementation for you.

Building a dynamic search query

The cleanest feature for dynamic filters is that whereAnd() skips null predicates automatically. You turn each optional field into a predicate with ?.let, and any missing filter simply evaluates to null and drops out of the WHERE clause.

1
2
3
4
5
6
7
// src/main/kotlin/com/example/library/book/BookRepository.kt
package com.example.library.book

import com.linecorp.kotlinjdsl.support.spring.data.jpa.repository.KotlinJdslJpqlExecutor
import org.springframework.data.jpa.repository.JpaRepository

interface BookRepository : JpaRepository<Book, Long>, KotlinJdslJpqlExecutor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/main/kotlin/com/example/library/book/BookSearchService.kt
package com.example.library.book

import java.time.LocalDate
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

data class BookSearchCondition(
    val title: String? = null,
    val authorName: String? = null,
    val minPrice: Int? = null,
    val publishedFrom: LocalDate? = null,
)

@Service
@Transactional(readOnly = true)
class BookSearchService(
    private val bookRepository: BookRepository,
) {
    fun search(condition: BookSearchCondition, pageable: Pageable): Page<Book> =
        bookRepository.findPage(pageable) {
            select(
                entity(Book::class),
            ).from(
                entity(Book::class),
            ).whereAnd(
                condition.title?.takeIf { it.isNotBlank() }?.let { path(Book::title).like("%$it%") },
                condition.authorName?.let { path(Book::author)(Author::name).eq(it) },
                condition.minPrice?.let { path(Book::price).ge(it) },
                condition.publishedFrom?.let { path(Book::publishedAt).ge(it) },
            ).orderBy(
                path(Book::id).desc(),
            )
        }.map { requireNotNull(it) }
}

path(Book::author)(Author::name) traverses an association property—the equivalent of Book.author.name in JPQL. Because findPage() returns Page<T?>, I map each element through requireNotNull to keep the service’s return type non-null. Renaming any entity property now updates the query automatically during IDE refactoring, and passing a mismatched value type fails at compile time.

How JPQL rendering works under the hood

Kotlin JDSL 2.x built queries on top of the JPA Criteria API. Version 3.x replaced that layer completely: the DSL constructs an immutable query model and renders it into a JPQL string. That makes it work identically across any JPQL-compliant provider, whether Hibernate or EclipseLink.

flowchart TD
    A["Execute jpql DSL lambda"] --> B["Build immutable SelectQuery model"]
    B --> C["JpqlRenderer + RenderContext"]
    C --> D["JPQL string + parameter map"]
    D --> E["EntityManager.createQuery execution"]

Inside the lambda, calls like select, from, and whereAnd only assemble an immutable AST of query elements. JpqlRenderer then walks that tree using serializers registered in JpqlRenderContext, producing a parameterized query such as SELECT Book FROM Book AS Book WHERE Book.title LIKE :param1 alongside a map of named bind parameters. Because user input is always bound as named parameters rather than concatenated into the string, you avoid JPQL injection by default.

When you call findPage(), expect two queries in your SQL log: the data query plus a separate COUNT query for total elements. If you’re building infinite scroll and don’t need a total count, switch to findSlice() to skip the count query.

Caveats and when not to use it

Watch out for three common traps. First, if every predicate passed to whereAnd() is null, the clause resolves to 1 = 1 and scans the entire table—enforce at least one filter or a default date range on public search endpoints. Second, passing raw user input into like lets % and _ act as wildcards, so escape them explicitly and pass the escape parameter. Third, never combine findPage() with a collection fetch join: Hibernate logs firstResult/maxResults specified with collection fetch; applying in memory and loads the whole result set into JVM memory to paginate.

Kotlin JDSL isn’t the right tool for every query. For fixed, static lookups, a Spring Data derived method name or @Query annotation is shorter and easier to scan. For reporting queries that rely on window functions, CTEs, or database-specific functions, you’ve outgrown JPQL—use native SQL or a SQL-first library like jOOQ instead. And if your repository layer is shared across Java and Kotlin modules, QueryDSL is often easier for the whole team to maintain than a Kotlin-only DSL.

Checklist

  • Keep jpql-dsl, jpql-render, and spring-data-jpa-support pinned to the exact same version.
  • Convert optional filters with ?.let so absent conditions pass null to whereAnd().
  • Guard against empty search conditions so a blank request can’t trigger an unbounded full-table scan.
  • Escape % and _ in user-supplied like patterns and pass the matching escape character.
  • Keep window functions, CTEs, and vendor-specific SQL out of JDSL by routing them to native SQL or jOOQ.
This post is licensed under CC BY 4.0 by the author.