SpringBoot实现多数据源(四)【集成多个 Mybatis 框架】

news/2024/11/29 19:47:20/

上一篇文章《SpringBoot实现多数据源(三)【AOP + 自定义注解】》

四、集成多个 Mybatis 框架


在这里插入图片描述

实现步骤

  1. 创建一个 dynamic_mybatis 的springboot项目,导入依赖
    • pom.xml
<dependencies><!--jdbc--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!--web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--aop--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><!--mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency><!--druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.8</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency></dependencies>
  1. 配置文件
    • application.yml
spring:application:name: dynamic_datasource# 数据源datasource:type: com.alibaba.druid.pool.DruidDataSource# 读数据源read:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/read?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456# 写数据源write:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/write?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456
# 端口号
server:port: 3355
  1. 实体类(这里省略增删查改的数据库操作)
    • People
package com.vinjcent.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@AllArgsConstructor
@NoArgsConstructor
@Data
public class People {private String name;}
  1. 配置读写分离的的MybatisConfiguration配置
  • RMybatisConfiguration(读数据源)
package com.vinjcent.config.mybatis;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.logging.stdout.StdOutImpl;
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.boot.context.properties.ConfigurationProperties;
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;/*** 读数据源配置* 1. 指定扫描mapper接口包* 2. 指定使用wSqlSessionFactory是哪个*/
@Configuration
@MapperScan(basePackages = "com.vinjcent.mapper.read", sqlSessionFactoryRef = "rSqlSessionFactory")
public class RMybatisConfiguration {@Bean(name = "readDatasource")@ConfigurationProperties(prefix = "spring.datasource.read")public DataSource readDatasource() {// 底层会自动拿到spring.datasource中的配置,创建一个DruidDataSourcereturn DruidDataSourceBuilder.create().build();}@Bean@Primarypublic SqlSessionFactory rSqlSessionFactory(@Qualifier("readDatasource") DataSource dataSource) throws Exception {final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();sqlSessionFactory.setDataSource(dataSource);sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/vinjcent/mapper/read/*.xml"));/* 主库设置sql控制台打印 */org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();configuration.setLogImpl(StdOutImpl.class);sqlSessionFactory.setConfiguration(configuration);sqlSessionFactory.setTypeAliasesPackage("com.vinjcent.pojo");return sqlSessionFactory.getObject();}
}
  • WMybatisConfiguration(写数据源)
package com.vinjcent.config.mybatis;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.logging.stdout.StdOutImpl;
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.boot.context.properties.ConfigurationProperties;
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;/*** 写数据源配置* 1. 指定扫描mapper接口包* 2. 指定使用wSqlSessionFactory是哪个*/
@Configuration
@MapperScan(basePackages = "com.vinjcent.mapper.write", sqlSessionFactoryRef = "wSqlSessionFactory")
public class WMybatisConfiguration {@Bean(name = "writeDatasource")@ConfigurationProperties(prefix = "spring.datasource.write")public DataSource writeDatasource() {// 底层会自动拿到spring.datasource中的配置,创建一个DruidDataSourcereturn DruidDataSourceBuilder.create().build();}@Bean@Primarypublic SqlSessionFactory wSqlSessionFactory(@Qualifier("writeDatasource") DataSource dataSource) throws Exception {final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();sqlSessionFactory.setDataSource(dataSource);sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/vinjcent/mapper/write/*.xml"));/* 主库设置sql控制台打印 */org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();configuration.setLogImpl(StdOutImpl.class);sqlSessionFactory.setConfiguration(configuration);sqlSessionFactory.setTypeAliasesPackage("com.vinjcent.pojo");return sqlSessionFactory.getObject();}
}
  1. 读写mapper接口以及对应映射文件.xml
  • RPeopleMapper
package com.vinjcent.mapper.read;import com.vinjcent.pojo.People;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface RPeopleMapper {List<People> list();}
<?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.vinjcent.mapper.read.RPeopleMapper"><select id="list" resultType="People">select * from `people`</select>
</mapper>
  • WPeopleMapper
package com.vinjcent.mapper.write;import com.vinjcent.pojo.People;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface WPeopleMapper {boolean save(People people);}
<?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.vinjcent.mapper.write.WPeopleMapper"><insert id="save">insert into `people`(name)values (#{name});</insert></mapper>
  1. Service层
    • PeopleServiceImpl
package com.vinjcent.service.impl;import com.vinjcent.mapper.read.RPeopleMapper;
import com.vinjcent.mapper.write.WPeopleMapper;
import com.vinjcent.pojo.People;
import com.vinjcent.service.PeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class PeopleServiceImpl implements PeopleService {private final WPeopleMapper wPeopleMapper;private final RPeopleMapper rPeopleMapper;@Autowiredpublic PeopleController(WPeopleMapper wPeopleMapper, RPeopleMapper rPeopleMapper) {this.wPeopleMapper = wPeopleMapper;this.rPeopleMapper = rPeopleMapper;}// 读@GetMapping("/list")public List<People> getAllPeople() {return rPeopleMapper.list();}// 写@GetMapping("/insert")public String addPeople() {wPeopleMapper.save(new People("vinjcent"));return "添加成功";}
}
  1. 测试接口
  • PeopleController
package com.vinjcent.controller;import com.vinjcent.mapper.read.RPeopleMapper;
import com.vinjcent.mapper.write.WPeopleMapper;
import com.vinjcent.pojo.People;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("people")
public class PeopleController {private final PeopleService peopleService;@Autowiredpublic PeopleController(PeopleService peopleService) {this.peopleService = peopleService;}@GetMapping("/list")public List<People> getAllPeople() {return peopleService.list();}@GetMapping("/insert")public String addPeople() {peopleService.save(new People("vinjcent"));return "添加成功";}}
  1. 运行并测试接口

下一篇文章《SpringBoot实现多数据源(五)【多数据源事务控制】》


http://www.ppmy.cn/news/1555.html

相关文章

linux+window+macos下的JDK安装

1. Linux中安装JDK &#xff08;1&#xff09;下载Linux版本的jdk压缩包 &#xff08;2&#xff09;解压 tar -zxvf 压缩包名 例如&#xff1a; tar -zxvf jdk-8u251-linux-x64.tar.gz&#xff08;3&#xff09;在系统配置文件配置java 编辑profile配置文件 vim /etc/prof…

Allegro如何锁定器件操作指导

Allegro如何锁定器件操作指导 Allegro上可以锁定器件,避免误操作被移动,具体操作如下 选择fix命令 Find选择Symbols 框选需要锁定的器件 可以看到器件被锁住了 除了这个方法之外,还有另外一种方法锁定器件,选择edit-property Find选择Symbols

XYNUOJ 1252 纪念品分组—贪心算法

欢迎访问XYNUOJ 1252: NOIP2007普及组第2题 纪念品分组  时间限制: 1 Sec 内存限制: 128 MB 提交: 10 解决: 5 [ 提交][ 状态][ 讨论版][ Edit] [ TestData] 题目描述 元旦快到了&#xff0c;校学生会让乐乐负责新年晚会的纪念品发放工作。为使得参加晚会的同学所获得的…

【SSM框架 二】Spring

文章目录二、Spring1、简介2、IOC理论思想3、Hello Spring4、IOC创建对象的方式4.1 无参构造构造器注入4.2 有参构造器注入5、Spring的配置5.1 别名5.2 Bean的配置5.3 import6、DI依赖注入6.1 构造方法注入6.2 set方法注入6.3 扩展注入6.4、Bean的作用域7、Bean的自动装配7.1 正…

WSDM‘23 推荐系统论文梳理

之前把2022年已公布的推荐系统相关顶会梳理一遍 &#xff0c;历史推荐系统顶会论文梳理系列文章可以参考公众号或知乎&#xff0c;快捷合辑详见《2022推荐系统顶会论文梳理系列》。 WSDM23已公布录用结果&#xff0c;共收到投稿690篇&#xff0c;录用123篇&#xff0c;录用率为…

程序人生 | 与足球共舞的火柴人(致敬格拉利什,赋予足球更深的意义)

个人简介 &#x1f440;个人主页&#xff1a; 前端杂货铺 &#x1f64b;‍♂️学习方向&#xff1a; 主攻前端方向&#xff0c;也会涉及到服务端 &#x1f4c3;个人状态&#xff1a; 在校大学生一枚&#xff0c;已拿多个前端 offer&#xff08;秋招&#xff09; &#x1f680;未…

ActiveMQ 笔记(十)Linux部署:单机与集群部署流程

1. 单机部署 (1) 获取安装包 方法1:从官网下载 官网: ActiveMQ 方法2:直接用wget命令下载 cd /optwget http://archive.apache.org/dist/activemq/5.15.3/apache-activemq-5.15.3-bin.tar.gz (2)解压安装包并拷贝到工作目录 cd /opt/apache-activemq-5.15.3cp …

家庭用户无线上网案例(AC通过三层口对AP进行管理)

组网需求 为一个家庭用户使用的网络架构。该家庭消费用户的上网流量大多是低速流量&#xff0c;例如浏览网页、玩游戏、看视频等。家庭成员使用的无线终端主要为手机、PC、电视机等。终端接入的数量正常情况下在10个以内&#xff0c;偶尔有家庭聚会等特殊情况&#xff0c;终端接…