3

As you know, when using spring boot jpa module, below codes in application.properties import pre-defined sql data to rdb.

spring.datasource.initialization-mode = always
spring.datasource.data = classpath:/sql/spring-boot-mysql.sql

But when using mongodb as storage, what properties codes in application.properties file can import pre-defined JSON data of external files? If such properties do not exit, how can the JSON data be imported from the external files with spring boot?

1 Answer 1

4

I don't know if there is a solution using application.properties but here is my solution to import documents from a file containing one document per line.

public static void importDocumentsFromJsonFile(File file) {
        //Read each line of the json file. Each file is one observation document.
        List<Document> observationDocuments = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(file.getPath()));) {
            String line;
            while ((line = br.readLine()) != null) {
                observationDocuments.add(Document.parse(line));
            }
        } catch (IOException ex) {
            ex.getMessage();
        }
        mongoTemplate.getCollection("yourCollection").insertMany(observationDocuments);
    }
Sign up to request clarification or add additional context in comments.

4 Comments

I have more question. I am using MongoRepository interface. But MongoRepository.save or insert method throws error with the Document objects parameter. Any idea?
I have no idea. I suggest you to post another question with the error logged and to let me know.
Which Document class are you using? I get The method parse(String) is undefined for the type Document for org.springframework.data.mongodb.core.mapping.Document and also for org.w3c.dom.Document. Is it probably org.bson.Document?
Yes it's org.bson.document of mongo-java-driver API, Whch comes as a peer dependency of Spring data mongodb if I'm not wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.