首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Boot分页查询

Spring Boot分页查询
EN

Stack Overflow用户
提问于 2021-05-28 10:58:51
回答 1查看 179关注 0票数 0

我想使用返回一个@Query对象的注释Page在spring中编写一个查询。

所以,我的问题是:最佳的JPA查询类型是什么(JPQL,NativeQuery,.)为了分页?

预先谢谢你!

EN

回答 1

Stack Overflow用户

发布于 2021-05-28 11:54:02

对于分页,我使用org.springframework.data.repository.PagingAndSortingRepository --这允许存储库返回一个页面

存储库代码:

代码语言:javascript
复制
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ItemRepository 
extends JpaRepository<Item, Long> , PagingAndSortingRepository<Item, Long>{
    
}

服务代码:

代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class ItemService {

    @Autowired
    private ItemRepository repository;

    public Page<Item> findItems(Pageable pageable){
        return repository.findAll(pageable);        
    }
        
}

控制器代码:

代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path="api/v1/")
@CrossOrigin(origins = "http://localhost:4200")
public class ItemController {

    @Autowired
    private ItemService service;
    
    @GetMapping("/items")
    public Page<Item> findItems(@PageableDefault(size = 5) Pageable pageable) {     
        return service.findItems(pageable);
    }
    
}

反应体

代码语言:javascript
复制
{
    "content": [ ... ], // contain your objects 
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 5,
        "unpaged": false,
        "paged": true
    },
    "last": false,
    "totalElements": 22,
    "totalPages": 5,
    "size": 5,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "numberOfElements": 5,
    "first": true,
    "empty": false
}

我希望这能帮上忙,祝你今天愉快!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67737625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档