【问题标题】:Limiting the visibility of results from the database on one page- spring boot限制一页上数据库结果的可见性-spring boot
【发布时间】:2020-05-08 16:39:37
【问题描述】:

我使用 postgress 数据库在 Spring Boot 中创建 Web 应用程序。

我想限制每页的记录数(现在是 30,000 条记录 - 加载时间很长),那么我应该怎么做才能限制呢?我用百里香叶。

型号:

@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

存储库:

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

控制器:

@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
public class ArticleService {


@Autowired
private ArticlesRepository articlesRepository;

public ArticleService() {
}

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

【问题讨论】:

    标签: spring spring-boot jpa spring-data-jpa thymeleaf


    【解决方案1】:

    使用Pageable 限制文章的大小。

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

    请注意,repository.findAll(pageable) 包装了Page 上的数据列表,它提供了getNumber()getSize()getNumberOfElements()getTotalPages()getTotalElements 等。

    并考虑探索PageRequestPagedResources

    【讨论】:

    • 我应该更改百里香模板中的某些内容吗?我问是因为当我在控制器方法中设置例如 page=100 和 limit=40 时,我只收到 40 条记录,而无法转到下一页或类似的东西来查看更多记录。我应该怎么做才能浏览有其他记录的页面?
    • 您可以考虑查看hateos 来浏览页面。或者你也可以使用getTotalElements() / getTotalPages()。而pagelimit 你可以通过你的*model*(getAll(Model model))
    • 查看PagedResources 以及使用hateoas 链接..
    • 'And page and limit you can pass through your *model*(getAll(Model model))'是什么意思?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2018-01-01
    • 2020-05-09
    • 2020-01-18
    • 2016-04-25
    • 1970-01-01
    相关资源
    最近更新 更多