8

When building a Predicate for the Entity Book, I would like to be able to left join on Category (ManyToMany) to add a AND Predicate on Category. I could simply achieve that if I have the JPAQuery instance :

if (catId != null) {
    jpaQuery.leftJoin(book.categories, category);
    jpaQuery.where(category.id.eq(catId).or(category.parentCategory.id.eq(catId)));
}

But when building Predicates I don't have yet the JPAQuery. So for the Predicate itself I could do :

booleanBuilder.and(category.id.eq(this.categoryId).or(category.parentCategory.id.eq(this.categoryId)));

But for the leftjoin how to proceed without the jpaQuery instance ?

leppie
  • 115,091
  • 17
  • 196
  • 297
Gauthier Peel
  • 1,438
  • 2
  • 17
  • 35
  • Any news regarding this one? I'm searching all over the place for an elegant solution of Joining Fetching without too much hassle... apparently Spring Data didn't think of use cases more complex then a single "select from where scenario" like shown on their basic examples... – Shay Elkayam Oct 02 '15 at 16:18
  • yep i found a solution : i coded an extension to spring-data interface : public interface TworkQueryDslRepository extends JpaRepository {) and added a prep method : JPAQuery createQuery(); and all executing methods with a new param typed JPAQuery : ex age findAll(JPAQuery jpaQuery, Predicate predicate, Pageable pageable); The goal is to have the Repo build and give me the JPAQuery so i could fetch. And Second phase, i can invoke an almost standard repo API but giving back the JPAQuery as first param in my case. I should make a PullResquest sometimes – Gauthier Peel Oct 15 '15 at 13:40
  • 1
    @GauthierPeel could you please elaborate on your solution, maybe in the form of an answer? It would be really helpful! – vargen_ Jun 07 '18 at 08:32
  • now in spring boot 2.6+ we have a feature for that. Even if it's a new feature and not all seems to works: https://stackoverflow.com/questions/71100160/fetching-and-paging-in-the-same-time-with-fetchablefluentquery-and-querydslpredi – Gauthier Peel Feb 17 '22 at 11:57

1 Answers1

1

You need the Query to declare the left join in Querydsl. If this is Spring Data related, they might come up with an API level solution.

book.categories.any() can be used instead of category, but it is serialized differently to JPQL, with a subquery instead of a join.

Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111
  • I'm trying to do this with Spring Data, thanks for the pointer that this is a problem with their API. – JBCP Jan 30 '15 at 04:20