Search code examples
javadatequerydsl

QueryDSL - Avoid NPE when date is null


I have a query that has the following where clause:

.where(table.lastupdated.after(date))

Where the date is just a Timestamp. However, date can be null. If I pass a null date I will get an NPE. How can I avoid this?

In the case where the date is null, I want the query to execute as if the where clause above does not exist. In other words, to query the entire table regardless of the lastupdated field.

The query is rather large, I'd rather not create two queries (one with date check and the other without). I'm looking for something more succint.


Solution

  • You can first build your query and then execute it.

    if (date != null) {
        query = query.where(table.lastUpdated.after(date));
    }
    
    repository.findOne(query);
    

    No need to make 2 different queries.