初始化数据库上的数据 (Spring & Mongo)

Initialize data on the database (Spring & Mongo)

我正在使用 mongock 在数据库上生成初始数据,到目前为止它在 Country 上运行良好,但还有很长的路要走

@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);
    }
}

我现在看到的问题是我需要为 Places 做同样的事情。问题是 Places140.000 records。想象一下用手填充它。我在一个 200MB json 文件中有这些地方,我可以使用它们而不是手动填充。

最好的方法是什么?

您可以在这里做的是:

  1. 将 JSON 文件作为资源放置在您的项目中。
  2. 在迁移到 read resource file and deseriliza using Jackson, gson 或您喜欢的任何 JSON 库时添加一些逻辑。
  3. 将这些记录转换为 Country 个实例,并像您现在所做的那样将它们保存到数据库中。