springboot连接多个数据库test(MySQL+SQL server)

1. 引入jar包

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

附加:

sqlserver和mysql的jar包

        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.32</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency>

mybatis-plus的jar包

        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

Lombok

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>

完整pom

<?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 https://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.7.10-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.myf</groupId>
    <artifactId>demo20230317</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo20230317</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.32</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </pluginRepository>
    </pluginRepositories>

</project>

2. 修改配置文件

2.1 修改之前

spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: 123456
        url: jdbc:mysql://localhost:3306/hrdata?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
        username: root

2.2 修改之后(可保存自己之前的配置,然后复制下面的修改一下)

server:
    port: 8088
spring:
    datasource:
        dynamic:
            primary: dm  #设置默认的数据源或者数据源组,默认值即为master
            strict: false  #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
            datasource:
                dm1:
                    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
                    url: jdbc:sqlserver://58.246.128.122:1433;DatabaseName=HuiSoft
                    username: sa
                    password: 123
                dm:
                    driver-class-name: com.mysql.cj.jdbc.Driver
                    url: jdbc:mysql://localhost:3306/hrdata?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
                    username: root
                    password: 123456


3. 在serviceImpl类中加@DS注解(可以加在类上,也可以加在方法上)

3.1 使用dm数据库(默认就是dm,不加也可)

3.2 使用dm1数据库

 

以下是一个使用Spring Boot配置多数据源的示例: 1. 创建两个数据库 我们将创建两个MySQL数据库:mydb1和mydb2。在每个数据库中,我们将创建一个表:user。 CREATE DATABASE mydb1; USE mydb1; CREATE TABLE user (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50)); CREATE DATABASE mydb2; USE mydb2; CREATE TABLE user (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50)); 2. 添加依赖 在pom.xml文件中添加以下依赖: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.4.5</version> </dependency> </dependencies> ``` 3. 配置数据源 在application.properties文件中添加以下配置: ``` # 数据源1 spring.datasource.one.url=jdbc:mysql://localhost:3306/mydb1?useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.one.username=root spring.datasource.one.password=root spring.datasource.one.driver-class-name=com.mysql.cj.jdbc.Driver # 数据源2 spring.datasource.two.url=jdbc:mysql://localhost:3306/mydb2?useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.two.username=root spring.datasource.two.password=root spring.datasource.two.driver-class-name=com.mysql.cj.jdbc.Driver ``` 4. 配置JPA 在application.properties文件中添加以下配置: ``` # JPA配置1 spring.jpa.one.database=default spring.jpa.one.show-sql=true spring.jpa.one.hibernate.ddl-auto=update # JPA配置2 spring.jpa.two.database=default spring.jpa.two.show-sql=true spring.jpa.two.hibernate.ddl-auto=update ``` 5. 创建实体类 在src/main/java目录下创建两个实体类:User1和User2,分别对应mydb1和mydb2数据库中的user表。 User1.java: ``` @Entity @Table(name="user") public class User1 { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; // getter和setter方法 } ``` User2.java: ``` @Entity @Table(name="user") public class User2 { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; // getter和setter方法 } ``` 6. 创建Repository 在src/main/java目录下创建两个Repository接口:User1Repository和User2Repository,分别对应mydb1和mydb2数据库中的user表。 User1Repository.java: ``` @Repository public interface User1Repository extends JpaRepository<User1, Integer> { } ``` User2Repository.java: ``` @Repository public interface User2Repository extends JpaRepository<User2, Integer> { } ``` 7. 创建Service 在src/main/java目录下创建两个Service类:User1Service和User2Service,分别对应mydb1和mydb2数据库中的user表。 User1Service.java: ``` @Service public class User1Service { @Autowired private User1Repository user1Repository; // 方法1:获取所有用户 public List<User1> getAllUsers() { return user1Repository.findAll(); } // 方法2:添加一个用户 public void addUser(User1 user) { user1Repository.save(user); } } ``` User2Service.java: ``` @Service public class User2Service { @Autowired private User2Repository user2Repository; // 方法1:获取所有用户 public List<User2> getAllUsers() { return user2Repository.findAll(); } // 方法2:添加一个用户 public void addUser(User2 user) { user2Repository.save(user); } } ``` 8. 测试 在src/test/java目录下创建一个测试类:MultiDataSourceTest。 MultiDataSourceTest.java: ``` @SpringBootTest public class MultiDataSourceTest { @Autowired private User1Service user1Service; @Autowired private User2Service user2Service; // 测试方法1:添加一个用户到mydb1数据库的user表中 @Test public void testAddUser1() { User1 user = new User1(); user.setName("张三"); user1Service.addUser(user); } // 测试方法2:添加一个用户到mydb2数据库的user表中 @Test public void testAddUser2() { User2 user = new User2(); user.setName("李四"); user2Service.addUser(user); } // 测试方法3:获取mydb1数据库中user表中的所有用户 @Test public void testGetAllUsers1() { List<User1> users = user1Service.getAllUsers(); for (User1 user : users) { System.out.println(user.getName()); } } // 测试方法4:获取mydb2数据库中user表中的所有用户 @Test public void testGetAllUsers2() { List<User2> users = user2Service.getAllUsers(); for (User2 user : users) { System.out.println(user.getName()); } } } ``` 运行测试类,可以看到输出的结果: ``` 张三 李四 ``` 这表明我们已经成功地配置了多个数据源,并使用JPA和Repository来访问它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值