SpringBoot学习笔记25——Mybatis多数据源配置

news/2024/7/5 2:28:21 标签: 数据源, mybatis

       本来是半个月之前就要写这篇博客的,结果临时有事一下给忘记了,现在补上。由于时间比较长了,如果有哪些地方写的不清楚的,可以在评论指出,博主会第一时间来修改完善博客内容。

我今天记录的是在已经使用oracle数据库的情况下,添加mysql的数据源。话不多说直接上代码。

1.首先我们需要先写一下配置文件的内容,在数据源配置中,添加mysql的配置。

#Oracle数据库,这部分是原有配置
spring.datasource.url = jdbc:oracle:thin:@//localhost:9290/ADC
spring.datasource.username = 123
spring.datasource.password = 123

spring.datasource.type = com.alibaba.druid.pool.DruidDataSource

#Mysql数据库,这部分是添加的mysql的配置
spring.datasource.mysql.url = jdbc:mysql://localhost:3306/jhmon?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.mysql.username = root
spring.datasource.mysql.password = 123

spring.datasource.mysql.driver-class-name=com.mysql.jdbc.Driver

2.配置mysql数据源

oracle数据源配置不需要改动,为了方便大家还是贴出来吧

package com.adc.da.main.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Druid的DataResource配置类
 * 凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,
 * 获取到系统环境变量和application配置文件中的变量。 还有一种方式是采用注解的方式获取 @value("${变量的key值}")
 */
@Configuration
@MapperScan(basePackages = "com.adc.da.**.dao", sqlSessionFactoryRef = "cagdsSqlSessionFactory")
public class DruidDataSourceConfig implements EnvironmentAware {

    @Value("${mybatis.mapper-locations}")
    private String mappingLocation;

    private RelaxedPropertyResolver propertyResolver;

    @Override
    public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
    }

    @Bean(name = "oracleDataSource")
    @Primary
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(propertyResolver.getProperty("url"));
        datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
        datasource.setUsername(propertyResolver.getProperty("username"));
        datasource.setPassword(propertyResolver.getProperty("password"));
        datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize")));
        datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle")));
        datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait")));
        datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive")));
        datasource.setMinEvictableIdleTimeMillis(
                Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
        try {
            datasource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        // initParameters.put("loginUsername", "druid");// 用户名
        // initParameters.put("loginPassword", "druid");// 密码
        initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
        initParameters.put("allow", "127.0.0.1"); // IP白名单 (没有配置或者为空,则允许所有访问)
        // initParameters.put("deny", "192.168.20.38");// IP黑名单
        // (存在共同时,deny优先于allow)
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    // 按照BeanId来拦截配置 用来bean的监控
    @Bean(value = "druid-stat-interceptor")
    public DruidStatInterceptor druidstatinterceptor() {
        return new DruidStatInterceptor();
    }

    @Bean
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        beanNameAutoProxyCreator.setProxyTargetClass(true);
        // 设置要监控的bean的id
        beanNameAutoProxyCreator.setInterceptorNames("druid-stat-interceptor");
        return beanNameAutoProxyCreator;
    }


    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager cagdsTransactionManager(
            @Qualifier("oracleDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "cagdsSqlSessionFactory")
    @Primary
    public SqlSessionFactory cagdsSqlSessionFactory(
            @Qualifier("oracleDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(mappingLocation));
        return sessionFactory.getObject();
    }

    @Bean(name = "cagdsJdbcTemplate")
    @Primary
    public JdbcTemplate cagdsJdbcTemplate(@Qualifier("oracleDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}

下面是添加的mysql数据源的配置

package com.adc.da.main.config;

import com.alibaba.druid.pool.DruidDataSource;
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.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Druid的DataResource配置类
 * 凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,
 * 获取到系统环境变量和application配置文件中的变量。 还有一种方式是采用注解的方式获取 @value("${变量的key值}")
 */
@Configuration
@MapperScan(basePackages = "com.adc.signal.dao", sqlSessionFactoryRef = "sessionFactoryMysql")
public class MybatisMysqlConfig implements EnvironmentAware {

    @Value("${mybatis.mapper-locations}")
    private String mappingLocation;

    @Value("${spring.datasource.mysql.url}")
    private String url;
    @Value("${spring.datasource.mysql.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.mysql.username}")
    private String username;
    @Value("${spring.datasource.mysql.password}")
    private String password;

    private RelaxedPropertyResolver propertyResolver;



    @Override
    public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
    }

    @Bean(name = "dataSourceMysql")
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(url);
        datasource.setDriverClassName(driverClassName);
        datasource.setUsername(username);
        datasource.setPassword(password);


        datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize")));
        datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle")));
        datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait")));
        datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive")));
        datasource.setMinEvictableIdleTimeMillis(
                Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
        try {
            datasource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }

    @Bean(name = "transactionManagerMysql")
    public DataSourceTransactionManager cagdsTransactionManager(
            @Qualifier("dataSourceMysql") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sessionFactoryMysql")
    public SqlSessionFactory sessionFactoryMysql(
            @Qualifier("dataSourceMysql") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(mappingLocation));
        return sessionFactory.getObject();
    }

    @Bean(name = "jdbcTemplateMysql")
    public JdbcTemplate cagdsJdbcTemplate(@Qualifier("dataSourceMysql") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}

这块需要注意的一点是:类注解中的两个数据源配置的扫描的包名不能有冲突,如果两个包名之间又交集的话就会出现问题,博主在这里就被坑了一下。

@MapperScan(basePackages = "com.adc.da.**.dao", sqlSessionFactoryRef = "cagdsSqlSessionFactory")

@MapperScan(basePackages = "com.adc.signal.dao", sqlSessionFactoryRef = "sessionFactoryMysql")

 

3.最后一步需要去掉启动类中的相关数据源注解例如:@MapperScan注解

 

 

 

 

 


http://www.niftyadmin.cn/n/860594.html

相关文章

Java中线程顺序执行解析

这篇文章给大家介绍Java中线程顺序执行解析&#xff0c;内容非常详细&#xff0c;感兴趣的小伙伴们可以参考借鉴&#xff0c;希望对大家能有所帮助。 线程的执行顺序是不确定的 调用Thread的start()方法启动线程时&#xff0c;线程的执行顺序是不确定的。也就是说&#xff0c;…

使用Nginx做RTMP直播服务器

今天来简单记录一下nginx来配置一个RTMP服务器的过程&#xff0c;实际特别简单&#xff0c;我们使用的是集成好的解压版软件&#xff0c;下载地址如下&#xff1a; https://download.csdn.net/download/lp840312696/11829426 解压出来将文件夹放到D盘根目录下 双击nginx.exe即…

Spring @Valid @Validated实现验证的方法

小编给大家分享一下Spring Valid Validated实现验证的方法&#xff0c;相信大部分人都还不怎么了解&#xff0c;因此分享这篇文章给大家参考一下&#xff0c;希望大家阅读完这篇文章后大有收获&#xff0c;下面让我们一起去了解一下吧&#xff01; 对于属性的验证有如下一些注…

Netty实战学习笔记01——简单Echo服务器编写

十一假期以过去一大半&#xff0c;本来是计划每天一篇学习记录进行更新的&#xff0c;结果今天才开始写第一篇博文。这就是为什么我还是一个菜鸟的原因。既然不能每天进步一点&#xff0c;那么就每周进步一点&#xff01; 最近博主新入手一本《Netty实战》&#xff0c;从今天开…

java实现递归菜单树

本文实例为大家分享了java实现递归菜单树的具体代码&#xff0c;供大家参考&#xff0c;具体内容如下 1.表结构 SET FOREIGN_KEY_CHECKS0;-- ---------------------------- -- Table structure for menu -- ---------------------------- DROP TABLE IF EXISTS menu; CREATE …

Netty实战学习笔记02——简单Echo客户端编写

今天来继续记录Echo的下半部分&#xff0c;Echo客户端的编写。 这里我们需要简单介绍一下我们所需要做的内容&#xff1a; 为初始出啊客户端&#xff0c;创建一个Bootstarp实例&#xff1b;为进行事件处理分配一个NIOEventLoopGroup实例&#xff0c;其中事件处理包括创建新的…

Git怎么配置别名

这篇文章主要介绍“Git怎么配置别名”&#xff0c;在日常操作中&#xff0c;相信很多人在Git怎么配置别名问题上存在疑惑&#xff0c;小编查阅了各式资料&#xff0c;整理出简单好用的操作方法&#xff0c;希望对大家解答”Git怎么配置别名”的疑惑有所帮助&#xff01;接下来&…

Java基础学习03——通过继承Comparable方法实现排序

今天来记录一下一个知识点&#xff0c;学了这个功能点之后就可轻松的将对象进行排序了。 只需要实现Comparable接口即可通过Collections.sort()方法进行排序了。 示例代码如下&#xff1a; package com.youyou.util;import lombok.Data;import java.util.ArrayList; import …