Search code examples
springspring-data-jpajpqlpredicatequerydsl

How to create Predicate BooleanExpression for many to many relations in QueryDSL


How can inner join be done on Many to Many relations using Predicate BooleanExpression?

I have 2 entities

public class A {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

 @ManyToMany(fetch = FetchType.LAZY,
  cascade = { CascadeType.DETACH, CascadeType.MERGE, 
      CascadeType.REFRESH, CascadeType.PERSIST})
  @JoinTable(name = "a_b_maps",
      joinColumns = @JoinColumn(name = "a_id", nullable = 
          false,referencedColumnName = "id"),
      inverseJoinColumns = @JoinColumn(name = "b_id", nullable = false, 
        referencedColumnName = "id")
  )
  private Set<B> listOfB = new HashSet<B>();
}


public class B {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

 @ManyToMany(fetch = FetchType.LAZY,
  cascade = { CascadeType.DETACH, CascadeType.MERGE, 
      CascadeType.REFRESH, CascadeType.PERSIST})
  @JoinTable(name = "a_b_maps",
      joinColumns = @JoinColumn(name = "b_id", nullable = 
          false,referencedColumnName = "id"),
      inverseJoinColumns = @JoinColumn(name = "a_id", nullable = false, 
        referencedColumnName = "id")
  )
  private Set<A> listOfA = new HashSet<A>();
}

A Base repo

@NoRepositoryBean
public interface BaseRepository<E, I extends Serializable>
    extends JpaRepository<E, I> {

}

And a repository class for A

public interface Arepo extends BaseRepository<A, Integer>,
    QueryDslPredicateExecutor<A> {
    Page<A> findAll(Predicate predicate, Pageable pageRequest);

}

Now I want to use A Repo with Predicate query. I need to form a predicate where I can load A based on some given Bs

I tried

QA a = QA.a;
QB b = QB.b;
BooleanExpression boolQuery = null;
JPQLQuery<A> query = new JPAQuery<A>();
  query.from(a).innerJoin(a.listOfB, b)
    .where(b.id.in(someList));

Now I am able to form a JPQLQuery, but the repository expects a Predicate. How can I get Predicate from the JPQLQuery??

Or, how can the inner join be achieved using Predicate?


Solution

  • I am able to create a Predicate with the help of answer given here

    https://stackoverflow.com/a/23092294/1969412.

    SO, instead of using JPQLQuery, I am directly using

    a.listOfB.any()
          .id.in(list);
    

    This is working like a charm.