How to sort query results with Spring Data

BAEL-2331
This commit is contained in:
Trevor Gowing 2018-11-25 17:11:31 +02:00
parent 0c384f13b0
commit 322af68ae2
2 changed files with 32 additions and 0 deletions

View File

@ -2,7 +2,11 @@ package com.baeldung.passenger;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
interface PassengerRepository extends JpaRepository<Passenger, Long>, CustomPassengerRepository {
Passenger findFirstByOrderBySeatNumberAsc();
List<Passenger> findByOrderBySeatNumberAsc();
}

View File

@ -14,6 +14,8 @@ import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
@DataJpaTest
@ -66,4 +68,30 @@ public class PassengerRepositoryIntegrationTest {
Passenger actual = page.getContent().get(0);
assertEquals(expected, actual);
}
@Test
public void givenSeveralPassengersWhenOrderedBySeatNumberAscThenThePassengersReturnedInCorrectOrder() {
Passenger fred = Passenger.from("Fred", "Bloggs", 22);
Passenger ricki = Passenger.from("Ricki", "Bobbie", 36);
Passenger jill = Passenger.from("Jill", "Smith", 50);
Passenger siya = Passenger.from("Siya", "Kolisi", 85);
Passenger eve = Passenger.from("Eve", "Jackson", 95);
List<Passenger> passengers = repository.findByOrderBySeatNumberAsc();
assertThat(passengers, contains(fred, ricki, jill, siya, eve));
}
@Test
public void givenSeveralPassengersWhenFindAllWithSortBySeatNumberAscThenReturnPassengersInCorrectOrder() {
Passenger fred = Passenger.from("Fred", "Bloggs", 22);
Passenger ricki = Passenger.from("Ricki", "Bobbie", 36);
Passenger jill = Passenger.from("Jill", "Smith", 50);
Passenger siya = Passenger.from("Siya", "Kolisi", 85);
Passenger eve = Passenger.from("Eve", "Jackson", 95);
List<Passenger> passengers = repository.findAll(Sort.by(Sort.Direction.ASC, "seatNumber"));
assertThat(passengers, contains(fred, ricki, jill, siya, eve));
}
}