SpringBoot + MyBatis配置连接MySQL、SQL Server、Oracle数据库

17 篇文章 0 订阅


本文主要供博主参考使用:如需要更详细的内容,请联系博主!
源码:https://gitee.com/XiMuQi/转储项目

一、项目环境配置

1.1 JDK8

1.2 SpringBoot版本:2.3.4.RELEASE

1.3 pom中主要的Maven依赖:

(1)starter-web

		<!-- web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

(2)jackson-databind

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.3</version>
		</dependency>

(3)mybatis

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.3</version>
		</dependency>

(4)alibaba 数据连接池

		<!-- alibaba 数据连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.13</version>
		</dependency>

(5)mysql 驱动

		<!-- mysql 驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

(6)sqlserver 驱动

		<!-- sqlserver 驱动 -->
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>mssql-jdbc</artifactId>
			<version>7.4.1.jre8</version>
			<scope>runtime</scope>
		</dependency>

(7)Oracle数据库驱动

		<!-- Oracle数据库驱动 -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.4.0</version>
		</dependency>

(8)lombok主要用来记录日志

		<!-- lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

(9)tomcat

		<!-- tomcat -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>

二、配置

2.1 application.properties配置文件

server.port= 9000
server.servlet.context-path= /multiDatabase

#mybatis
mybatis.mapper-locations=classpath:mapper/*/*.xml
#将扫描到的mapper.xml显示在控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

#MaBatis在控制台打印执行的SQL语句 注意其中dump.xxx.xxxx.dao是Dao层的包名,注意不是XML文件的包名=日志等级
logging.level.dump.xxx.xxxx.dao=debug

#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/MySQL数据库名?useUnicode=true&characterEncoding=utf8&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8
#spring.datasource.username=root
#spring.datasource.password=root


#################################  多数据源配置  #########################################
#参考:https://www.cnblogs.com/viwofer/p/13149863.html (Oracle数据源的配置使用默认的即可)
#如果同时配置了MySQL和SqlServer的数据源,并同时启动MySQL和SqlServer的数据源配置,注意是两个数据源的都同时启动,可能会出现如下错误并给出提示信息:
#错误:Field transactionManager in dump.pspaceTodb.base.aspect.TransactionAdviceConfig required a single bean, but 2 were found:
#提示信息:Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

#问题的原因:MySQL和SqlServer数据库的配置类没有分主次,所以导致启动失败;
#解决方法:在MySQL或SqlServer配置类的每个方法上都加上@Primary,注意只能在其中一个数据源上添加@Primary注解,在加了@Primary注解的配置类上,
# 执行的sql也会优先使用加了@Primary注解的配置类,所以数据只会优先出现在有@Primary注解对应的数据库中;

#MySQL数据库连接配置
spring.datasource.mysql.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.mysql.driver-class-name=com.mysql.cj.jdbc.Driver
#注意是jdbc-url不是url,否则报jdbcUrl is required with driverClassName错误
spring.datasource.mysql.jdbc-url=jdbc:mysql://localhost:3306/mysql数据库名?useUnicode=true&characterEncoding=utf8&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8
spring.datasource.mysql.username=root
spring.datasource.mysql.password=root

#SqlServer数据库连接配置
spring.datasource.mssql.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.mssql.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
#注意是jdbc-url不是url,否则报jdbcUrl is required with driverClassName错误
spring.datasource.mssql.jdbc-url=jdbc:sqlserver://localhost:1433;databasename=SqlServer数据库名
spring.datasource.mssql.username=sa
spring.datasource.mssql.password=admin123

#Oracle数据库连接配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@192.168.18.200:1521:orcl
spring.datasource.username=root
spring.datasource.password=admin123

通过application.properties里的配置可以看出,项目默认的数据库配置是Oracle连接,所以在连接使用Oracle数据库时,需要把MySQL和SqlServer的 配置类 暂时注释掉,MySQL和SqlServer在application.properties里的配置信息不用注释。

2.2 dao、Mapper配置 省略

需要注意的是因为连接Oracle数据库是使用的SpringBoot默认的配置,所以需要在启动类上加上
@MapperScan扫描dao层接口

@MapperScan({"com.demo.test1.dao","com.demo.test2.dao"})

2.3 MySQL和SqlServer的数据源配置类

2.3.1 MySql数据源配置类

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;

import javax.sql.DataSource;

/**
 * MySql数据源配置类
 * @author chenlc
 * @created 2020-11-06 15:03
 */
@Configuration(value="mysql")
@MapperScan(basePackages = "com.demo.test1.dao", sqlSessionFactoryRef = "MysqlSqlSessionFactory")//此处@MapperScan扫的是dao层接口
public class MySqlDataSourceConfig {

    @Primary
    @Bean(name = "MysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource getDateSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置事务管理
     */
    @Primary
    @Bean(name = "MysqlTransactionManager")
    public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("MysqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 配置工厂
     * @param datasource
     * @return
     * @throws Exception
     */
    @Primary
    @Bean(name = "MysqlSqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("MysqlDataSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        //此处 classpath:mapper/*/*.xml 对应的是Mapper文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*/*.xml"));
        return bean.getObject();
    }

    /**
     * 配置会话
     * @param sessionFactory
     * @return
     */
    @Primary
    @Bean("MysqlSqlSessionTemplate")
    public SqlSessionTemplate mysqlSessionTemplate(@Qualifier("MysqlSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
}

2.3.2 SqlServer数据源配置类

配置同MySQL数据源配置类的差不多一致,区别如下:
(1)MySQL数据源配置类里每个方法上都加了@Primary

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;

import javax.sql.DataSource;

/**
 * SqlServer数据源配置类
 * @author chenlc
 * @created 2020-11-06 15:05
 */
@Configuration(value = "mssql")
@MapperScan(basePackages = "com.demo.test1.dao", sqlSessionFactoryRef = "MssqlSqlSessionFactory")
public class SqlServerDataSourceConfig {
    /**
     * 配置数据源
     * @return
     */
    @Bean(name = "MssqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mssql")
    public DataSource getDateSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置事务管理
     */
    @Bean(name = "MssqlTransactionManager")
    public DataSourceTransactionManager mssqlTransactionManager(@Qualifier("MssqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 配置工厂
     * @param datasource
     * @return
     * @throws Exception
     */
    @Bean(name = "MssqlSqlSessionFactory")
    public SqlSessionFactory mssqlSqlSessionFactory(@Qualifier("MssqlDataSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*/*.xml"));
        return bean.getObject();
    }

    /**
     * 配置会话
     * @param sessionFactory
     * @return
     */
    @Bean("MssqlSqlSessionTemplate")
    public SqlSessionTemplate mssqlSqlsessionTemplate(@Qualifier("MssqlSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
}

2.4 注意因为在自定义的MySQL或SqlServer数据库连接配置中已经指定了对应的Dao层接口和Mapper文件所在地址,所以在使用自定义的MySQL或SqlServer数据库连接配置时,就不需要在启动类上加

@MapperScan({"com.demo.test1.dao","com.demo.test2.dao"})

2.5 SpringBoot对三种数据库的连接是互斥的,在使用时只能使用一种数据库配置。

三、MySQL、SqlServer和Oracle的SQL批量新增语句

Oracle数据库的批量新增SQL和(MySQL和SqlServer)的SQL语法不一样,下面是Oracle在MyBatis里的批量新增语句示例:

    <!--批量新增点(Oracle数据库方式)-->
    <insert id="insertBatchOracle">
        INSERT ALL
        <foreach collection="list" item="point" index="index">
            INTO tb_point (mid, name, full_name, point_type, parent_id, id, data_type, description, security_zone) VALUES
            (#{point.mId}, #{point.name}, #{point.fullName}, #{point.pointType}, #{point.parentId}, #{point.id},
            #{point.dataType}, #{point.description}, #{point.securityZone})
        </foreach>
        select 1 from dual
    </insert>
  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值