Search code examples
springspring-bootjpaspring-data-jpathymeleaf

Limiting the visibility of results from the database on one page- spring boot


I create web application in spring boot using the postgress database.

I want to limit the number of records per page(now it's 30,000 records - it's loading a long time), so what should i do to limit it? I use thymeleaf.

Model:

@Entity(name="articles")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Articles {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long article_id;
private String title;
private String issn;
private String eissn;
private String title2;
private String issn2;
private String eissn2;
private Integer points;

@ManyToMany
@JoinTable(
        name = "articles_categories",
        joinColumns = @JoinColumn(name = "article_id"),
        inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<Category> categories;
....

getters and setters

Repository:

public interface ArticlesRepository extends JpaRepository<Articles,Long> {
}

Controller:

@Controller
@RequestMapping("/articles")
public class ArticlesController {


private ArticleService articleService;

@Autowired
public void setArticleService(ArticleService articleService) {
    this.articleService = articleService;
}

@GetMapping 
public String getAll(Model model)
{
    model.addAttribute("articles", articleService.list());
    return "articles"; 
}

Service:

@Service
public class ArticleService {


@Autowired
private ArticlesRepository articlesRepository;

public ArticleService() {
}

public List<Articles> list(){
    return articlesRepository.findAll();
}}

Solution

  • Use Pageable to limit the size of your articles.

    public List<Articles> list(int page, int limit){
        Page<Articles> pageableArticales = articlesRepository.findAll(PageRequest.of(page, limit);
        return pageableArticales.getContent();
    }
    

    Note that repository.findAll(pageable) wraps the list of data on Page, which provides getNumber(), getSize(), getNumberOfElements(), getTotalPages(), getTotalElements, etc.

    And consider exploring PageRequest and PagedResources as well.