Boot连接Mysql和MongoDb

Boot连接Mysql和MongoDb

本文介绍了Spring Boot连接Mysql和MongoDb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

可以这样做.您将为不同的数据源创建不同的配置.此链接上有很好的例子 http://www.baeldung.com/spring-data-jpa-multiple-databases

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

另一个有用的stackoverflow问题: Spring Boot配置和使用两个数据源

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

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

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 /

我创建了这个示例,合并了上面的两个示例

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

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

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

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

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

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

这篇关于Spring Boot连接Mysql和MongoDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 23:38