【问题标题】:How to create Predicate BooleanExpression for many to many relations in QueryDSL如何在 QueryDSL 中为多对多关系创建 Predicate BooleanExpression
【发布时间】:2017-12-03 11:09:42
【问题描述】:

如何使用 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。我需要形成一个谓词,我可以根据一些给定的 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??

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

【问题讨论】:

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


    【解决方案1】:

    我可以在此处给出的答案的帮助下创建一个谓词

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

    所以,我没有使用JPQLQuery,而是直接使用

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

    这就像一个魅力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2019-10-11
      • 2021-03-12
      • 2021-09-21
      • 2017-08-03
      • 1970-01-01
      • 2021-06-27
      相关资源
      最近更新 更多