【问题标题】:JPA CriteriaSepcification IN clauseJPA CriteriaSepcification IN 子句
【发布时间】:2020-08-06 08:09:46
【问题描述】:

我正在使用SpringBoot 2.2.6JPA,我需要使用标题中提到的IN 子句进行查询。我尝试过:

@Override
public Predicate toPredicate(Root<Distinta> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    
    List<Predicate> predicates = new ArrayList<>();
    .....
    .....
    for (DistintaCriteria criteria : list) {
        switch(criteria.getOperation()) {
        case TEST:
            Join<Entity, JoinEntity> join = root.join("joinEntity");
            predicates.add(join.<Integer>get("id").in(criteria.getValue()));
    }
}

其中criteria.getValue() 是一个Integer[] 数组,但它不起作用。你能帮帮我吗?

谢谢大家。

更新

如果我尝试使用与List&lt;String&gt; 相同的Query,它会起作用!使用 Integer 我有这个错误:

Unaware how to convert value [[2, 3, 4, 5] : java.util.ArrayList] to requested type [java.lang.Integer]

【问题讨论】:

    标签: spring-boot hibernate jpa jpa-criteria


    【解决方案1】:

    我已解决如下:

    Join<Entity, JoinEntity> join = root.join("joinEntity");
    Predicate in = join.get("id").in((List<Integer>)criteria.getValue());
    predicates.add(in);
    

    我不知道为什么 List&lt;String&gt; 我不需要投射。 希望有所帮助。

    【讨论】:

      【解决方案2】:

      对于 in 子句,我们需要始终传递一个列表。

      您需要使用 Java-8 将您的 Integer array 转换为 Integer list

      List&lt;Integer&gt; values = Arrays.asList(criteria.getValue())

      @Override
      public Predicate toPredicate(Root<Distinta> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
          
          List<Predicate> predicates = new ArrayList<>();
          .....
          .....
          for (DistintaCriteria criteria : list) {
          
              List<Integer> values = Arrays.asList(criteria.getValue());
          
              switch(criteria.getOperation()) {
              case TEST:
                  Join<Entity, JoinEntity> join = root.join("joinEntity");
                  predicates.add(join.<Integer>get("id").in(values));
          }
      }
      

      在 Eclipse 中,我们会像传递数组一样收到警告

      Type Integer[] of the last argument to a method in(Object...) doesn't exactly match the vararg parameter type. Cast to Object[] to confirm the non-varargs invocation, or pass individual arguments of type Object for a varargs invocation.

      【讨论】:

        猜你喜欢
        • 2018-06-08
        • 2017-07-20
        • 2013-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        相关资源
        最近更新 更多