Predicates

Kotlin JDSL has the Predicate interface to represent a conditional expression in JPQL.

Logical operators

Use the following functions to build logical operations:

  • AND (and)

  • OR (or)

  • NOT (not)

If all Predicate passed to and() and or() is null or empty, and() will be interpreted as 1 = 1 and or() will be interpreted as 0 = 1. So be careful when creating a dynamic query.

path(Employee::name).eq("Employee01").and(path(Employee::nickname).eq("E01"))
and(path(Employee::name).eq("Employee01"), path(Employee::nickname).eq("E01"))

path(Employee::name).eq("Employee01").or(path(Employee::nickname).eq("E01"))
or(path(Employee::name).eq("Employee01"), path(Employee::nickname).eq("E01"))

not(path(Employee::name).eq("Employee01"))

Parentheses

Call logical operators using a normal function instead of an extension function to add parentheses for the order of operations. As for extension functions, Kotlin JDSL cannot add parentheses because the order is ambiguous.

// normal function: (Employee.name = 'Employee01' AND Employee.nickname = 'E01') or (Employee.name = 'Employee02' AND Employee.nickname = 'E02')
or(
    path(Employee::name).eq("Employee01").and(path(Employee::nickname).eq("E01")),
    path(Employee::name).eq("Employee02").and(path(Employee::nickname).eq("E02")),
)

// extension function: Employee.name = 'Employee01' AND Employee.nickname = 'E01' or Employee.name = 'Employee02' AND Employee.nickname = 'E02'
path(Employee::name).eq("Employee01").and(path(Employee::nickname).eq("E01")).or(path(Employee::name).eq("Employee02").and(path(Employee::nickname).eq("E02")))

Comparison operators

Use the following functions to build comparison operators:

  • = (equal or eq)

  • <> (notEqual or ne)

  • > (greaterThan or gt)

  • >= (greaterThanOrEqualTo or ge)

  • < (lessThan or lt)

  • <= (lessThanOrEqualTo or le)

All or Any

Append all and any at the end of the function name to use All and Any operators on subqueries.

Null

Use isNull() and isNotNull() to build null comparison operations.

Like

Use like() and notLike() to build like comparison operations.

Between

Use between() and notBetween() to build between comparison operations.

In

Use in() and notIn() to build in comparison operations.

Exists

Use exists() and notExists() to build exists operations.

Empty

Use isEmpty() and isNotEmpty() to build empty operations.

Database function

Call function() with KClass<Boolean> to create predefined database functions and user-defined database functions.

You may need to register information about the function you want to use with the JPA Provider. For example, if you are using Hibernate, you need to register a FunctionContributor.

Custom predicate

Call customPredicate() to build a custom predicate.

If you frequently use customPredicate(), you can create your own DSL.

Last updated