首页 > 其他分享 >mybatis配置多数据源

mybatis配置多数据源

时间:2023-05-29 22:46:50浏览次数:44  
标签:数据源 配置 springframework public import mybatis org com annotation

yml中配置mybatis的日志输出信息


mybatis:
  # spring boot集成mybatis的方式打印sql
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

maven引入相关的配置

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

数据元的配置


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfiguration {

    //默认使用这个实体的DataSource
    @Primary
    @Bean("firstDataSource")
    public DataSource firstDataSource(){
        /**
         * <dependency>
         *             <groupId>com.alibaba</groupId>
         *             <artifactId>druid</artifactId>
         *             <version>1.1.10</version>
         *         </dependency>
         * */
        DruidDataSource oracleDataSource = new DruidDataSource();
        // oralce 数据库账户密码基础配置
        oracleDataSource.setUsername("CXK");
        oracleDataSource.setPassword("密码");
        oracleDataSource.setUrl("jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.5.143)(PORT = 49161)))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = helowin)))");
        oracleDataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        return oracleDataSource;
    }


    @Bean("secondDataSource")
    public DataSource secondDataSource(){
        /**
         * <dependency>
         *             <groupId>com.alibaba</groupId>
         *             <artifactId>druid</artifactId>
         *             <version>1.1.10</version>
         *         </dependency>
         * */
        DruidDataSource mysqlDataSource = new DruidDataSource();
        // oralce 数据库账户密码基础配置
        mysqlDataSource.setUsername("root");
        mysqlDataSource.setPassword("密码");
        mysqlDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/caoxuekun?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8");
        mysqlDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return mysqlDataSource;
    }
}

SqlSessionFactory的创建


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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration

@MapperScan(basePackages="com.moredatabase.mapper",sqlSessionFactoryRef="firstSqlSessionFactory")
public class FirstMybatisConfig {

    @Primary
    @Bean("firstSqlSessionFactory")
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource")DataSource dataSource)  {
        // 数据源设置
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //mapper的xml文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String locationPattern = "classpath:mapper/*.xml";
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources(locationPattern));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对应数据库的entity位置
//        String typeAliasesPackage = "com.moredatabase.mapper";
//        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        SqlSessionFactory sqlSessionFactory = null;
        try {
            sqlSessionFactory = sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }

}

第二个sqlSessionFactory实体的创建


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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@MapperScan(basePackages="com.moredatabase.mysql",sqlSessionFactoryRef="secondSqlSessionFactory")
public class SecondMybatisConfig {

    @Bean("secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource)  {

        SqlSessionFactory sqlSessionFactory = null;

        try{
            // 数据源设置
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource);
            //mapper的xml文件位置
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            String locationPattern = "classpath:mapper2/*.xml";
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources(locationPattern));

            //对应数据库的entity位置
//        String typeAliasesPackage = "com.moredatabase.entry";
//        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
            sqlSessionFactory = sqlSessionFactoryBean.getObject();
        }catch (Exception e){
            System.out.println("******************************************************");
            e.printStackTrace();
        }

        return sqlSessionFactory;
    }
}

接口的创建


import com.moredatabase.entry.Cxk;
import com.moredatabase.entry.Test;
import com.moredatabase.mapper2.CxkMapper;
import com.moredatabase.mapper.TestMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class HelloController {

    @RequestMapping("hello")
    public String hello(){
        System.out.println("coming...");
        return "SUCCESS";
    }


    @Resource(name = "secondSqlSessionFactory")
    @Qualifier("secondSqlSessionFactory")
    private SqlSessionFactory secondSqlSessionFactory;

    @Resource(name = "firstSqlSessionFactory")
    @Qualifier("firstSqlSessionFactory")
    private SqlSessionFactory firstSqlSessionFactory;


    @RequestMapping("getAllCxk")
    public List<Cxk> getAllCxk(){
        System.out.println("getAllCxk");
        SqlSession sqlSession = secondSqlSessionFactory.openSession();
        CxkMapper mapper = sqlSession.getMapper(CxkMapper.class);
        List<Cxk> allCxk = mapper.getAllCxk();
        return allCxk;
    }

    @RequestMapping("getAllTest")
    @ResponseBody
    public List<Test> getAllTest(){
        System.out.println("getAllTest");
        SqlSession sqlSession = firstSqlSessionFactory.openSession();
        TestMapper mapper = sqlSession.getMapper(TestMapper.class);
        List<Test> allTest = mapper.getAllTest();
        return allTest;

    }


}

Mapper的创建


import com.moredatabase.entry.Test;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface TestMapper {


    List<Test> getAllTest();

}

import com.moredatabase.entry.Cxk;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface CxkMapper{

    List<Cxk> getAllCxk();

}

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.moredatabase.mapper.TestMapper">
 
  <select id="getAllTest" resultType="com.moredatabase.entry.Test">
    select * from test
  </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.moredatabase.mapper2.CxkMapper">
 
  <select id="getAllCxk" resultType="com.moredatabase.entry.Cxk">
    select * from cxk
  </select>

</mapper>

标签:数据源,配置,springframework,public,import,mybatis,org,com,annotation
From: https://www.cnblogs.com/caoxuekun/p/17441876.html

相关文章

  • 开发手记:MyBatis的mapper文件的中SQL符号转义
    字符转义问题在MaBatis的XML文件中编写SQL语句时,<符号会出现转义问题,例如:<!--查询指定月份内的订单--><selectid="queryInRange"resultType="OrderEntity"> SELECT*FROMorder WHEREcreate_time>DATE_SUB(NOW(),INTERVAL#{month}MONTH) ANDuser_i......
  • SpringBoot i18n 配置
    概述由于项目需要进行国际化提示,所以做了一下SpringBoot的i18n的配置。有两种方式实现i18n的配置操作页面每次访问后端都携带用户设定的语言类型的i18n国际化操作。在请求URL中设置一个字段?language=zh_CN的方式实现或者请求头中设置表明语言类型都行Accept-Language:......
  • Ansible 安装与ssh密钥配置
    环境系统IP名称CentOS7.610.22.86.71管理机CentOS7.610.22.86.72被控机CentOS7.610.22.86.73被控机CentOS7.610.22.86.74被控机安装#yum源[root@localhost~]#cat/etc/yum.repos.d/epel.repo[epel]name=ExtraPackagesforEnterpriseLi......
  • Linux操作系统日志审计-关于secure和messages两个重要的日志的logrotate配置
    关于Linux操作系统中有两个日志非常的重要的,常常用来对操作系统的活动进行审计,两个日志文件分别是:/var/log/secure/var/log/messages 其中/var/log/secure是 securityandauthentication-relatedmessagesanderrors,安全与认证相关的信息和错误对于 /var/log/messages......
  • vue-cli 的配置和使用
    vue-cli介绍vue-cli是Vue.js开发的标准工具。它简化了程序员基于webpack创建工程化的Vue项目的过程。中文官网在工程化的项目中,vue要做的事情很单纯:通过main.js把App.vue渲染到index.html的指定区域中。配置和使用Vue-CLI的安装、使用及环境配置(超详细)vue项......
  • stm32环境配置---keil5
    第一步安装keil5官网下载位置填写必要信息后就可以安装core就是keil的安装位置pack就是芯片包的下载位置安装完成后会跳出这个界面,这个界面就是用来管理芯片包的,需要下载对应的芯片包才能将程序下载到板子上第二步安装芯片包如上所示,可以在对应界面中安装芯片包,也可......
  • Mybatis-plus 简单使用
    Mybatis-plus特点介绍:1、无侵入:只做增强不做改变,引入它不会对现有工程产生影响2、强大的CRUD操作:内置通用Mapper、Service,仅仅通过少量配置即可实现单表大部分CRUD操作,更有强大的条件构造器,满足各类使用需求。3、支持Lambda形式调用:通过Lambda表达式,方便编......
  • NETCORE - Swagger配置
    NETCORE-Swagger配置 环境:WebApiNET6  配置输出文档,项目右键-> 属性-> 生成-> 输出 勾选“生成包含API文档的文件”维护生成文件名称。  2.Program.cs中的修改把原来的 builder.Services.AddSwaggerGen();  修改成:builder.Services.AddSwagge......
  • 独角数卡 搭建-邮件配置-Epusdt配置-收U详细配置
    配置独角数卡https://github.com/assimon/dujiaoka/wiki/2.x_bt_install⚠️正式上线后一定要将.env配置里面的APP_DEBUG设置为false⚠️⚠️正式上线后一定要将.env配置里面的APP_DEBUG设置为false⚠️⚠️正式上线后一定要将.env配置里面的APP_DEBUG设置为false⚠️安装宝塔(国际版宝塔:a......
  • docker-oracle;配置oracle
    地址:172.18.0.170root/cssjkyhs/yhs0527le一、安装检查uname-r:查看centos版本,root登录,如果不是root,需要前面加sudo如果之前有安装,卸载:yumremovedockerdocker-commondocker-selinuxdocker-engine二、安装docker安装需要的软件包,yum-util提供......