Search code examples
javaspringmongodbpostman

Using saveAll to save a ArrayList of type FileMetadataEntity to a mongoDB database


Here is the MetadataService class. Method in this class is called in the FileController.

Here is the FileController code(Omitted details...):

@Autowired
    private MetadataService metadataService;

    @PostMapping("/metadata")
    public ResponseEntity<String> uploadMetadata(@RequestParam("specFile") MultipartFile specFile) {
        try {
            String jsonSpecFile = new String(specFile.getBytes(), StandardCharsets.UTF_8);
            metadataService.parseAndSaveMetadata(jsonSpecFile);
            return ResponseEntity.ok().body("Metadata uploaded successfully.");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error uploading metadata.");
        }
    }

package com.example.justin_fulkerson_project.services;

import com.example.justin_fulkerson_project.entities.FileMetadataEntity;
import com.example.justin_fulkerson_project.respositories.FileMetadataRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

// Service class to parse JSON spec file and save metadata to MongoDB
@Service
public class MetadataService {

    private FileMetadataRepository metadataRepository;

    @Autowired
    public MetadataService(FileMetadataRepository metadataRepository)
    {
        this.metadataRepository = metadataRepository;
    }

    public void parseAndSaveMetadata(String jsonSpecFile) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonSpecFile);

        ArrayList<FileMetadataEntity> data = new ArrayList<>();

        JsonNode fieldsNode = rootNode.get("fields");
        if (fieldsNode.isArray()) {
            for (JsonNode fieldNode : fieldsNode) {
                String fieldName = fieldNode.get("name").asText();

                JsonNode startNode = fieldNode.get("start");
                int startPosition = startNode != null ? startNode.asInt() : 0;

                JsonNode lengthNode = fieldNode.get("length");
                int length = lengthNode != null ? lengthNode.asInt() : 0;


                // Create an instance of FileMetadataEntity
                FileMetadataEntity metadata = new FileMetadataEntity();
                metadata.setFieldName(fieldName);
                metadata.setStartPosition(startPosition);
                metadata.setLength(length);

                data.add(metadata);

                System.out.println(metadata.getFieldName());

                // Save the metadata to the repository
            }
            metadataRepository.saveAll(data);
        }
    }


}


In the mongoDB collection, two documents are outputted to the collection instead of one document with an array of metadata for one spec file.

Here is the JSON file I am parsing...

"fields": [ { "name": "field1", "startIndex": 0, "length": 5 }, { "name": "field2", "startIndex": 6, "length": 10 } ] }

I tried created an ArrayList with the given types and adding at the end of each iteration of the for loop.


Solution

  • @Document
    public class FileMetadataEntity
    {
        private List<MetaData> metaDataList;
    }
    

    Create a new class MetaData and add all the fields like name, start etc. in that.Now instead ArrayList<FileMetadataEntity> data = new ArrayList<>(); use ArrayList<MetaData> data = new ArrayList<>(); and update this list in the FileMetadataEntity object say fileMetaData and then call metadataRepository.save(fileMetadata);