How to Create Dynamic SQL Queries with Spring Boot

Transcript:

Hi friends! In this video, we will learn how to create dynamic SQL queries in Spring Boot with Spring Data JPA. I will use a project I created for this tutorial. You can find it on GitHub. It is a minimalistic bookshop application. The main entity class is ‘book,’ and we also have some auxiliary classes such as ‘category,’ ‘format,’ and ‘language.’

They also have the book repository and book service. In a real-world bookshelf application, users apply multiple filters to find the book they need. But we don't want to write separate queries for various combinations of these filters, right? This is where dynamic SQL queries come into play.

As the name suggests, they enable us to create SQL queries dynamically based on the user input. To build dynamic SQL queries with JPA, we can use the ‘Specification’ interface. It helps us build multiple predicates over the entity. These predicates can be combined to create queries with flexible WHERE clauses.

To make use of JPA specification, let's make our book repository interface extend the JPA specification executor. Here it is. Our book repository extends both the JPA repository and specification. Now, we need to create a specification class. Let's call it BookSpecification.

Here, we will create our filters, which are going to be custom specifications. Let’s start with the first method and define a filter for category. We need to return the specification for the Book entity class and call this method hasCategoryName. We pass a String for the category name and write a return statement. We return the root, which is our book, along with the query and criteriaBuilder. The criteriaBuilder is the most important part as it provides numerous methods.

We use equal() and pass the root (our book), get the category, and then extract its name. This will be our filter. The book entity has a category field, and the category has a name field. We extract the category and then the name we are looking for.

But in most cases, we need multiple filters, not just one. So let’s add additional filters: price, language, and format. We start with the price filter by creating a method called hasPriceLessThanOrEqualTo and passing the price parameter. The logic is similar—we retrieve the price field from the root and use the lessThanOrEqualTo method from the criteriaBuilder.

Currently, we are using strings to reference entity fields, such as category name or price. While this works, it's not the safest approach because changes in field names can break the specification. Instead, we could use the JPA static model generator for type-safe queries, but we will keep it simple in this demo.

Our filters are ready. Now, let's move to the book service and write a method for finding books based on the filters. Users may apply none, some, or all filters, but we only need one method to handle all these cases. We pass String categoryName, String languageName, String formatName, and a price parameter.

We create a specification called spec, initially set to null to handle cases where no filters are applied. Then, we check each parameter—if it's not null, we add it to the specification using the and method with the corresponding filter from BookSpecification.

Finally, we return the list of books using bookRepository.findAll(spec). If the specification is empty, we return all books. Otherwise, we return a filtered list based on the applied criteria.

Now, it’s time to test it. In the book service test, I have pre-written some tests to speed up the demo. The setup is simple: we first find books by category while passing null for other filters. We test different filter combinations, including category and format, category and language, and all four filters together. We also check that an empty list is returned when there are no matches and verify that all books are returned when no filters are applied.

Let’s run the tests. All tests have passed! And that’s how we create dynamic SQL queries in Spring Boot. Don't forget to like this video, subscribe to our channel, and see you next time!

Summary

This video demonstrates how to create dynamic SQL queries in Spring Boot using Spring Data JPA and the Specification interface for flexible filtering. Instead of writing multiple separate queries for different filter combinations, conditions like category, price, language, and format can be dynamically combined. Finally, tests confirm that the method correctly filters data or returns all books if no filters are applied.

About Catherine

Java developer passionate about Spring Boot. Writer. Developer Advocate at BellSoft

Social Media

Videos
card image
Feb 6, 2026
Backend Developer Roadmap 2026: What You Need to Know

Backend complexity keeps growing, and frameworks can't keep up. In 2026, knowing React or Django isn't enough. You need fundamentals that hold up when systems break, traffic spikes, or your architecture gets rewritten for the third time.I've been building production systems for 15 years. This roadmap covers three areas that separate people who know frameworks from people who can actually architect backend systems: data, architecture, and infrastructure. This is about how to think, not what tools to install.

Videos
card image
Jan 29, 2026
JDBC Connection Pools in Microservices. Why They Break Down (and What to Do Instead)

In this livestream, Catherine is joined by Rogerio Robetti, the founder of Open J Proxy, to discuss why traditional JDBC connection pools break down when teams migrate to microservices, and what is a more efficient and reliable approach to organizing database access with microservice architecture.

Further watching

Videos
card image
Feb 27, 2026
Spring Developer Roadmap 2026: What You Need to Know

Spring Boot is powerful. But knowing the framework isn’t the same as understanding backend engineering. In this video, I walk through the roadmap I believe matters for a Spring developer in 2026. We start with data. That means real SQL — CTEs, window functions, normalization trade-offs — and understanding what ACID and BASE actually imply for system guarantees. Spring Data JPA is useful, but you still need to know what happens underneath. Then architecture: microservices vs modular monolith, serverless, CQRS, and when HTTP, gRPC, Kafka, or WebSockets make sense. Not as buzzwords — but as design choices with trade-offs. Security and infrastructure follow: OWASP Top 10, AuthN vs AuthZ, encryption in transit and at rest, Docker, Kubernetes, Infrastructure as Code, and observability with Micrometer, OpenTelemetry, and Grafana. This roadmap isn’t about mastering every tool. It’s about knowing what affects reliability in production.

Videos
card image
Feb 18, 2026
Build Typed AI Agents in Java with Embabel

Most Java AI demos stop at prompt loops. That doesn't scale in production. In this video, we integrate Embabel into an existing Spring Boot application and build a multi-step, goal-driven agent for incident triage. Instead of manually orchestrating prompt → tool → prompt cycles, we define typed actions and let the agent plan across deterministic and LLM-powered steps. We parse structured input with Ollama, query MongoDB deterministically, classify risk using explicit thresholds, rank affected implants, generate a constrained root cause hypothesis, and produce a bounded containment plan. LLM handles reasoning. Java enforces rules. This is about controlled AI workflows on the JVM — not prompt glue code.

Videos
card image
Feb 12, 2026
Spring Data MongoDB: From Repositories to Aggregations

Spring Data MongoDB breaks down fast once CRUD meets production—real queries, actual data volumes, analytics. What looks simple at first quickly turns into unreadable repository methods, overfetching, and slow queries. In this video, I walk through building a production-style Spring Boot application using Spring Data MongoDB — starting with basic setup and repositories, then moving into indexing, projections, custom queries, and aggregation pipelines. You'll see how MongoDB's document model changes data design compared to SQL, when embedding helps, and when it becomes a liability. We cover where repository method naming stops scaling, how to use @Query safely, when to switch to MongoTemplate, and how to reduce payload size with projections and DTOs. Finally, we implement real MongoDB aggregations to calculate analytics directly in the database and test everything against a real MongoDB instance using Testcontainers. This is not another MongoDB overview. It's a practical guide to actually using Spring Data MongoDB in production without fighting the database.