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
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With