如何在QueryDSL中为多对多关系创建Predicate BooleanExpression

时间:2017-06-29 16:19:02

标签: spring spring-data-jpa jpql predicate querydsl

如何使用Predicate BooleanExpression在多对多关系中完成内连接?

我有2个实体

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>();
}

基地回购

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

}

A

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

}

现在我想使用A Repo with Predicate查询。我需要形成一个谓词,我可以根据一些给定的B来加载A

我试过

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));

现在我能够形成JPQLQuery,但存储库需要一个谓词。如何从JPQLQuery中获取谓词?

或者,如何使用Predicate实现内连接?

1 个答案:

答案 0 :(得分:1)

我可以在这里给出答案的帮助下创建谓词

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

所以,我没有使用Pommm...Pommmmm!! Black 5000$ Black 5000$ Four Wheels man: 4 Black 5000$ Just Two man : 2 ,而是直接使用

JPQLQuery

这就像一个魅力。