CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Handle Null Values in QueryDSL Projections

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

Handle Null Values in QueryDSL Projections

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 ยท 3 min read ยท 0 Comments
Share: in X

QueryDSL is a powerful library for building type-safe SQL-like queries in Java, especially in conjunction with JPA (Java Persistence API). When working with projections, it’s common to encounter situations where some fields might be null in the database, and handling these cases effectively is crucial for obtaining accurate query results.

There is another post on spring data JPA projection if you want to understand different type of projection in Spring Boot.

In this blog post, we’ll discuss a common issue related to null values in QueryDSL projections and provide a solution to handle such scenarios.

Table of Contents

The Problem
The Solution
Real-world Example
Conclusion

The Problem

Consider a scenario where we are using QueryDSL to perform a projection on entities, and we want to concatenate multiple fields, such as names, titles, etc. If any part of the concatenation is null, the result may end up being null as well, leading to unexpected behavior.

Following is a simplified example of the problem:

Expressions.cases().when(entity.field1.isNotNull())
    .then(entity.field1.concat(" ").concat(entity.field2))
    .otherwise("Default Value")

In this example, if field1 is null, the whole concatenation becomes null, even though field2 might contain a value.

The Solution

To handle null values effectively during concatenation, we can use the coalesce function along with Expressions.cases(). Let’s look at an example:

Expressions.cases().when(entity.field1.isNotNull())
    .then(entity.field1.concat(" "))
    .otherwise("").concat(Expressions.cases().when(entity.field2.isNotNull())
        .then(entity.field2)
        .otherwise(""))

In this updated example, if field1 is null, an empty string is used for the first part of the concatenation, and the field2 value is appended only if it is not null.

Real-world Example

Let’s consider a real-world scenario where we have a User entity with createdBy and modifiedBy relationships to other User entities, and we want to project a DTO (UserProjection) with concatenated names (createdByName and modifiedByName). The code might look like this:

created.title.coalesce("").concat(" ")
	.concat(created.firstName.coalesce("")
.concat(" "))
	.concat(created.middleName.coalesce("")
.concat(" "))
	.concat(created.lastName.coalesce(""))

In this example, the coalesce function is used to handle null values for the titles and names, ensuring that the projection doesn’t result in unexpected null values.

The complete code look like below:

JPAQuery<UserProjection> query = new JPAQuery<>(entityManager);
		 
QUser user = QUser.user;
QUser created = new QUser("created"); // Alias for created user
QUser modified = new QUser("modified"); // Alias for modified user
		 	 
List<UserProjection> content = query
	    .select(new QUserProjection(
	        user.id,
                ...
		user.email,

		created.title.coalesce("").concat(" ")
	            .concat(created.firstName.coalesce("")
                .concat(" "))
	            .concat(created.middleName.coalesce("")
                .concat(" "))
	            .concat(created.lastName.coalesce(""))
		))
		.from(user)
		.leftJoin(created).on(user.createdBy.eq(created.id))
		.leftJoin(modified).on(user.modifiedBy.eq(modified.id))
		.fetch();

Important

If we don’t define the aliases to the join operations then the incorrect data will come. This is because the same user alias for all three join operations will lead to confusion and incorrect retrieval of data

Conclusion

To handle null values in QueryDSL projections is a common challenge, but with the use of coalesce and Expressions.cases(), we can build robust queries that handle null cases gracefully. It’s essential to be aware of these techniques to ensure our queries produce the expected results, especially when dealing with complex projections involving concatenations.

I hope this blog post helps you address null value issues in your QueryDSL projects. If you have any additional tips or experiences to share, feel free to leave a comment!

Related Posts:

  • Spring Data JPA Projection
  • Most Frequently Asked Spring Boot Interview…
  • How to Use QueryDSL in Spring Boot 3: A Complete…
  • Master Spring Data JPA Method Queries: The Ultimate…
  • Spring Data REST example.
  • Pagination and Sorting in Spring Boot
Tags:javajpaquerydsl
Was this article helpful?
โ† Previous ArticleSpring Data JPA Projection
Next Article โ†’Auto Generate Created and Modified Date Time in Spring Boot

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
ยฉ 2026 CoderSathi. All rights reserved. Privacy Policy ยท Sitemap