Search code examples
spring-dataquerydsl

QueryDslPredicateExecutor: Predicate from two tables


I have this QueryDSL Predicate:

public class Predicates {
    public static Predicate get() {
        QUser qUser = QUser.user;
        QUserCompany qUserCompany = QUserCompany.userCompany;
        return qUser.id.eq(qUserCompany.userId);
    }
}

as you see, I need two tables to query users (User and UserCompany), so I get an error when I declare my repository like this:

public interface UserRepository QueryDslPredicateExecutor<User>
{
}

because internally UserCompany table is not included in the query (QueryDslPredicateExecutor<User>).

List<User> users = userRepository.findAll(Predicates.get());

How can I build a Predicate using two tables and use it with QueryDslPredicateExecutor?


Solution

  • Solved! I have mapped the one-to-many relationship in the User entity to UserCompany and then:

    public class Predicates {
        public static Predicate get() {
            QUser qUser = QUser.user;
            return qUser.userCompanies.any().userId.eq(qUser.id);
        }
    }