如何自动填充mongo存储库?

时间:2017-06-15 08:07:44

标签: mongodb spring-data

将Spring Data MongoDB与MongoRepository一起使用。我有这个豆子

@Bean
public Jackson2RepositoryPopulatorFactoryBean repositoryPopulator() {

    Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
    try {
        factory.setResources(resourceResolver.getResources("classpath:static/collections/*.json"));
    } catch (IOException e) {
        log.error("Could not load data", e);
    }
    return factory;
}

它可以正常使用fongo(在测试运行结束时删除db)但不使用真正的mongo。如果我按原样离开bean并切换到真正的mongo实例,那么我将填充我的数据库,但只有第一次运行,如果我重新运行项目(+测试)然后它失败,因为它已经填充(获取DuplicateKeyException)。

如何仅在存储库为空的情况下填充?

2 个答案:

答案 0 :(得分:1)

@Bean
public Jackson2RepositoryPopulatorFactoryBean repositoryPopulator() throws Exception {

    Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
    try {
        Resource[] resources = resourceResolver.getResources("classpath:static/collections/*.json");
        //resources to list so I can add only the necessary resources
        List<Resource> resourcesToFill = new ArrayList<>();
        for (Resource r : resources) {
            String collection = r.getFilename().substring(0, r.getFilename().length() - 5);
            if (!mongoTemplate().collectionExists(collection))
                resourcesToFill.add(r);
        }

        //back to Array...
        resources = new Resource[resourcesToFill.size()];
        for(int i=0; i<resources.length; i++)
            resources[i] = resourcesToFill.get(i);
        factory.setResources(resources); // <-- the reason of this shitty code, why the hell use Array? 
    } catch (IOException e) {
        log.error("Could not load data", e);
    }
    return factory;
}

答案 1 :(得分:1)

考虑使用Mongobee等数据迁移工具。这基本上是MongoDB的Liquibase / Flyway。