我想使用返回一个@Query对象的注释Page在spring中编写一个查询。
所以,我的问题是:最佳的JPA查询类型是什么(JPQL,NativeQuery,.)为了分页?
预先谢谢你!
发布于 2021-05-28 11:54:02
对于分页,我使用org.springframework.data.repository.PagingAndSortingRepository --这允许存储库返回一个页面
存储库代码:
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>{
}服务代码:
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);
}
}控制器代码:
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);
}
}反应体
{
"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
}我希望这能帮上忙,祝你今天愉快!
https://stackoverflow.com/questions/67737625
复制相似问题