2017-06-15 110 views
1

在MongoRepository中使用Spring Data MongoDB。我有這個bean如何自動填充mongo存儲庫?

@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是在測試運行結束時下降),但與真正的蒙戈。如果我按照原樣離開bean並切換到真實的mongo實例,那麼我會填充我的數據庫,但只有第一次運行,如果我重新運行項目(+測試),那麼它會失敗,因爲它已經填充(獲取DuplicateKeyException )。

如何僅填充存儲庫爲空的情況?

回答

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

考慮使用數據遷移工具,如Mongobee。這基本上是Liquibase/Flyway for MongoDB。

相關問題