16

I have a problem with Spring Boot application. I want to connect a MongoDB database and a MySql database in my Spring boot application. I would to know if it is possible, in positive case How I can make this multiple connection. I had made a try based on an example with Mysql and Post without success. So I'm wondering if someone have an easy example to know the method. thanks

asked Jun 12, 2017 at 19:55
1
  • Hii, have you succeeded in connecting both MySQL and MongoDb to your springboot project? Commented Oct 4, 2020 at 11:54

3 Answers 3

14

It is possible to do this.you will have create different configuration for different datasources. This link has good examples on that http://www.baeldung.com/spring-data-jpa-multiple-databases

Another useful stackoverflow question: Spring Boot Configure and Use Two DataSources

To get started with mongo and mysql , you can follow example from spring.io guides.

https://spring.io/guides/gs/accessing-data-mongodb/

https://spring.io/guides/gs/accessing-data-mysql/

EDIT :

I have created this one example, merging two samples above

package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import hello.model.Customer;
import hello.model.User;
import hello.mongodao.CustomerRepository;
import hello.mysqldao.UserRepository;
@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
@EnableJpaRepositories (basePackageClasses = UserRepository.class)
@SpringBootApplication
public class Application implements CommandLineRunner {
 @Autowired
 private CustomerRepository repository;
 @Autowired
 private UserRepository userRepository;
 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }
 @Override
 public void run(String... args) throws Exception {
 System.out.println("getting data from Mongo");
 repository.deleteAll();
 // save a couple of customers
 repository.save(new Customer("Alice", "Smith"));
 repository.save(new Customer("Bob", "Smith"));
 // fetch all customers
 System.out.println("Customers found with findAll():");
 System.out.println("-------------------------------");
 for (Customer customer : repository.findAll()) {
 System.out.println(customer);
 }
 System.out.println();
 // fetch an individual customer
 System.out.println("Customer found with findByFirstName('Alice'):");
 System.out.println("--------------------------------");
 System.out.println(repository.findByFirstName("Alice"));
 System.out.println("Customers found with findByLastName('Smith'):");
 System.out.println("--------------------------------");
 for (Customer customer : repository.findByLastName("Smith")) {
 System.out.println(customer);
 }
 System.out.println("gettting data from mysql");
 userRepository.deleteAll();
 // save a couple of customers
 userRepository.save(new User("Alice", "[email protected]"));
 userRepository.save(new User("Bob", "[email protected]"));
 // fetch all customers
 System.out.println("Users found with findAll():");
 System.out.println("-------------------------------");
 for (User user : userRepository.findAll()) {
 System.out.println(user);
 }
 }
}

CustomerRepository.java

package hello.mongodao;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import hello.model.Customer;
public interface CustomerRepository extends MongoRepository<Customer, String> {
 public Customer findByFirstName(String firstName);
 public List<Customer> findByLastName(String lastName);
}

UserRepository.java

package hello.mysqldao;
import org.springframework.data.repository.CrudRepository;
import hello.model.User;
// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Long> {
}

Customer.java

package hello.model;
import org.springframework.data.annotation.Id;
public class Customer {
 @Id
 public String id;
 public String firstName;
 public String lastName;
 public Customer() {}
 public Customer(String firstName, String lastName) {
 this.firstName = firstName;
 this.lastName = lastName;
 }
 @Override
 public String toString() {
 return String.format(
 "Customer[id=%s, firstName='%s', lastName='%s']",
 id, firstName, lastName);
 }
}

User.java

package hello.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity // This tells Hibernate to make a table out of this class
public class User {
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private Integer id;
 private String name;
 private String email;
public User() {
 // TODO Auto-generated constructor stub
}
 public User(String string, String string2) {
 // TODO Auto-generated constructor stub
 name = string;
 email = string2;
 }
 public Integer getId() {
 return id;
 }
 public void setId(Integer id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getEmail() {
 return email;
 }
 public void setEmail(String email) {
 this.email = email;
 }
 @Override
 public String toString() {
 return String.format(
 "User[id=%s, name='%s', email='%s']",
 id, name, email);
 }
}

application.properties

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.data.mongodb.uri=mongodb://localhost:27017/local
answered Jun 12, 2017 at 20:37
Sign up to request clarification or add additional context in comments.

4 Comments

I want to use two mongodb databse, in my application.properties: spring.data.mongodb.uri=mongodb://username:password@localhost:27017/databasename, when I want to use another mongodb databse, should I add another same application.properties ? and how I distinguish it when I use it?
that's helped me much: ignoring of parametrization of @EnableJpa/MongoRepositories or even one of them cause the strange non-clear errors on beans initialization.
I tried this but i get this message: The bean 'userMigrationDataRepository', defined in UserMigrationDataRepository defined in EnableJpaRepositories declared on UsersApplication, could not be registered. A bean with that name has already been defined in UserMigrationDataRepository defined in EnableMongoRepositories declared on UsersApplication and overriding is disabled.
@CarlosAndres Add two packages in your repository package(one for mongo and another one for mysql. Move all your repositories of Mongo to mongo package and all your mysql repositories to mysql package. Then add this in you main class: @EnableMongoRepositories(basePackages = {"com.yourpackagename.repository.mongo"})
10

You really don't need to make additional config and property files because MongoDB has different property names than sql so all you will need is an application.properties file

application.properties

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/dbName?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=
spring.data.mongodb.uri=mongodb://localhost:27017
spring.data.mongodb.database=dbName

example models

MongoDB document

import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Id;
 @Document("Gyros")
 public class Gyros {
 
 public Gyros(String description) {
 this.description = description;
 }
 
 @Id
 public String id;
 
 public String description;
 }

Mysql JPA entity

import javax.persistence.*;
@Entity
@Table(name = "Kebab")
public class Kebab {
 public Kebab(String description) {
 this.description = description;
 }
 public Kebab() {
 }
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 public int id;
 public String description;
}

MongoDB repository

@Repository
public interface GyrosRepository extends MongoRepository<Gyros, String> {
}

Mysql Jpa repository

 @Repository
 public interface KebabRepository extends JpaRepository<Kebab, Integer> {
 }

TestService

@org.springframework.stereotype.Service
public class Service {
 private final GyrosRepository gyrosRepository;
 private final KebabRepository kebabRepository;
 @Autowired
 public Service(GyrosRepository gyrosRepository, KebabRepository kebabRepository) {
 this.gyrosRepository = gyrosRepository;
 this.kebabRepository = kebabRepository;
 }
 @PostConstruct
 void test() {
 this.gyrosRepository.insert(new Gyros("ham ham"));
 this.kebabRepository.saveAndFlush(new Kebab("yum yum"));
 }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.2.2.RELEASE</version>
 <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>org.example</groupId>
 <artifactId>stack</artifactId>
 <version>1.0-SNAPSHOT</version>
 <name>stackoverflow</name>
 <dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <scope>runtime</scope>
 </dependency>
 </dependencies>
</project>
answered Nov 14, 2020 at 1:08

1 Comment

Your solution works! I'm wondering, how did you get rid of this warning on starting the application: Spring Data JPA - Could not safely identify store assignment for repository candidate interface 'repository' If you want this repository to be a JPA repository, consider annotating your entities with one of these ...
3

I also faced the same kind of problem once. I had to connect my spring boot application to two different databases. One was Mongo db and other was Postgres db.

You can see that i have used both JPA as well as spring-boot-starter-data-mongodb. Still my project is running absolutely fine.Hope for you also it work successfully. There are suggestions over the internet to not use JPA but i am not able to use JPA repository without include JPA.

Here I am posting the solution which worked for me.

Hope it helps someone:

  1. application.properties file:

    MONGODB (MongoProperties)

    spring.data.mongodb.uri=mongodb://XX.XX.XX.XX:27017/testdb

    #POSTGRES properties
     spring.datasource.platform=postgres
     spring.datasource.url= jdbc:postgresql://localhost:5432/database_name 
     spring.datasource.username=postgres_usr_name
     spring.datasource.password=postgres_pwd
     spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
    
  2. My pom dependencies:

    <dependencies>
    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency> 
    <dependency>
     <groupId>org.postgresql</groupId>
     <artifactId>postgresql</artifactId>
    </dependency> 
    <dependency>
     <groupId>org.mongodb</groupId>
     <artifactId>mongo-java-driver</artifactId>
    </dependency> 
    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    
  3. To access my data Using Repositories:

    (i): MONGO REPOSITORY

     import org.springframework.data.mongodb.repository.MongoRepository;
     public interface MRepositories extends MongoRepository<YourEntityClass, String>{
     }
    

    (ii): JPA repository

    @Repository public interface PostGresRepo extends JpaRepository<TestEntity,Long> {}
    
answered May 16, 2019 at 12:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.