Spring Boot 同时连接 MongoDB 和 MySQL

Spring Boot 是一个开源的 Java 框架,它简化了基于 Spring 应用程序的创建和部署过程。在许多现代应用程序中,我们经常需要同时使用 MongoDB 和 MySQL 数据库。本文将介绍如何在 Spring Boot 应用程序中同时连接这两种数据库。

1. 添加依赖

首先,我们需要在 pom.xml 文件中添加 MongoDB 和 MySQL 的依赖项。

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Starter Data MongoDB -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- Spring Boot Starter Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

2. 配置数据库连接

接下来,我们需要在 application.propertiesapplication.yml 文件中配置 MongoDB 和 MySQL 的连接信息。

# MongoDB
spring.data.mongodb.uri=mongodb://localhost:27017/mydb

# MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

3. 创建实体类和仓库

现在,我们可以创建一些实体类和仓库来操作 MongoDB 和 MySQL 数据库。

// MongoDB Entity
@Document(collection = "users")
public class User {
    @Id
    private String id;
    private String name;
    private int age;

    // Getters and Setters
}

// MongoDB Repository
public interface UserRepository extends MongoRepository<User, String> {
}

// MySQL Entity
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    // Getters and Setters
}

// MySQL Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}

4. 服务层

在服务层中,我们可以注入这些仓库并使用它们来执行数据库操作。

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User createUser(User user) {
        return userRepository.save(user);
    }
}

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public Product createProduct(Product product) {
        return productRepository.save(product);
    }
}

5. 控制器

最后,我们可以创建一个控制器来处理 HTTP 请求。

@RestController
@RequestMapping("/api")
public class ApiController {
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;

    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User createdUser = userService.createUser(user);
        return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
    }

    @PostMapping("/products")
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        Product createdProduct = productService.createProduct(product);
        return new ResponseEntity<>(createdProduct, HttpStatus.CREATED);
    }
}

状态图

以下是 Spring Boot 应用程序连接 MongoDB 和 MySQL 的状态图:

stateDiagram-v2
    A[Spring Boot Application] --> B[MongoDB]
    A --> C[MySQL]
    B --> D[User Entity]
    C --> E[Product Entity]

结论

通过上述步骤,我们可以在 Spring Boot 应用程序中同时连接 MongoDB 和 MySQL 数据库。这使得我们可以利用这两种数据库的优势,为应用程序提供更灵活的数据存储和查询能力。希望本文能帮助你更好地理解和实现这一过程。