Location>code7788 >text

PageHeper

Popularity:661 ℃/2024-09-05 17:31:01

PageHelper It is a very popularMyBatis Pagination plugin, mainly used to simplify the implementation of paging queries. Use thePageHelper Paging parameters can be handled automatically when executing database queries, thus avoiding the need to manually write cumbersome paging logic.

Learn about PageHelper and its usage today!

PageHelper

Key Features

  1. paging search: By() method specifies the page number and size of each page, after which the query executed is automatically paged.
  2. sorting function: Sorting is supported, and the sorted result set can be obtained by specifying the sorting fields and the sorting method during the paging query.
  3. Simplify paging logic: No need to manually modify SQL statements.PageHelper Paging logic is automatically added to the query SQL, greatly simplifying the code.
  4. Multi-database supportPageHelper Supports many mainstream databases, such as MySQL, Oracle, PostgreSQL and so on.

Procedure for use

  1. Introducing dependencies
    exist AddPageHelper Dependency:

    <dependency>
        <groupId></groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.2.0</version>
    </dependency>
    
  2. Configuring Interceptors
    In a MyBatis configuration file or configuration class, register thePageHelper Interceptor:

    @Bean
    public PageInterceptor pageHelper() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        ("helperDialect", "mysql"); // Database type
        (properties);
        return pageInterceptor;
    }
    
  3. Pagination Query Usage Example
    Use the() method to specify the paging parameters, and subsequent queries will automatically take the paging information with them:

    @Service
    public class UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        public List<User> getUsers(int pageNum, int pageSize) {
            // Turn on paging
            (pageNum, pageSize);
            // Inquiry results
            return ();
        }
    }
    
  4. Return paging results
    utilizationPageInfo to wrap the paging results, containing both the paging information and the query results:

    List<User> userList = ();
    PageInfo<User> pageInfo = new PageInfo<>(userList);
    (()); // Total number of records
    (()); // list of records on the current page
    

Core methodology

  • (int pageNum, int pageSize): Specify the page number and size of each page, and subsequent queries will be automatically paged.
  • (String orderBy): Set the sorting rules, e.g."id desc"pressid Arranged in reverse order.
  • PageInfo<T>: Encapsulates the paging result information, including the total number of records, the total number of pages, and the records on the current page.

summarize

PageHelper Provides a simple way to implement MyBatis paging query , automatic processing of paging logic and simplify the code , while supporting a variety of databases and sorting functions , is a commonly used MyBatis user paging query tool .

PageHelper in SpringBoot

pagehelper-spring-boot-starter bePageHelper Spring Boot autoconfiguration version of Spring Boot, which makes it easier to integrate thePageHelper, especially in Spring Boot projects. As opposed to manually configuringPageHelperUsepagehelper-spring-boot-starter Configuration and use can be further simplified.

Procedure for use

  1. Introducing dependencies
    In the Spring Boot project's Addpagehelper-spring-boot-starter Dependency:

    <dependency>
        <groupId></groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.4.6</version>
    </dependency>
    
  2. auto-configuration
    pull intopagehelper-spring-boot-starter After that, there is no need to manually configure thePageHelper interceptor, Spring Boot automatically configures the paging plugin.

  3. In the query method, use the
    utilization() method specifies the paging parameter, the results are automatically paged when the query is executed.

    Sample code:

    @Service
    public class UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        // Paging through the list of users
        public PageInfo<User> getUsers(int pageNum, int pageSize) {
            // Set the paging parameters
            (pageNum, pageSize); // Execute the query to get the result set.
            // Execute the query and get the result set
            List<User> users = (); // Use PageInfo to get the result set.
            // Use PageInfo to encapsulate the paging information.
            return new PageInfo<>(users);
        }
    }
    
  4. Return paging results
    PageInfo bePageHelper Tool class provided to encapsulate paging information, such as total number of records, total number of pages, current page data and so on. This can be accomplished by using thePageInfo object gets this information:

    PageInfo<User> pageInfo = (1, 10);
    (()); // Get the total number of records.
    (()); // Get the total number of pages.
    (()); // get current page data
    
  5. Customized configuration (optional)
    You can use Spring Boot's maybe File CustomizationPageHelper related configurations, such as database dialects, rationalization configurations, paging methods, and so on.

    exist Add custom configurations to the

    pagehelper.
      helper-dialect: mysql # database dialect
      reasonable: true # Enable rationalization to avoid out-of-range page numbers
      support-methods-arguments: true # support paging parameters as method arguments
      params: count=countSql # SQL for counting the total number of pages in a paging query
    

    Or in the case of Center:

    =mysql
    =true
    =true
    =count=countSql
    

complexity theory

  • time complexity: The time complexity of a paging query depends on the database query operation. In general, the query complexity is $O(n)$, plus the paging condition, and the actual execution may vary depending on the indexing and optimization mechanism of the database.
  • (math.) space complexity: The space complexity depends on the paging result and the form in which the data is stored, and is typically $O(k)$, wherek is the amount of data returned per page.

summarize

pass (a bill or inspection etc)pagehelper-spring-boot-starterThe following are a few examples of how you can easily integrate thePageHelper, automatically complete the configuration and operation of the paging query , simplifying the amount of developer code . Also supports customized configuration , can flexibly respond to a variety of paging needs .

practical application

It's used in a lot of places in the faux 12306 project I'm working onpagehelperSo you will generally encapsulate the incoming and outgoing classes of a paged query, just for the example of a query for a rider:

PageReq

seal insidePageReqserves as a parent class for the paging query entry class, providing thepageNumrespond in singingpageSize

PageReq
public class PageReq {

    @NotNull(message = "【pagination】Cannot be empty")
    private Integer start;

    @NotNull(message = "【Number of articles per page】Cannot be empty")
    @Max(value = 100, message = "【Number of articles per page】cannot exceed100")
    private Integer count;

    public @NotNull(message = "【pagination】Cannot be empty") Integer getStart() {
        return start;
    }

    public void setStart(@NotNull(message = "【pagination】Cannot be empty") Integer start) {
         = start;
    }

    public @NotNull(message = "【Number of articles per page】Cannot be empty") @Max(value = 100, message = "【Number of articles per page】cannot exceed100") Integer getCount() {
        return count;
    }

    public void setCount(@NotNull(message = "【Number of articles per page】Cannot be empty") @Max(value = 100, message = "【Number of articles per page】cannot exceed100") Integer count) {
         = count;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("pageReq{");
        ("start=").append(start);
        (", count=").append(count);
        ('}');
        return ();
    }
}

Inheritance of entry class for query rider servicePageReqClass;

PassengerQueryReq
public class PassengerQueryReq extends PageReq {

    private Long memberId;

    private String idCard;

    public Long getMemberId() {
        return memberId;
    }

    public void setMemberId(Long memberId) {
         = memberId;
    }

    public String getIdCard() {
        return idCard;
    }

    public void setIdCard(String idCard) {
         = idCard;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("PassengerQueryReq{");
        ("memberId=").append(memberId);
        (", idCard='").append(idCard).append('\'');
        ('}');
        return ();
    }
}

Used in the Lookup Rider servicePageReqofferedpageNumcap (a poem)pageSizeinvocationsPageHelper

PassengerService
@Service
public class PassengerService {

    @Resource
    private PassengerMapper passengerMapper;

    public List<PassengerQueryResp> queryList (PassengerQueryReq req) {
        PassengerExample passengerExample = new PassengerExample();
         criteria = ();
        if ((())) {
            (());
        }
        ((), ());
        List<Passenger> passengerList = (passengerExample);
        return (passengerList, );
    }

    public void update(PassengerSaveReq req) {
        DateTime now = ();
        Passenger passenger = (req, );
        (());
        (now);

        PassengerExample passengerExample = new PassengerExample();
        ().
                andMemberIdEqualTo(()).
                andIdCardEqualTo(());

        (passenger, passengerExample);
    }
}

PageResp

seal insidePageRespAs the response class, returns the query total, the paged total, and the query list;

PageResp
public class PageResp<T> implements Serializable {

    private static final Long serialVersionUID = 1L;

    /**
     * Total number of search results
     */
    private Long total;

    /**
     * List of query results
     */
    private List<T> list;

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
         = list;
    }

    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
         = total;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("PageResp{");
        ("total=").append(total);
        (", list=").append(list);
        ('}');
        return ();
    }
}

Used in the Rider Enquiry ServicePageInfoGet the total number of results and the number of pages of the paging query, returnPageResp

PassengerService
@Service
public class PassengerService {

    private static final Logger LOG = ();

    @Resource
    private PassengerMapper passengerMapper;

    public PageResp<PassengerQueryResp> queryList (PassengerQueryReq req) {
        PassengerExample passengerExample = new PassengerExample();
         criteria = ();
        if ((())) {
            (());
        }

        // mybatis PageHelperpaging search
        ("Search for page number:{}", ());
        ("Number of articles per page:{}", ());
        ((), ());
        List<Passenger> passengerList = (passengerExample);
        // particle marking the following noun as a direct objectpassengerListchange over topassengerQueryRespList
        List<PassengerQueryResp> passengerQueryResp = (passengerList, );

        // pageHelper获取paging search总item count (of a consignment etc),将paging search结果(item count (of a consignment etc)+list)encapsulatepageResp
        PageInfo<Passenger> pageInfo = new PageInfo<>(passengerList);
        ("总item count (of a consignment etc):{}", ());
        ("Total pages:{}", ());
        PageResp<PassengerQueryResp> pageResp = new PageResp<>();
        (passengerQueryResp);
        (());
        return pageResp;
    }
}