How to get a big amount of JSON data from DB and then putting that into a json or csv file that can be downloaded directly from spring boot REST API?

Viewed 18

My whole Question is basically in the title. My Current Controller Method to do this looks like this:

@GetMapping("/download")
public ResponseEntity<byte[]> downloadData() throws JsonProcessingException {
    List<DataResponse> data = service.getAllData();
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(data);
    byte[] isr = json.getBytes();
    String fileName = "data.json";
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentLength(isr.length);
    respHeaders.setContentType(new MediaType("text", "json"));
    respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

    return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);
}

My problem with that is, that it only works for a little amount of data, with the desired amount I get an OutOfMemory Heap Error...

0 Answers
Related