In Spring Data JPA, one of the ways to do sorting on the returned result is to define repository methods with Sort parameter.
It can be used with both query methods or with declared JPQL queries using @Query.
Example
Entity
@Entity
public class Employee {
private @Id
@GeneratedValue
Long id;
private String name;
private String dept;
private int salary;
.............
}
Repository
package com.logicbig.example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
public List<Employee> findByDept(String deptName, Sort sort);
}
Example client
@Component
public class ExampleClient {
@Autowired
private EmployeeRepository repo;
public void run() {
List<Employee> employees = createEmployees();
repo.saveAll(employees);
System.out.println(" -- finding all employees --");
Iterable<Employee> all = repo.findAll();
all.forEach(System.out::println);
System.out.println(" -- finding by dept Sales sort by 'salary' and 'name' --");
List<Employee> list = repo.findByDept("Sales", Sort.by("salary", "name").ascending());
list.forEach(System.out::println);
}
private List<Employee> createEmployees() {
return Arrays.asList(
Employee.create("Diana", "Sales", 2000),
Employee.create("Mike", "Sales", 1000),
Employee.create("Rose", "IT", 4000),
Employee.create("Sara", "Sales", 3000),
Employee.create("Andy", "Sales", 3000),
Employee.create("Charlie", "IT", 2500)
);
}
}
Main class
public class ExampleMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
ExampleClient exampleClient = context.getBean(ExampleClient.class);
exampleClient.run();
EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
emf.close();
}
} -- finding all employees -- Employee{id=1, name='Diana', dept='Sales', salary=2000} Employee{id=2, name='Mike', dept='Sales', salary=1000} Employee{id=3, name='Rose', dept='IT', salary=4000} Employee{id=4, name='Sara', dept='Sales', salary=3000} Employee{id=5, name='Andy', dept='Sales', salary=3000} Employee{id=6, name='Charlie', dept='IT', salary=2500} -- finding by dept Sales sort by 'salary' and 'name' -- Employee{id=2, name='Mike', dept='Sales', salary=1000} Employee{id=1, name='Diana', dept='Sales', salary=2000} Employee{id=5, name='Andy', dept='Sales', salary=3000} Employee{id=4, name='Sara', dept='Sales', salary=3000}
Using JpaSort
JpaSort can be used to sort by applying a JPQL function to the target property. See an example here.
Example ProjectDependencies and Technologies Used: - spring-data-jpa 2.0.7.RELEASE: Spring Data module for JPA repositories.
Uses org.springframework:spring-context version 5.0.6.RELEASE - hibernate-core 5.3.1.Final: Hibernate's core ORM functionality.
Implements javax.persistence:javax.persistence-api version 2.2 - h2 1.4.197: H2 Database Engine.
- JDK 1.8
- Maven 3.3.9
|
|