1. 程式人生 > 其它 >9、SpringBoot-mybatis-druid多源資料多源資料

9、SpringBoot-mybatis-druid多源資料多源資料

系列導航

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多源資料多源資料

未完待續

當一個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/

 

上下拖動發現有兩個資料來源