9、SpringBoot-mybatis-druid多源数据多源数据

系列导航

springBoot项目打jar包

1、springboot工程新建(单模块)

2、springboot创建多模块工程

3、springboot连接数据库

4、SpringBoot连接数据库引入druid

5、SpringBoot连接数据库引入mybatis

6、SpringBoot-mybatis分页实现pagehelper

7、SpringBoot-mybatis-plus引入

8、SpringBoot 事务

9、SpringBoot-mybatis-druid多源数据多源数据

10、SpringBoot-mybatis-plus-druid多源数据

11、SpringBoot-mybatis-plus-druid多源数据事务

12、SpringBoot-mybatis-plus-ehcache

13、SpringBoot-配置文件里密码加密

14、SpringBoot-easyexcel导出excle

完结

当一个mybatis工程中想操作多个数据库的时候就需要配置多数据源的工程,这里分享一个例子

1数据库中创建表

zy数据库:

CREATE TABLE TEST_BLOCK_T   
(
  BLOCK_ID         VARCHAR2(10 BYTE) PRIMARY   KEY,    --编码
  BLOCK_NAME       VARCHAR2(200 BYTE)                    --资源名称 
); 
 Insert into TEST_BLOCK_T (BLOCK_ID, BLOCK_NAME) Values ('1', 'java');
COMMIT;

yc数据库:

CREATE TABLE TEST_USER_T   
(
  USER_ID         VARCHAR2(10 BYTE) PRIMARY   KEY,     
  NAME            VARCHAR2(200 BYTE)                      
);
Insert into TEST_USER_T (USER_ID, NAME) Values ('1', '张三');
COMMIT;

2、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.1.17.RELEASE</spring-boot.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>

        <!-- oracle驱动 -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>

        <!-- 集成druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>


        <!-- 集成mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>




    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.17.RELEASE</version>
                <configuration>
                    <mainClass>com.example.demo.DemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>



</project>

3、 application.properties配置

# 应用名称
spring.application.name=demo
# 应用服务 WEB 访问端口
server.port=8080

# druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

#mybatis-plus控制台打印sql
mybatis-plus.configuration.log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

zy.datasource.username=zy
zy.datasource.password=1
zy.datasource.url=jdbc:oracle:thin:@192.168.0.100:1521:orcl
zy.datasource.driver-class-name=oracle.jdbc.OracleDriver

yc.datasource.username=yc
yc.datasource.password=1
yc.datasource.url=jdbc:oracle:thin:@192.168.0.100:1521:orcl
yc.datasource.driver-class-name=oracle.jdbc.OracleDriver

4、文件目录

 

 

5、源码

启动类

package com.example.demo;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;



@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

数据源yc配置类

这里注意指定扫描mapper和xml文件的路径

package com.example.demo.config;



import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;


@Configuration
@MapperScan(basePackages = YcDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "ycSqlSessionFactory")
public class YcDataSourceConfig {

    /**
     * 配置多数据源 关键就在这里 这里配置了不同的数据源扫描不同mapper
     */
    static final String PACKAGE = "com.example.demo.mapper.yc";
    static final String MAPPER_LOCATION = "classpath:mybatis/yc/mapper/*.xml";

    /**
     * 连接数据库信息 这个其实更好的是用配置中心完成
     */
    @Value("${yc.datasource.url}")
    private String url;

    @Value("${yc.datasource.username}")
    private String username;

    @Value("${yc.datasource.password}")
    private String password;

    @Value("${yc.datasource.driver-class-name}")
    private String driverClassName;

    @Bean("ycDataSource")
    public DataSource ycDataSource(){

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);

        return dataSource;
    }

    @Bean(name = "ycTransactionManager")
    public DataSourceTransactionManager ycTransactionManager() {
        return new DataSourceTransactionManager(ycDataSource());
    }

    @Bean(name = "ycSqlSessionFactory")
    public SqlSessionFactory ycSqlSessionFactory(@Qualifier("ycDataSource") DataSource ycDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(ycDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(YcDataSourceConfig.MAPPER_LOCATION));

        return sessionFactory.getObject();
    }



}

数据源zy配置类

这里注意指定扫描mapper和xml文件的路径

package com.example.demo.config;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;


@Configuration
@MapperScan(basePackages = ZyDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "zySqlSessionFactory")
public class ZyDataSourceConfig {

    /**
     * 配置多数据源 关键就在这里 这里配置了不同的数据源扫描不同mapper
     */
    static final String PACKAGE = "com.example.demo.mapper.zy";

    static final String MAPPER_LOCATION = "classpath:mybatis/zy/mapper/*.xml";
    /**
     * 连接数据库信息 这个其实更好的是用配置中心完成
     */
    @Value("${zy.datasource.url}")
    private String url;

    @Value("${zy.datasource.username}")
    private String username;

    @Value("${zy.datasource.password}")
    private String password;

    @Value("${zy.datasource.driver-class-name}")
    private String driverClassName;



    //    注解@Primary表示是主数据源
    @Bean("zyDataSource")
    @Primary
    public DataSource zyDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);

        return dataSource;
    }

    //设置登录druid监控的用户名和密码
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // IP黑名单(共同存在时,deny优先于allow)
//        servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }



    @Bean(name = "zyTransactionManager")
    @Primary
    public DataSourceTransactionManager zyTransactionManager() {
        return new DataSourceTransactionManager(zyDataSource());
    }

    @Bean(name = "zySqlSessionFactory")
    @Primary
    public SqlSessionFactory zySqlSessionFactory(@Qualifier("zyDataSource") DataSource zyDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(zyDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ZyDataSourceConfig.MAPPER_LOCATION));

        return sessionFactory.getObject();
    }
}

实体类User

package com.example.demo.domain.yc;

 
public class User {
    private static final long serialVersionUID = 1L;


    private String userId;
    /**
     * $field.comment。
     */
    private String name;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId='" + userId + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

实体类block

package com.example.demo.domain.zy;

 
public class Block {
    private static final long serialVersionUID = 1L;


    private String blockId;
    /**
     * $field.comment。
     */
    private String blockName;

    public String getBlockId() {
        return blockId;
    }

    public void setBlockId(String blockId) {
        this.blockId = blockId;
    }

    public String getBlockName() {
        return blockName;
    }

    public void setBlockName(String blockName) {
        this.blockName = blockName;
    }

    @Override
    public String toString() {
        return "XyDicBlockT{" +
                "blockId='" + blockId + '\'' +
                ", blockName='" + blockName + '\'' +
                '}';
    }
}

mapper类

package com.example.demo.mapper.yc;


import com.example.demo.domain.yc.User;


public interface UserMapper {
    // 对应xml映射文件元素的ID
    User selectByPrimaryKey(String userId);
}
package com.example.demo.mapper.zy;


import com.example.demo.domain.zy.Block;

public interface BlockMapper  {
    // 对应xml映射文件元素的ID
    Block selectByPrimaryKey(String blockId);
}

service类

package com.example.demo.service;


import com.example.demo.mapper.yc.UserMapper;
import com.example.demo.mapper.zy.BlockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ManySourceService {


    @Autowired
    BlockMapper BlockMapper;

    @Autowired
    UserMapper userMapper;

    //获取zy库中的block中的数据
    public String getZyBlock() {
        return  BlockMapper.selectByPrimaryKey("1").toString();
    }


    //获取yc库中的user中的数据
    public String getYcUser() {
        return  userMapper.selectByPrimaryKey("1").toString() ;
    }



}

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.yc.UserMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.domain.yc.User">
        <result property="userId" column="USER_ID"/>
        <result property="name" column="NAME"/>
    </resultMap>

    <sql id="Base_Column_List">
        USER_ID,NAME
    </sql>
    <select id="selectByPrimaryKey" parameterType="String"  resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from TEST_USER_T
        where USER_ID =  #{userId,jdbcType=VARCHAR}
    </select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.zy.BlockMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.domain.zy.Block">
        <result property="blockId" column="block_Id"/>
        <result property="blockName" column="block_Name"/>
    </resultMap>

    <sql id="Base_Column_List">
        block_id,block_name
    </sql>
    <select id="selectByPrimaryKey" parameterType="String"  resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from TEST_BLOCK_T
        where block_Id = #{blockId,jdbcType=VARCHAR}
    </select>
</mapper>

6、启动项目访问项目

(1)访问http://localhost:8080/hello/getZyBlock 成功取到zy库里的数据

 

 

 

(2)访问http://localhost:8080/hello/getYcUser 成功取到yc库里的数据

 

 

(3)查看druid的数据源信息

先要执行一下上面两个请求这个页面才能出来(估计是不执行以上请求连接池里没有数据)

浏览器输入:http://localhost:8080/druid/

 

上下拖动发现有两个数据源

 

 

posted @ 2022-04-14 17:57  万笑佛  阅读(255)  评论(0编辑  收藏  举报