Skip to content
Advertisement

Is it possible to use MongoDb and PostgreSql for same model in Spring boot?

I have built a User management service in which I’m using MongoDb (spring data). I have two models User and Role.

JavaScript

Role model –

JavaScript

and Role enumerator-

JavaScript

In User there is a role attribute which I have @Dbref to role collection. My problem is that I want to have a option of using PostgreSql and MongoDb in the same application for these Models. I have implemented this for MongoDb but I’m not sure how to go about doing this for postgreSql in the same application as an option. One way I think is to have a interface User and role and build two different classes for User_mongo model and User_postgre entity(same way for role). I’m stuck here, and I tried to do certain research but most of the time I find tutorials that have separate databases of same type(Both PostgreSql databases). Any direction is highly appreciated. PS I’m new to spring boot and Java.

My AddUser Controller that Uses Mongorepository as of now

JavaScript

Advertisement

Answer

I would use the @ConditonalOnProperty annotation here on two configs(one for Mongo and one for PostgerSql), and add the enabled config-property at runtime(For the config you want it’s beens to load)

Here is a simplified example.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement