Home > Mobile >  Initialize data on the database (Spring & Mongo)
Initialize data on the database (Spring & Mongo)

Time:04-12

I'm using mongock to generate the initial data on the database and so far it's working fine for Country but still a long way to go

@ChangeUnit(id="country-initializer", order = "1")
public class CountryInitializerCU {

    @BeforeExecution
    public void beforeExecution(MongoTemplate mongoTemplate) {
        mongoTemplate.createCollection(COUNTRY_COLLECTION_NAME);
    }

    @RollbackBeforeExecution
    public void rollbackBeforeExecution() {
        // do nothing
    }

    @Execution
    public void execution(CountryRepository countryRepository) {
        List<Country> countries = new ArrayList<>();

        countries.add(new Country("AM", "ARM", "Armenia"));
        countries.add(new Country("AL", "ALB", "Albania"));
        countries.add(new Country("AO", "AGO", "Angola"));
        countries.add(new Country("BS", "BHS", "Bahamas"));
        countries.add(new Country("BY", "BLR", "Bahamas"));
        // TODO

        countryRepository.saveAll(countries);

    }

    @RollbackExecution
    public void rollbackExecution(MongoTemplate mongoTemplate) {
        mongoTemplate.dropCollection(COUNTRY_COLLECTION_NAME);
    }
}

The problem that I see now is that I need to to the same for Places. The problem is that Places have 140.000 records. Imagine filling that by hand. I have those places in a 200MB json file that I could use instead of filling manually.

What is the best approach?

CodePudding user response:

What you may do here is:

  1. Place the JSON file as a resource in your project.
  2. Add some logic in your migration to read resource file and deseriliza using Jackson, gson or any JSON library of your preference.
  3. Transform these records into Country instances and save them into the database as you are doing right now.

CodePudding user response:

Dude, use file reader feature of Java and traverse all the required fields you want to store in database.

CodePudding user response:

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

CodePudding user response:

1.Add your json file into resource folder of your project.

2.You can follow the below refernce for converting JSON into list of places object. https://stackabuse.com/converting-json-array-to-a-java-array-or-list/

  • Related