📜 ⬆️ ⬇️

Migrating data with mongoDB and Spring Boot

Each developer sooner or later encounters the need to migrate data in a database. On our project we use mongoDB as a database. We approached data migration in various ways:



The result was a library called Mongration, which supports all the functionality described above.


Spring Boot life cycle support


The first function is implemented using auto configuration, which starts after creating MongoClient and before scanning repositories:


 @Configuration @AutoConfigureAfter(MongoAutoConfiguration.class) @AutoConfigureBefore(MongoDataAutoConfiguration.class) @Import(MongrationConfiguration.class) public class MongrationAutoConfiguration { } 

But the problem with auto configuration is that if you use the @EnableMongoRepositories annotation to activate repositories, Mongo Data components are initialized before our auto configuration. To avoid this problem, you must use the @EnableMongration annotation with @EnableMongoRepositories :


 @Configuration @EnableMongoRepositories @EnableMongration public class MongoRepositoriesConfiguration { } 

The @EnableMongration does nothing more than launching the same configuration, only allows you to start it earlier:


 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(MongrationConfiguration.class) public @interface EnableMongration { } 

Transaction support


To support transactions, you need to configure Replica Set MongoDB. You must also declare a MongoTransationManager bin (if Mongration does not find this bin in context, then it will create it yourself). Mongration allows you to use transactions in two ways:



The second method is useful in that it allows using both DDL operations that cannot be started in a transaction, and DML operations launched in a transaction in a single migration.


Embedding dependencies in ChangeLog classes


This functionality is possible due to the fact that each ChangeLog class itself is a regular bean:


 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Component public @interface ChangeLog { } 

It is worth noting that you cannot inject bins that have dependencies on Mongo Data components, because they are not yet initialized at the time of the migrations.


The source code for the library is available on Github .


')

Source: https://habr.com/ru/post/451798/


All Articles