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

和自甴很熟 提交于 2019-12-13 08:12:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44830387/how-to-create-predicate-booleanexpression-for-many-to-many-relations-in-querydsl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!