Example Queries

This page provides some examples of using QueryDSL, as passed into the various findXxx() methods of QueryDslRepository.

The examples use the SimpleApp's SimpleObject and SimpleObjectRepository.

Subclass QueryDslRepository

First, note that SimpleObjectRepository inherits from and QueryDslRepository, parameterized by both the entity (SimpleObject) and its corresponding query class (QSimpleObject):

@Service
public class SimpleObjectRepository
    extends QueryDslRepository<SimpleObject, QSimpleObject> {

    @Override
    protected Function<QSimpleObject, List<OrderSpecifier<? extends Comparable>>> getDefaultOrders() {
        return entity -> Arrays.asList(entity.name.asc());
    }

}

As the example above shows, it’s usually good practice to override getDefaultOrders() method, which specifies the order to apply for the various finders that require an ordering, eg findUsingDefaultOrder().

The default implementation of getDefaultOrders() assumes that there is a unique "id" property. If that isn’t the case, then override the method to avoid potential runtime exceptions.

find & findUsingDefaultOrder

The QueryDslRepository#find() returns all matching entities, in the specified order:

public List<SimpleObject> findByNameContaining(final String name) {
    return find(
                entity -> entity.name.contains(name),
                entity -> entity.name.asc()
            );
}

To find matching instances use the default order, use QueryDslRepository#findUsingDefaultOrder():

public List<SimpleObject> findByNameContaining(final String name) {
    return findUsingDefaultOrder(
                entity -> entity.name.contains(name)
            );
}

This slightly more complicated example combine predicates with an AND:

    public List<SimpleObject> findByNameAndAmount(
            final String name,
            final int amount
    ) {
        return find(
                entity -> entity.name.eq(name)
                     .and(entity.amount.gt(ConstantImpl.create(amount))),
                entity -> entity.name.asc()
        );
    }

findFirst

The QueryDslRepository#findFirst() will instead return only a single instance:

public SimpleObject findFirstByName(final String name) {
    return findFirst(
            entity -> entity.name.eq(name),
            entity -> entity.name.asc()
    );
}

findFieldsDistinct & findUniqueFields

As well as returning entire entities, with QueryDSL we can also return custom projections. For example:

public List<String> findUniqueNames(final String name) {
    return findFieldsDistinct(
            entity -> entity.name,
            entity -> entity.name.eq(name),
            entity -> entity.name.asc()
    );
}

and in a similar manner:

public String findUniqueName(final String name) {
    return findUniqueFields(
            entity -> entity.name,
            entity -> entity.name.eq(name)
    ).orElse(null);
}