ยท
Sometimes, your JPA query returns a lot of results.
To handle such amount of data, you should use pagination.
And thanksfully, JPA provides an API for such needs.
1๏ธโฃ ๐๐ก๐ ๐ซ๐๐ฉ๐จ๐ฌ๐ข๐ญ๐จ๐ซ๐ฒ ๐พ ๐๐๐
@Repository public interface EmployeeRepository extends ๐๐๐ ๐ข๐ง๐ ๐๐ง๐๐๐จ๐ซ๐ญ๐ข๐ง๐ ๐๐๐ฉ๐จ๐ฌ๐ข๐ญ๐จ๐ซ๐ฒ<EmployeeEntity, Long> { }
2๏ธโฃ ๐๐ก๐ ๐ฌ๐๐ซ๐ฏ๐ข๐๐ ๐จโ๐ง ๐๐๐
@Service public class EmployeeService { @Autowired EmployeeRepository ๐ซ๐๐ฉ๐จ๐ฌ๐ข๐ญ๐จ๐ซ๐ฒ; public List<EmployeeEntity> getAllEmployees(Integer pageNo, Integer pageSize, String sortBy) { ๐๐๐ ๐๐๐๐ฅ๐ ๐ฉ๐๐ ๐ข๐ง๐ = ๐๐๐ ๐๐๐๐ช๐ฎ๐๐ฌ๐ญ.๐จ๐(๐ฉ๐๐ ๐๐๐จ, ๐ฉ๐๐ ๐๐๐ข๐ณ๐, ๐๐จ๐ซ๐ญ.๐๐ฒ(๐ฌ๐จ๐ซ๐ญ๐๐ฒ)); Page<EmployeeEntity> pagedResult = ๐ซ๐๐ฉ๐จ๐ฌ๐ข๐ญ๐จ๐ซ๐ฒ.findAll(paging); if(pagedResult.hasContent()) { return pagedResult.getContent(); } else { return new ArrayList<EmployeeEntity>(); } } }
3๏ธโฃ ๐๐ก๐ ๐๐จ๐ง๐ญ๐ซ๐จ๐ฅ๐ฅ๐๐ซ ๐ฎโโ๏ธ ๐๐๐
@RestController @RequestMapping("/employees") public class EmployeeController { @Autowired EmployeeService ๐ฌ๐๐ซ๐ฏ๐ข๐๐; @GetMapping public ResponseEntity<List<EmployeeEntity>> getAllEmployees( @RequestParam(defaultValue = "0") Integer pageNo, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "id") String sortBy) { List<EmployeeEntity> list = ๐ฌ๐๐ซ๐ฏ๐ข๐๐.getAllEmployees(pageNo, pageSize, sortBy); return new ResponseEntity<List<EmployeeEntity>>(list, new HttpHeaders(), HttpStatus.OK); } }