【问题标题】:Spring Boot connect Mysql and MongoDbSpring Boot 连接 Mysql 和 MongoDb
【发布时间】:2017-11-14 10:01:43
【问题描述】:

我的 Spring Boot 应用程序有问题。我想在我的 Spring Boot 应用程序中连接一个 MongoDB 数据库和一个 MySql 数据库。我想知道是否有可能,在肯定的情况下,我如何建立这种多重连接。我曾根据 Mysql 和 Post 的示例进行了尝试,但没有成功。所以我想知道是否有人有一个简单的例子来了解该方法。 谢谢

【问题讨论】:

  • 您好,您成功将 MySQL 和 MongoDb 连接到您的 springboot 项目了吗?

标签: mysql mongodb spring-boot


【解决方案1】:

这是可能的。您将为不同的数据源创建不同的配置。这个链接有很好的例子 http://www.baeldung.com/spring-data-jpa-multiple-databases

另一个有用的stackoverflow问题:Spring Boot Configure and Use Two DataSources

要开始使用 mongo 和 mysql ,您可以按照 spring.io 指南中的示例进行操作。

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

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

编辑:

我已经创建了一个示例,合并了上面的两个示例

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", "Alice@Smith.com"));
        userRepository.save(new User("Bob", "Bob@Smith.com"));

        // 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> {

}

客户.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);
    }

}

用户.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

【讨论】:

  • 我想在我的 application.properties 中使用两个 mongodb 数据库:spring.data.mongodb.uri=mongodb://username:password@localhost:27017/databasename,当我想使用另一个 mongodb 数据库时,我应该添加另一个相同的 application.properties 吗?以及使用时如何区分?
  • 这对我帮助很大:忽略 @EnableJpa/MongoRepositories 的参数化,甚至其中一个都会导致 bean 初始化时出现奇怪的不清晰错误。
【解决方案2】:

您真的不需要制作额外的配置和属性文件,因为 MongoDB 的属性名称与 sql 不同,所以您只需要一个 application.properties 文件

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

示例模型

MongoDB 文档

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 实体

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
public interface GyrosRepository extends MongoRepository<Gyros, String> {
}

Mysql Jpa 仓库

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

测试服务

@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>

【讨论】:

    【解决方案3】:

    我也遇到过同样的问题。我必须将我的 Spring Boot 应用程序连接到两个不同的数据库。一个是 Mongo db,另一个是 Postgres db。

    你可以看到我同时使用了 JPA 和 spring-boot-starter-data-mongodb。我的项目仍然运行得很好。希望你也能成功。互联网上有不使用 JPA 的建议,但我无法在不包含 JPA 的情况下使用 JPA 存储库。

    我在这里发布对我有用的解决方案。

    希望对某人有所帮助:

    1. application.properties 文件:

      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. 我的 pom 依赖项:

      <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. 使用存储库访问我的数据:

      (i): MONGO 存储库

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

      (ii):JPA 存储库

      @Repository public interface PostGresRepo extends JpaRepository<TestEntity,Long> {}
      

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 2020-02-11
      • 2017-11-13
      • 2017-08-02
      • 1970-01-01
      • 2016-09-13
      • 2021-03-15
      • 2017-08-01
      • 1970-01-01
      相关资源
      最近更新 更多