Home > Net >  OrderBy is not working with the In clause in Spring Data JPA
OrderBy is not working with the In clause in Spring Data JPA

Time:09-17

I have a method whose signature is like this.

public Page<Config> searchByCriteria(Map<String, String> params, Pageable pageable) {
    //prework
    if (zoneIds.equals(BLANK_STRING)) {
        return repository.findByUserIdAndNameContains(userId, name, pageable);
    }
    List<Integer> zones = Arrays
            .stream(zoneIds.split(","))
            .distinct()
            .map(Integer::parseInt)
            .collect(toList());
    return repository.findByUserIdEqualsAndNameContainsAndZonesInAndOrderByUpdatedOnDesc(userId, name, zones, pageable);
}

Here the second query is not working when the OrderBy clause is being appended. However, it works fine when I remove the OrderBy clause. eg: repository.findByUserIdEqualsAndNameContainsAndZonesIn(...) This works fine. Please suggest how can I use In and OrderBy clauses together.

here is the error which I am getting here in the stack trace.

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property inAnd found for type Integer! Traversed path: 

Config Object

    
@Entity 
public class Config extends AbstractEntity implements Serializable {{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer configId;


    private Integer userId;


    private String name;


    @Enumerated(EnumType.STRING)
    private State state;


    @ElementCollection
    @CollectionTable(name = "zone", joinColumns = @JoinColumn(name = "config_id"))
    @Column(name = "zone_id")
    private Set<Integer> zones = new HashSet<>();

    
    @Valid
    @ElementCollection
    @CollectionTable(name = "param", joinColumns = @JoinColumn(name = "config_id"))
    private Set<ApParam> apParams = new HashSet<>();

    
    private String remarks;
//getter
//setter

    }

CodePudding user response:

I think the problem is you are connecting the method query and the order by with And. This should work: repository.findByUserIdEqualsAndNameContainsAndZonesInOrderByUpdatedOnDesc(userId, name, zones, pageable);

Example: https://www.baeldung.com/spring-data-sorting#1-sorting-with-the-orderby-method-keyword

Document reference: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation

  • Related