Summary of three ways of Sort sorting by JPA in SpringBoot

  • 2021-12-13 07:52:37
  • OfStack

Directory Environment Description Pre-Description Method 1: Sort Based on Special Parameters Method 2: Sort Based on Custom @ Query Method 3: Summary Based on Sort Field in Pageable

Introduction: In Spring Boot application, sorting based on a certain field of data is a very common requirement. Here, three common uses of Sort will be given. Based on paging application, everyone can take what they need and use it at an opportune time.

Environmental description

Spring 4.2 Spring Boot 1.5.11 Java 8

Pre-description

Definition of ECardEntity. java:


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.jd.ai.fasion.util.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Entity
@Table(name="t_ebusiness_card")
@Data
@EqualsAndHashCode(callSuper=true)
public class ECardEntity extends BaseEntity { 
    private static final long serialVersionUID = 6580526495176090890L;
    @Column
    private String name;
    @Column(name="zip_url")
    private String zipUrl;
    @Column(name="thumb_url")
    private String thumbUrl;
    @Column(name="seq_num")
    private int seqNum;
}

Here, seqNum is a sort field, which is sorted based on ascending order.

Definition of Repository:


@Repository
public interface EBusinessCardRepository extends JpaRepository<ECardEntity, Long> {
   /// Definition of method 
}

Method 1: Sorting based on special parameters

Create a paging object:


Pageable pageable = new PageRequest(pageNum, size);

Define the corresponding method in Repository:


Page<ECardEntity> findByOrderBySeqNumAsc(Pageable pageable);

Here, the default method name formed by field splicing is used, so that the corresponding method is automatically resolved.

Method 2: Sort based on custom @ Query

The object definition for Pageable is the same as in Method 1.

Define the corresponding JPL statement in Repository:


@Query("select e from ECardEntity e ORDER BY e.seqNum ASC")
Page<ECardEntity> findInOrders(Pageable pageable);

Method 3: Based on the Sort field in Pageable

Declaration of an Pageable object:


Sort sort = new Sort(Direction.ASC, "seqNum");
Pageable pageable = new PageRequest(pageNum, size, sort);

Here, the Pageable object is created with the Sort field as the entry parameter of the constructor.

There is no need to declare any new methods in Repository, just use the findAll (Pageable pageable) method inherited from JpaRepository.

Calling the methods in the specific Repository in Service is as follows:


Page<ECardEntity> eCardEntities = this.eCardRepo.findAll(pageable);

Summarize

These methods are very simple and easy to use. For the simple requirements of this sorting, the method is the simplest, and can be used directly without any method declaration in Repository.


Related articles: