20

Is it possible to load initial data in a MongoDB database using src/main/resources/data.sql or by any other file?

I understand that data.sql is used for SQL DB's whereas MongoDB is a NOSQL DB. But just wanted to know if there is any equivalent of data.sql for NOSQL DB's.

While googling I found out this SO link (Spring Boot - Loading Initial Data) which does what I am looking for but still it's not a standalone file data.sql.

3 Answers 3

5

To load initial data you can use db migration tool like MongoBee

It's very useful option to handle data initialization in java. You just need to configure @Bean public Mongobee mongobee in your spring boot and setup component scan for data ChangeLogs where data creation actually happens.

Sign up to request clarification or add additional context in comments.

Comments

5

You can use a repository populator with Spring Data MongoDB. Let me demonstrate this with a code sample in Kotlin:

@Configuration
class TestApplicationConfig {
    @Value("classpath:test_data.json")
    private lateinit var testData: Resource

    @Bean
    @Autowired
    fun repositoryPopulator(objectMapper: ObjectMapper): Jackson2RepositoryPopulatorFactoryBean {
        val factory = Jackson2RepositoryPopulatorFactoryBean()
        // inject your Jackson Object Mapper if you need to customize it:
        factory.setMapper(objectMapper)
        factory.setResources(arrayOf(testData))
        return factory
    }
}

Put test_data.json in resources directory.

3 Comments

can you take the array from test_data.json and populate it 1 by 1?
@ShaharWider it looks like a new question. please ask and Stack Overflow will answer.
i did about 20 days ago. no one answered... stackoverflow.com/questions/60711819/…
4

you can define your data in json/xml and use populator elements of the repository to load the data.

https://docs.spring.io/spring-data/mongodb/docs/2.0.9.RELEASE/reference/html/#core.repository-populators

Comments

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.