What is the usage method of pagehelper in Java?

The method of using PageHelper for pagination in Java is as follows:

  1. First of all, to introduce PageHelper dependency into your project, you can add the dependency through Maven or Gradle.
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.1</version>
</dependency>
  1. Add PageHelper methods to your Mapper interface to set pagination parameters.
import com.github.pagehelper.Page;

public interface YourMapper {
    List<YourEntity> selectByPage(Page<YourEntity> page);
}
  1. Write the corresponding SQL statements in your Mapper interface’s XML file.
<select id="selectByPage" resultType="YourEntity">
    SELECT * FROM your_table
</select>
  1. Call the methods of PageHelper in your Service layer to perform pagination queries.
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

public class YourService {
    @Autowired
    private YourMapper yourMapper;

    public List<YourEntity> selectByPage(int pageNum, int pageSize) {
        Page<YourEntity> page = PageHelper.startPage(pageNum, pageSize);
        yourMapper.selectByPage(page);
        return page.getResult();
    }
}
  1. Finally, in your Controller layer, call the method from the Service layer to retrieve paginated data.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YourController {
    @Autowired
    private YourService yourService;

    @GetMapping("/yourData")
    public List<YourEntity> getYourData(@RequestParam int pageNum, @RequestParam int pageSize) {
        return yourService.selectByPage(pageNum, pageSize);
    }
}

Following these steps, you can now use PageHelper for pagination in Java. Hope it helps you!

bannerAds