1

I'm using SpringBoot 2.2.6 with JPA and I need to do query with IN clause as mentioned in Title. I have try with:

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

where criteria.getValue() is a Integer[] array but it doesn't work. Can you help me?

Thank you all.

UPDATE

If I try the same Query with List<String> it works! With Integer I had this error:

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

2 Answers2

1

I have solved as follows:

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

I don't know why with List<String> I don't need to cast. Hope helps.

CoderJammer
  • 599
  • 3
  • 8
  • 27
0

For in clause we need to pass a list always.

You need to convert your Integer array to Integer list using Java-8 like

List<Integer> 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));
    }
}

In eclipse, we will get the warning like if we pass an array

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.

SSK
  • 3,444
  • 6
  • 32
  • 59