Skip to content

服务器托管,北京服务器托管,服务器租用-价格及机房咨询

Menu
  • 首页
  • 关于我们
  • 新闻资讯
  • 数据中心
  • 服务器托管
  • 服务器租用
  • 机房租用
  • 支持中心
  • 解决方案
  • 联系我们
Menu

Springboot之 Mybatis 多数据源实现

Posted on 2023年5月6日 by hackdl
简介

上篇讲解了 JPA 多数据源实现;这篇讲解一下 Mybatis 多数据源实现 。主要采用将不同数据库的 Mapper 接口分别存放到不同的 package,Spring 去扫描不同的包,注入不同的数据源来实现多数据源。原理跟 JPA 多数据源实现基本一致。

创建 mybatis-multip-datasource 项目
数据库脚本参考:
pom.xml文件引入如下依赖

	4.0.0

	com.olive
	mybatis-multip-datasource
	0.0.1-SNAPSHOT
	jar

	jpa-multip-datasource
	http://maven.apache.org

	
		org.springframework.boot
		spring-boot-starter-parent
		2.5.14
		 
	

	
		UTF-8
		8
		8
	

	
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.3
        
		
		
			mysql
			mysql-connector-java
		

		
			org.projectlombok
			lombok
		
		
		
		    org.springframework.boot
		    spring-boot-starter-web
		
		
	
配置两个数据源

分别为第一个主数据源(primary),第二数据源(second),具体配置如下:

# 基本配置
server:
  port: 8080

# 数据库
spring:
  datasource:
    primary:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
      username: root
      password: root
    second:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/crm72?characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
      username: root
      password: root

  jackson:
    serialization:
      indent-output: true
配置数据源

DataSourceConfig配置

package com.olive.config;

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 javax.sql.DataSource;

/**
 * @Description: 数据源配置
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondDataSource")
    @Qualifier("secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }
}

PrimaryConfig数据源

/**
 * @Description: 主数据源配置
 */
@Configuration
@MapperScan(basePackages = "com.olive.mapper.primary",
            sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryConfig {

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFacotory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(primaryDataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/primary/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "primaryTransactionManager")
    @Primary
    public DataSourceTransactionManager primaryTransactionManager() {
        return new DataSourceTransactionManager(primaryDataSource);
    }

    @Bean(name = "primarySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

SecondConfig数据源

/**
 * @Description: 主数据源配置
 */
@Configuration
@MapperScan(basePackages = "com.olive.mapper.second",
        sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondConfig {

    @Autowired
    @Qualifier("secondDataSource")
    private DataSource secondDataSource;

    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFacotory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(secondDataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/second/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "secondTransactionManager")
    public DataSourceTransactionManager secondTransactionManager() {
        return new DataSourceTransactionManager(secondDataSource);
    }

    @Bean(name = "secondSqlSessionTemplate")
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
创建学生与老师实体类

Student实体类

package com.olive.entity.primary;

import java.io.Serializable;
import lombok.Data;

@Data
public class StudentDO implements Serializable{

    private Long id;

    private String name;

    private int sex;
    
    private String grade;
}

Teacher实体类

package com.olive.entity.second;

import java.io.Serializable;
import lombok.Data;

@Data
public class TeacherDO implements Serializable {

	private Long id;

	private String name;

	private int sex;
	
	private String office;
}
数据库持久类

StudentMapper类

package com.olive.mapper.primary;

import com.olive.entity.primary.StudentDO;
import org.apache.ibatis.annotations.Param;


public interface StudentMapper {

    int save(@Param("studentDO") StudentDO studentDO);
}

TeacherMapper类

package com.olive.mapper.second;

import com.olive.entity.second.TeacherDO;
import org.apache.ibatis.annotations.Param;

public interface TeacherMapper {

    int save(@Param("teacherDO") TeacherDO teacherDO);
}
Mybatis xml映射

StudentMapper.xml




  
    
    
    
    
  

  
    INSERT INTO t_student (user_name, sex, grade) VALUES (#{studentDO.name}, #{studentDO.sex}, #{studentDO.grade});
  

TeacherMapper.xml




  
    
    
    
    
  

  
    INSERT INTO t_teacher ( user_name, sex, office) VALUES (#{teacherDO.name}, #{teacherDO.sex}, #{teacherDO.office});
  

主要注意这两个xml文件需要放到不同的目录,如下图

创建springboot引导类
package com.olive;

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

@SpringBootApplication
public class Application {

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

}
测试
package com.olive;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.olive.entity.primary.StudentDO;
import com.olive.entity.second.TeacherDO;
import com.olive.mapper.primary.StudentMapper;
import com.olive.mapper.second.TeacherMapper;

@SpringBootTest
public class MybatisTest {

	@Autowired
	StudentMapper studentMapper;

	@Autowired
	TeacherMapper teacherMapper;

	@Test
	public void userSave() {
		StudentDO studentDO = new StudentDO();
		studentDO.setName("BUG弄潮儿");
		studentDO.setSex(1);
		studentDO.setGrade("一年级");
		studentMapper.save(studentDO);

		TeacherDO teacherDO = new TeacherDO();
		teacherDO.setName("Java乐园");
		teacherDO.setSex(2);
		teacherDO.setOffice("语文");
		teacherMapper.save(teacherDO);
	}
}

服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net

Related posts:

  1. 陕西emobile云主机:稳定可靠的服务器托管方案
  2. 昆明优质XP服务器托管服务,稳定可靠
  3. idc北京地址
  4. 服务器托管——独享与共享的比较
  5. 天津网吧云服务器托管:高效稳定的网络服务

服务器托管,北京服务器托管,服务器租用,机房机柜带宽租用

服务器托管

咨询:董先生

电话13051898268 QQ/微信93663045!

上一篇: 未来智能牛奶壶 轻松辨别牛奶是否变质
下一篇: Springboot 之 JPA 多数据源实现

最新更新

  • 管理价值
  • 【每日一题】工作计划的最低难度
  • angular-devkit 中 build-angular 包的作用
  • 使用 ABAP 代码删除指定 SAP CRM 系统里 Opportunity 订单的文本
  • 使用 SAP fiori-tools-proxy 时遇到的错误消息 – invalid version

随机推荐

  • PreferenceActivity详解
  • 重庆服务器托管接线服务介绍
  • 北京数据中心机柜:高效稳定的数码存储解决方案
  • 虎门云服务器托管:高效稳定的云计算服务
  • 杭州云计算托管公司:稳定高效,保障数据安全

客服咨询

  • 董先生
  • 微信/QQ:93663045
  • 电话:13051898268
  • 邮箱:dongli@hhisp.com
  • 地址:北京市石景山区重聚园甲18号2层

友情链接

  • 服务器托管
  • 服务器租用
  • 机房租用托管
  • 服务器租用托管
©2023 服务器托管,北京服务器托管,服务器租用-价格及机房咨询 京ICP备13047091号-8