Home > Back-end >  Difference between JpaSort vs Sort
Difference between JpaSort vs Sort

Time:12-03

I have seen that when using Spring Boot there are JpaSort as well as Sort available for sorting and using in pagination. I have tried to figure out the difference between these two, but could not find much information regarding that.

Can someone tell me the difference between these two from a performance perspective as well as implementation perspective?

CodePudding user response:

(1) What is JPA Metamodel?

Often, when we write a criteria query, we need to reference entity classes and their attributes. Now, one of the ways of doing this is to provide the attributes' names as strings. But, this has several downsides. The JPA Metamodel was introduced by the community to avoid these drawbacks and provide static access to the metadata of the managed entity classes. For one, we have to look up the names of entity attributes. And, in case a column name is changed later in the project lifecycle, we have to refactor each query where the name is being used.

source https://www.baeldung.com/hibernate-criteria-queries-metamodel#prerequisites

(2) Inheritance between JpaSort and Sort

public class JpaSort extends Sort

(3) Authoritative definitions.

Sort Sort option for queries. You have to provide at least a list of properties to sort for that must not include null or empty strings. The direction defaults to DEFAULT_DIRECTION.

JpaSort Sort option for queries that wraps JPA meta-model Attributes for sorting.

https://docs.spring.io/spring-data/data-jpa/docs/current/api/org/springframework/data/jpa/domain/JpaSort.html

Let's see example

Page<Product> allProductsSortedByName = productRepository.findAll(Sort.by("name"));
Order order1 = new Order(Sort.Direction.DESC, "published");

and

List<Employee> list = repo.findByDepartment("Sales", JpaSort.unsafe("LENGTH(name)", "salary"));

(4) Conclusion: JpaSort support JPA meta-model Attributes what Sort does not support.

  • Related