Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Pageable sort with nested property

in my Spring boot application I have an entity with an embedded primary key:

public class MyEntity {
    
    @EmbeddedId
    private MyPk pk;

}

@Embeddable
public class MyPk implements Serializable {
    
    private Integer key1;

    private Integer key2;

}

To sort the results using spring's Pageable object I have to call the rest service at: localhost?sort=pk.key1,asc

Is it possible, using JPA, to accept requests without pk? For example: localhost?sort=key1,asc

I'd like to be able to do this at the service level

like image 932
Mark116 Avatar asked Feb 22 '26 06:02

Mark116


1 Answers

You would have to rewrite the sorts before passing them to the data layer:

@RequiredArgsConstructor
@Service
public class YourService {

    public static final Set<String> NESTED_PK_PROPERTIES = Set.of("key1", "key2");

    private final YourRepository repository;

    @Transactional(readOnly = true)
    public Page<YourResultType> search(final Pageable pageable) {
        // Correct sort properties if they refer to a nested property
        final Sort sort = Sort.by(
                pageable.getSort().get()
                        .map(order -> NESTED_PK_PROPERTIES.contains(order.getProperty()) ?
                                Sort.Order
                                        .by(String.format("%s_%s", "pk", order.getProperty()))
                                        .with(order.getDirection()) :
                                order)
                        .collect(Collectors.toList()));

        // Get manual changes matching the search criteria
        return repository.findAll(PageRequest.of(
                pageable.getPageNumber(), pageable.getPageSize(), sort));
    }

}

like image 161
Times Avatar answered Feb 25 '26 00:02

Times