java springboot 配置多數據源 mysql sqlserver


注意事項   需要驅動導包 

druid的包和sqlserver的包為

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        <!--sqlserver驅動 -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency>

注意 mysql和sqlserver配置中有一點要做判斷

        if(driveClassName.equals("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
            //sqlserver數據庫要加這個
            datasource.setValidationQuery("select 'x'");
        }

 

開始 

導包 驅動呀 連接呀都得有

我展示我的

    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!-- aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.19.RELEASE</version>
        </dependency>

        <!-- mybatis plus 代碼生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 引入 redis 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        <!--sqlserver驅動 -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

 

接下來看配置 我直接加我的配置

server.port=8081

spring.datasource.demo.user.url = jdbc:mysql://localhost:3306/sqlpractice?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.demo.user.username = root
spring.datasource.demo.user.password = 123456
spring.datasource.demo.user.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.demo.server.url = jdbc:mysql://172.11.11.12:3306/sqltest?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.demo.server.username = root
spring.datasource.demo.server.password = 123456
spring.datasource.demo.server.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.demo.SqlServer.url=jdbc:sqlserver://localhost:1433;DatabaseName=aiwozhonghua;
spring.datasource.demo.SqlServer.username= sa
spring.datasource.demo.SqlServer.password= Aa1212121
spring.datasource.demo.SqlServer.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

#mapper-locations= classpath*:/com/example/demo/dao/*.xml

#mapper文件的路徑
mybatis.demo.server.mapper-location=classpath*:/com/example/demo/demo-user/*.xml
mybatis.demo.user.mapper-location=classpath*:/com/example/demo/demo-server/*.xml
mybatis.demo.SqlServer.mapper-location=classpath*:/com/example/demo/demo-sqlserver/*.xml

mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.auto-mapping-behavior=full
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.mapper-locations=classpath*:mapper/**/*Mapper.xml
mybatis-plus.global-config.db-config.logic-not-delete-value=1
mybatis-plus.global-config.db-config.logic-delete-value=0


############################################################
#
# REDIS 配置
#
############################################################
# Redis數據庫索引(默認為0)
spring.redis.database=1
# Redis服務器地址
spring.redis.host=localhost
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=1000
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=10
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=2
# 連接超時時間(毫秒)
spring.redis.timeout=0

上邊注意 配置的的不同

 

接下來加注解

一共三個注解 分別給三個庫用 mysql mysql sqlserver

package com.example.demo.interfaceAcc;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
@Mapper
public @interface DemoServerMapper {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    String value() default "";
}
package com.example.demo.interfaceAcc;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
@Mapper
public @interface DemoUserMapper {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    String value() default "";
}

 

package com.example.demo.interfaceAcc;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
@Mapper
public @interface DemoSqlServerMapper {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    String value() default "";
}

 

接下來這步非常重要 配置通用連接數據庫的配置

package com.example.demo.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;


public abstract class AbstractDbConfig {

    protected SqlSessionFactory sqlSessionFactory(DataSource dataSource, String mapperLocation) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        Resource[] resource= resourceResolver.getResources(mapperLocation);
        factoryBean.setMapperLocations(resource);
        return factoryBean.getObject();
    }

    protected DataSource dataSourceFactory(String driveClassName, String url, String userName, String password){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setDriverClassName(driveClassName);
        datasource.setUrl(url);
        datasource.setUsername(userName);
        datasource.setPassword(password);
        datasource.setMaxActive(20);
        datasource.setInitialSize(20);
        if(driveClassName.equals("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
            //sqlserver數據庫要加這個
            datasource.setValidationQuery("select 'x'");
        }
        return datasource;
    }
}

 

接來這一步就是 幾個庫分別 繼承上邊這個然后 實現連接等操作
我這是三個 就是 mysql mysql sqlserver
package com.example.demo.config;

import com.example.demo.interfaceAcc.DemoUserMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = {"com.example"},annotationClass = DemoUserMapper.class,
        sqlSessionTemplateRef = "demoUserTemplate")
public class DemoUserDbConfig extends AbstractDbConfig {

    @Value("${spring.datasource.demo.user.url}")
    private String url;

    @Value("${spring.datasource.demo.user.username}")
    private String userName;

    @Value("${spring.datasource.demo.user.password}")
    private String password;

    @Value("${spring.datasource.demo.user.driver-class-name}")
    private String driveClassName;

    @Value(value = "${mybatis.demo.user.mapper-location}")
    private String mapperLocation;


    @Bean(name = "demoUser")
    public DataSource secondaryDataSource() {
        return dataSourceFactory(driveClassName, url, userName, password);
    }

    @Bean(name = "demoUserTemplate")
    public SqlSessionTemplate demoUserSqlTemplate() throws Exception {
        return new SqlSessionTemplate((sqlSessionFactory(secondaryDataSource(), mapperLocation)));
    }

    @Bean
    @Qualifier("demoUserTransaction")
    public PlatformTransactionManager demoUserTransaction() {
        return new DataSourceTransactionManager(secondaryDataSource());
    }
}
package com.example.demo.config;

import com.example.demo.interfaceAcc.DemoServerMapper;
import com.example.demo.interfaceAcc.DemoUserMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.example"},annotationClass = DemoServerMapper.class,
        sqlSessionTemplateRef = "demoServerTemplate")
public class DemoServerDbConfig extends AbstractDbConfig {

    @Value("${spring.datasource.demo.server.url}")
    private String url;

    @Value("${spring.datasource.demo.server.username}")
    private String userName;

    @Value("${spring.datasource.demo.server.password}")
    private String password;

    @Value("${spring.datasource.demo.server.driver-class-name}")
    private String driveClassName;

    @Value(value = "${mybatis.demo.server.mapper-location}")
    private String mapperLocation;


    @Bean(name = "demoServer")
    public DataSource secondaryDataSource() {
        return dataSourceFactory(driveClassName, url, userName, password);
    }

    @Bean(name = "demoServerTemplate")
    public SqlSessionTemplate demoServerSqlTemplate() throws Exception {
        return new SqlSessionTemplate((sqlSessionFactory(secondaryDataSource(), mapperLocation)));
    }

    @Bean
    @Qualifier("demoServerTransaction")
    public PlatformTransactionManager demoServerTransaction() {
        return new DataSourceTransactionManager(secondaryDataSource());
    }
}
package com.example.demo.config;

import com.example.demo.interfaceAcc.DemoSqlServerMapper;
import com.example.demo.interfaceAcc.DemoUserMapper;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.example"},annotationClass = DemoSqlServerMapper.class,
        sqlSessionTemplateRef = "demoSqlServerTemplate")
public class DemoSqlServerDbConfig extends AbstractDbConfig {

    @Value("${spring.datasource.demo.SqlServer.url}")
    private String url;

    @Value("${spring.datasource.demo.SqlServer.username}")
    private String userName;

    @Value("${spring.datasource.demo.SqlServer.password}")
    private String password;

    @Value("${spring.datasource.demo.SqlServer.driver-class-name}")
    private String driveClassName;

    @Value(value = "${mybatis.demo.SqlServer.mapper-location}")
    private String mapperLocation;


    @Bean(name = "demoSqlServer")
    public DataSource secondaryDataSource() {
        return dataSourceFactory(driveClassName, url, userName, password);
    }

    @Bean(name = "demoSqlServerTemplate")
    public SqlSessionTemplate demoSqlServerSqlTemplate() throws Exception {
        return new SqlSessionTemplate((sqlSessionFactory(secondaryDataSource(), mapperLocation)));
    }

    @Bean
    @Qualifier("demoSqlServerTransaction")
    public PlatformTransactionManager demoSqlServerTransaction() {
        return new DataSourceTransactionManager(secondaryDataSource());
    }
}

 

目前配置都已完成 接下來的就是 使用  寫dao寫mapper

mysql sqlserver 這個簡單就只展示兩個了   這分別是.java  .xml要區分開哦

package com.example.demo.dao;

import com.example.demo.interfaceAcc.DemoUserMapper;

import java.util.List;

@DemoUserMapper
public interface UserDao {

List<SC> list();

}
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.dao.UserDao">

    <select id="list" resultType="com.example.demo.entity.SC">
        SELECT Sid as SId,Cid as CId FROM sc 
    </select>
</mapper>
package com.example.demo.dao;

import com.example.demo.entity.SysUseRole;
import com.example.demo.entity.TenantMst;
import com.example.demo.interfaceAcc.DemoSqlServerMapper;

import java.util.List;

@DemoSqlServerMapper
public interface SqlServerDao {

    List<SysUseRole> list();

}
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.dao.SqlServerDao">

    <select id="list" resultType="com.example.demo.entity.SC">
        SELECT id as SId from sys_user_role
    </select>
</mapper>

 

最后隨便寫一個Controller測試即可

    @GetMapping("/getMysql3")
    public String getMysql3() {
        List<SysUseRole> list = sqlServerDao.list();
        return String.valueOf(list);
    }

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM