JPA Sorting & implicit joins
On a GET call for an HTTP API usually clients would need the functionality to filter and sort by certain fields. First, let’s suppose you have the following entities: Person, Address and City. Let’s assume that one person can have many addresses, and each address can have one city.
Using Spring Data’s PagingAndSortingRepository the service layer method would look something like this:
@RequiredArgsContructor
public class PersonService {
@Autowired
private PersonRepository personRepository;
public List<PersonDto> findAll() {
List<Person> persons = personRepository.findAll(Sort.by(Person_.address + "." Adress_.city + "." + City_.name));
return persons.stream()
.map(person -> convertToDto(person))
.collect(Collectors.toList());
}
// Handle conversion
// ...
}
If you are wondering where do the Person_, Address_, City_ classes come from, you should look into JPA Metamodel generator which generates these classes for you.