QueryDSL where relationship may be null

1k views Asked by At

So I'm trying to write a query dsl query that looks like this:

    JPAQuery bookQuery = new JPAQuery();
    QBook qBook = QBook.book;
    bookQuery.from(qBook);

    BooleanBuilder predicates = new BooleanBuilder();
    predicates
            .or(qBook.author.id.eq(personId))              
            .or(qBook.editor.id.eq(personId));

    bookQuery.where(predicates);

But the query is failing, because editor is sometimes null. How can I perform this query so it will return the results for the author id matching when editor is null?

This is a contrived example, but it's the technical problem I need to solve.

2

There are 2 answers

0
CorayThan On

Only way I could figure out how to do it in the same JPAQuery was with a subquery, like this:

JPAQuery bookQuery = new JPAQuery();
QBook qBook = QBook.book;
bookQuery.from(qBook);

BooleanBuilder predicates = new BooleanBuilder();
predicates
        .or(qBook.author.id.eq(personId))              
        .or(qBook.in(
            new JPASubQuery()
                .from(qBook)
                .where(qBook.editor.id.eq(personId)
                .list(qBook)));

bookQuery.where(predicates);
0
Timo Westkämper On

You can also use left joins for that

JPAQuery query = new JPAQUery();
QBook book = QBook.book;
query.from(book)
     .leftJoin(book.editor, editor)
     .where(book.author.id.eq(personId).or(editor.id.eq(personId)))
     .list(book);