user3529850
user3529850

Reputation: 976

QuerydslJpaPredicateExecutor sort by field in subclass

1) Model used in the exmaple

@Getter
@Setter
@Entity
@Table(name = "car")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Car {
    
    private String color;
}


@Entity
@Getter
@Setter
public class Truck extends Car { 
    
    private Clutch clutch;
}

@Entity
@Getter
@Setter
public class Clutch { 

    private String manufacturerCode;
}

and the repository classes:

public interface CarRepository extends JpaRepository<Car, Integer>,
        QuerydslPredicateExecutor<Car> {}
        
public interface TruckRepository extends JpaRepository<Truck, Integer>,
        QuerydslPredicateExecutor<Truck> {}
        
public interface PassengerCarRepository extends JpaRepository<PassengerCar, Integer>,
        QuerydslPredicateExecutor<PassengerCar> {}
    

2. The problem

In the GUI there is a call for all "cars" so the call is from "CarRepository":

carRepository.findAll(predicate, pageable)

I can create my own implementation of "pageable" and put "sort" in there like this:

@Getter
public class OwnPageable extends AbstractPageRequest {
    private final Sort sort;

    public CustomPageRequest(final int page, final Sort sort) {
        super(page, size);
        this.sort = sort;
    }

So in this call: carRepository.findAll(predicate, pageable) I put my "OwnPageable" with "sort" field. And it works just fine. But only when I specify fields from Car not from any of the concrete implementations. If I put: org.springframework.data.domain.Sort with property clutch.manufacturerCode into ownPageable it will not work, as clutch is not part of the car entity. That's clear.

3. The question

How could I sort by clutch.manufacturerCode in my example ?

Upvotes: 3

Views: 478

Answers (1)

What you are trying is not going to be possible. You want to sort all Cars which can be any number of subtypes like Suv, Sport etc and those subtypes may or may not have the nested property clutch.manufacturerCode.

Since you are specifying property of the subtype as sort order, it will not be present in all cars and in your case, it can only sort Cars which are trucks with a clutch. If it was allowed, hibernate would be in trouble when it retrieves other type of Cars that does not have this property.

Upvotes: 1

Related Questions