vikas kumar
vikas kumar

Reputation: 1

Jpa entity as sorted

I have a Employee entity class and I want a sorted list whenever I call 'List'. how can I do this in Spring boot?

I have implements Comparable with my entity class but I think that is not the write way.

Upvotes: 0

Views: 597

Answers (1)

Ishak Hari
Ishak Hari

Reputation: 188

If you want to sort un your code try this: (here you list will be sorted by name for example)

List<Employee> employees = employeeRepository.findAll();
Collections.sort(employees, new Comparator<Employee>() {
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareTo(e2.getName());
    }
});

If you are using a Spring Data repository to access your data, you can use the Sort class to specify the sort order when you call the findAll() like this:

List<Employee> employees = employeeRepository.findAll(Sort.by("name"));

Or if you want to sort it in your query, try this: (here you list will be sorted by name for example)

List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e ORDER BY e.name", Employee.class).getResultList();

But, in general, it is a good practice to perform sorting and filtering operations in the database rather than in the application code

Upvotes: 1

Related Questions