19 Şubat 2021 Cuma

SpringData JpaRepository Derived Query - OrderBy

Giriş
Açıklaması şöyle.
Sorting Derived Query Results
Spring Data JPA also allows us to enable static ordering by appending an OrderBy clause to the query method that references a property and by providing a sorting direction (Asc or Desc).

The following example uses static ordering to retrieve all User entities whose name contains a given value in the ascending order:
List<User> findByNameContainingOrderByName(String name);
// OR
List<User> findByNameContainingOrderByNameAsc(String name);

By default, the OrderBy clause sorts the results in the ascending order. But you can add Desc to reverse the sorting direction:
List<User> findByNameContainingOrderByNameDesc(String name);

If you need dynamic ordering, you can add a Sort parameter to your query method. This is one of the special parameters supported by Spring Data JPA. Sort triggers the generation of an ORDER BY clause. Here is an example:

List<User> findByNameContaining(String name, Sort sort);
To call the above method, you need to create a Sort object to specify the entity attributes and their ordering:
// sort users in ascending order
List<User> users = userRepository.findByNameContaining("john",Sort.by("name").descending());
// sort users in decending order
List<User> users = userRepository.findByNameContaining("john",Sort.by("name").descending());
// multiple sort parameters
List<User> users = userRepository.findByNameContaining("john", Sort.by("name","age").descending());
Örnek
Şöyle yaparız
@Entity
public class WishList {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "created_date")
  private Date createdDate;
  ...
}

@Repository
public interface WishListRepository extends JpaRepository<WishList, Integer> {
    
  //Method for fetching the wishlist of a particular user and order it by created_date
  List<WishList> findAllByUserIdOrderByCreatedDateDesc(Integer userId);
    
}

Hiç yorum yok:

Yorum Gönder