The labs on this site need JavaScript to run. The same content is written out below.
Learn › JPA › Queries
Dynamic queries: Specification and Querydsl
How do you add a search condition to where only when it is given?
Why it exists — If you join JPQL strings for each condition, a person has to get the positions of where and and and the spaces right, and the compiler cannot check those strings, so a query whose pieces were joined wrongly shows its error only when a request with that combination actually arrives. If you also put the values into the string, it becomes a path for SQL injection. The Criteria API of the JPA standard lets you pass the conditions as objects and has JPA attach where and and, and Specification in Spring Data JPA splits each condition into one named method and lets you combine them with and or or. Querydsl points to fields with Q classes generated from the entity, so it catches even a typo in a field name at compile time.
Where it's used today — You use it for search features where only the items that were entered become conditions, such as a member search on an admin screen or a product filter in a shop. In projects that use Spring Data JPA, it is common to add JpaSpecificationExecutor to the repository and combine conditions with Specification, or to use Querydsl together. For a query whose conditions are always the same, a query method or @Query is enough.
On a member search screen, the name and the age may be filled in or left blank. Only the conditions that were filled in must go into where, so the shape of the query differs from request to request. A query like this is called a dynamic query. Specification in Spring Data JPA, the Criteria API of JPA, and Querydsl assemble the conditions as objects instead of strings, and the tool attaches where and and.
Checked against real execution · The 24 combinations of Specification, the Criteria API, Querydsl, and joining strings by hand were run on Spring Boot 4.1.1, Spring Data JPA 4.1.1, Hibernate 7.4.5, H2, and Querydsl 5.1.0 and checked against the results
Concepts in this lab
- Dynamic query
- Why it exists — If there are several conditions that can be entered, you cannot prepare a query for every combination in advance (with 5 conditions, there are 32 combinations). A dynamic query picks only the conditions that came in at run time and assembles one query, so that a separate query is not kept for each combination.
- Where it's used today — It is needed for queries where the user chooses the sort order or the search fields on a list screen. In a project that uses MyBatis, only the conditions that came in are attached with the <if> and <where> tags in XML.
- A query built at run time from whichever conditions were supplied, so its shape changes with the input. It is needed when only the conditions that were entered must go into where, as on a search screen. If you build it by joining strings, mistakes happen: only where is left when there is no condition, an and ends up in the wrong place, or a space is missing. Such errors show up not at compile time but only when a request with that combination arrives. So you use Specification of Spring Data JPA, the Criteria API of JPA, or Querydsl, which assemble the conditions as objects. With any approach, values are bound as parameters instead of being put directly into the string.
- Specification
- Why it exists — When you write a dynamic query with the Criteria API, the code that builds the conditions stretches out long in a single method, and it is hard to reuse the same condition in another search. Specification lets you give each condition its own name and keep it separately, and pick and combine only the ones you need.
- Where it's used today — It is used to combine search conditions in a Spring Data JPA project without adding a library such as Querydsl. You build a list screen with findAll(spec, pageable), which also handles sorting and paging.
- This is an interface provided by Spring Data JPA that expresses how to build one search condition with the Criteria API as a single method (toPredicate). You usually write it as a lambda, as in (root, query, cb) -> cb.equal(root.get("name"), name), and combine them with and and or, as in Specification.where(a).and(b). If the repository also extends JpaSpecificationExecutor, you can pass a Specification to findAll(spec) and count(spec) to run it. If the lambda returns null instead of a condition, that condition is dropped and only the remaining conditions go into where, so it suits a dynamic query that drops conditions with no value. In Spring Data JPA 4.1.1, passing a null Specification itself to where or and throws an IllegalArgumentException.
- Criteria API
- Where it's used today — Use it when you must build a dynamic query without adding a library such as Querydsl. Because it is a JPA standard, the same code runs even if you switch to a JPA implementation other than Hibernate.
- An API in the JPA standard that builds a query as Java objects instead of a string. You create condition objects (Predicate) with a CriteriaBuilder, collect them in a list, and pass them to where, and then where and and are created to match the number of conditions. With 0 conditions, no where clause is created. You can use it without a separate library, but the code is long and it is hard to read what query it is. If you write a property name as a string, a wrong name still compiles and throws an exception while running.
- Querydsl
- Why it exists — A query built with the Criteria API has long code, and it is hard to read at a glance what SQL will be sent. Querydsl lets you chain select, from, and where as methods in an order similar to SQL, so that the shape of the query can be read even though you write it in Java code.
- Where it's used today — It is used not only for assembling conditions but also when writing queries whose JPQL string would become long, such as joins, group by aggregation, and queries that receive the result directly as a DTO, in Java code.
- A library that lets you build queries in Java code. It generates Q classes (for example QMember) in advance by looking at your entity classes, and you write the properties and conditions as methods, as in m.name.eq("Alice"). A wrong property name or type is a compile error, so you can find the mistake before running. If you pass several conditions to where, they are combined with and and null conditions are skipped, so you can write a dynamic query briefly by making condition methods that return null when there is no value. You can also stack conditions one at a time in a BooleanBuilder. It is not a JPA standard, so you have to add the dependency and the build setting that generates the Q classes separately.
- SQL injection
- An attack in which user input is interpreted as part of a SQL statement, so a query that the attacker intended is executed. It happens when SQL is built by concatenating input values as strings. Parameterized queries with bind variables (PreparedStatement) separate the SQL structure from the values, so input is always treated only as a value, which prevents the attack.
Try these
- Default settings — The name condition, which returned null, is dropped, and only the age condition goes into where.
- With no condition at all — No condition remains, so no where clause is created at all and everything is returned.
- Assemble two conditions with the Criteria API — When you pass two condition objects to where, JPA combines them with and. The cb that the lambda of Specification receives is also the CriteriaBuilder of this API.
- Assemble with Querydsl — where skips the null condition, and only the name condition remains. The SQL sent is the same as with Specification and the Criteria API.
- When quotes are mixed into the name field — The value is bound separately to the ? placeholder, so it is just a strange name, and 0 members are found.
- Joining strings by hand — and comes right after where, which causes a syntax error. It is an error you miss if you test with both conditions given.
- When quotes are mixed into the joined string — The quote that was entered closes the string and creates an or condition, and all 7 members are found.
Running with the default settings
- Search conditions: the name is null because it was not entered, and the age is 20. Only the conditions that are not null must go into the where of the query.
- Line 1, nameEq(name): an example method we made. It does not create the condition right away. It returns a lambda (a Specification) that is called when the query is built. This lambda is written to return null instead of a condition if name is null, and cb.equal(root.get("name"), name) otherwise. Specification.where is a method provided by Spring Data JPA, and it takes the Specification it receives as the starting point.
- Line 2, .and(ageGoe(age)): ageGoe is also an example method we made, and it returns a lambda of the same shape. and is a method provided by Spring Data JPA, and it returns a new Specification that combines two Specifications with and. No SQL has been built yet.
- Line 3, memberRepository.findAll(spec): a method provided by JpaSpecificationExecutor. Spring Data JPA creates a CriteriaQuery and calls the two lambdas. nameEq returns null, and ageGoe returns the condition age >= ?. A condition that returned null is dropped, and only the one remaining condition goes into where.
- One SELECT is sent to the DB. The condition of the SQL is "where age >= ?". The values bound to the ? placeholders are 20. Members found: 5 out of 7.
Result of this run
- The query assembled with Specification ran with 1 condition left, and members found: 5. All six combinations of the name and age fields run without a syntax error.
- You do not write where, and, or spaces yourself. If the lambda returns null instead of a condition when there is no value, Spring Data JPA drops that condition and combines only the remaining ones with and. When conditions increase, you create one more method like nameEq and chain it with and.
- Let the lambda return null instead of a condition. Do not pass null itself as the Specification. In Spring Data JPA 4.1.1, Specification.where(null) and and(null) throw an IllegalArgumentException.
Code
// Only the necessary parts are kept (class declaration, memberRepository field, the example Member entity we made, and imports omitted)
// MemberRepository is an example repository we made. JpaRepository, JpaSpecificationExecutor, and Specification are provided by Spring Data JPA
interface MemberRepository extends JpaRepository<Member, Long>, JpaSpecificationExecutor<Member> { }
// nameEq and ageGoe are example methods we made. When there is no value, they return null instead of a condition
static Specification<Member> nameEq(String name) {
return (root, query, cb) -> name == null ? null : cb.equal(root.get("name"), name);
}
static Specification<Member> ageGoe(Integer age) {
return (root, query, cb) -> age == null ? null : cb.greaterThanOrEqualTo(root.get("age"), age);
}
List<Member> search(String name, Integer age) {
Specification<Member> spec = Specification.where(nameEq(name))
.and(ageGoe(age));
return memberRepository.findAll(spec);
}
search(null, 20); // the name is not entered, the age is 20 or older
Assumptions of this model
All 24 combinations of the four methods, the three name fields, and the two age fields were run for real, with code that has the same structure as the screen, on Spring Boot 4.1.1 (auto-configuration), Spring Data JPA 4.1.1, Hibernate 7.4.5, an H2 database, and Querydsl 5.1.0 (jakarta), and the screen was checked against whether it succeeded, the kind of exception, the error position and the failing token, the where of the SQL sent to the DB, the bound values, and the number of members found. For the Q class (QMember), the one that querydsl-apt generated by looking at the Member entity at compile time was used. With the same conditions, the SQL sent by Specification, the Criteria API, and Querydsl was identical down to the letters. The explanations that Spring Data JPA drops a condition that returned null and combines only the remaining conditions with and, and that the where of Querydsl skips null conditions, are based on the SQL sent in this way. We also confirmed by running that Specification.where(null) and and(null) throw an IllegalArgumentException, that with the Criteria API a property name that does not exist in m.get compiles and a PathElementException occurs while running, and that even with strings, collecting the conditions in a list, joining them with and, and binding the values makes all six combinations run correctly. The position of the syntax error and the failing token are based on the message produced by Hibernate 7.4.5, and they may come out differently on other versions or other JPA implementations. The explanation that, for "where and", Hibernate reads and as a name and moves on is an interpretation based on the execution result that the error occurred not at and but at the token after it. The SQL where on the screen has the table aliases removed and is shortened to be easy to read. In a real service there are many more conditions, and or, like, and sorting are mixed in, so the mistakes of the string method are easier to make than here.
Previous lab: Spring Data JPA · Next lab: Connection pool and OSIV