千家信息网

Spring Boot 中怎么配置MyBatis多数据源

发表于:2025-02-23 作者:千家信息网编辑
千家信息网最后更新 2025年02月23日,今天就跟大家聊聊有关Spring Boot 中怎么配置MyBatis多数据源,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。创建数据库 db_t
千家信息网最后更新 2025年02月23日Spring Boot 中怎么配置MyBatis多数据源

今天就跟大家聊聊有关Spring Boot 中怎么配置MyBatis多数据源,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

创建数据库 db_test

SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;-- ------------------------------ Table structure for t_user-- ----------------------------DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` (  `id` int(8) NOT NULL AUTO_INCREMENT COMMENT 'ID',  `user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户姓名',  `user_sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户性别',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;-- ------------------------------ Records of t_user-- ----------------------------BEGIN;INSERT INTO `t_user` VALUES (1, '刘备', '男');INSERT INTO `t_user` VALUES (2, '孙尚香', '女');INSERT INTO `t_user` VALUES (3, '周瑜', '男');INSERT INTO `t_user` VALUES (4, '小乔', '女');INSERT INTO `t_user` VALUES (5, '诸葛亮', '男');INSERT INTO `t_user` VALUES (6, '黄月英', '女');INSERT INTO `t_user` VALUES (7, '关羽', '男');INSERT INTO `t_user` VALUES (8, '张飞', '男');INSERT INTO `t_user` VALUES (9, '赵云', '男');INSERT INTO `t_user` VALUES (10, '黄总', '男');INSERT INTO `t_user` VALUES (11, '曹操', '男');INSERT INTO `t_user` VALUES (12, '司马懿', '男');INSERT INTO `t_user` VALUES (13, '貂蝉', '女');INSERT INTO `t_user` VALUES (14, '吕布', '男');INSERT INTO `t_user` VALUES (15, '马超', '男');INSERT INTO `t_user` VALUES (16, '魏延', '男');INSERT INTO `t_user` VALUES (17, '孟获', '男');INSERT INTO `t_user` VALUES (18, '大乔', '女');INSERT INTO `t_user` VALUES (19, '刘婵', '男');INSERT INTO `t_user` VALUES (20, '姜维', '男');INSERT INTO `t_user` VALUES (21, '廖化', '男');INSERT INTO `t_user` VALUES (22, '关平', '男');COMMIT;SET FOREIGN_KEY_CHECKS = 1;

dbb_test2

SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;-- ------------------------------ Table structure for t_hero-- ----------------------------DROP TABLE IF EXISTS `t_hero`;CREATE TABLE `t_hero` (  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',  `hero_code` varchar(32) DEFAULT NULL COMMENT '英雄编码',  `hero_name` varchar(20) DEFAULT NULL COMMENT '英雄名称',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;-- ------------------------------ Records of t_hero-- ----------------------------BEGIN;INSERT INTO `t_hero` VALUES (1, '001', '德玛西亚');COMMIT;SET FOREIGN_KEY_CHECKS = 1;

构建项目,项目目录结构

pom 文件

        4.0.0                        org.springframework.boot                spring-boot-starter-parent                2.1.9.RELEASE                                 cn.zwqh        spring-boot-mybatis-mulidatasource        0.0.1-SNAPSHOT        spring-boot-mybatis-mulidatasource        spring-boot-mybatis-mulidatasource                        1.8                                                        org.springframework.boot                        spring-boot-starter-web                                                        org.springframework.boot                        spring-boot-starter-test                        test                                                                        org.springframework.boot                        spring-boot-starter-jdbc                                                                                        org.springframework.boot                        spring-boot-devtools                        true                                                                                                         mysql                        mysql-connector-java                        runtime                                                                                        org.mybatis.spring.boot                        mybatis-spring-boot-starter                        2.1.0                                                                                        com.alibaba                        druid-spring-boot-starter                        1.1.20                                                                                        com.github.pagehelper                        pagehelper-spring-boot-starter                        1.2.12                                                                                                        org.springframework.boot                                spring-boot-maven-plugin                                                

这里使用了alibaba的druid数据库连接池,Druid 能够提供强大的监控和扩展功能。这里我们暂时只做简单的应用。

配置文件

#master 数据源配置master.datasource.driver-class-name=com.mysql.cj.jdbc.Drivermaster.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=truemaster.datasource.username=rootmaster.datasource.password=zwqh@0258#slave 数据源配置slave.datasource.driver-class-name=com.mysql.cj.jdbc.Driverslave.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test2?useUnicode=true&characterEncoding=UTF-8&useSSL=trueslave.datasource.username=rootslave.datasource.password=zwqh@0258#mybatismybatis.mapper-locations=classpath:/mapper/**/*Mapper.xml

数据源配置

MasterDataSourceConfig 对应数据库 db_test

@Configuration@MapperScan(basePackages = "cn.zwqh.springboot.dao.master", sqlSessionFactoryRef = "masterSqlSessionFactory")public class MasterDataSourceConfig {        @Value("${master.datasource.driver-class-name}")        private String driverClassName;        @Value("${master.datasource.url}")        private String url;        @Value("${master.datasource.username}")        private String username;        @Value("${master.datasource.password}")        private String password;        @Bean(name = "masterDataSource")        @Primary        public DataSource dataSource() {                DruidDataSource dataSource = new DruidDataSource();                dataSource.setDriverClassName(this.driverClassName);                dataSource.setUrl(this.url);                dataSource.setUsername(this.username);                dataSource.setPassword(this.password);                return dataSource;        }        @Bean(name = "masterSqlSessionFactory")        @Primary        public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {                SqlSessionFactoryBean bean = new SqlSessionFactoryBean();                bean.setDataSource(dataSource);                bean.setMapperLocations(                                new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/master/*Mapper.xml"));                return bean.getObject();        }        @Bean(name = "masterTransactionManager")        @Primary        public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {                return new DataSourceTransactionManager(dataSource);        }        @Bean(name = "masterSqlSessionTemplate")        @Primary        public SqlSessionTemplate testSqlSessionTemplate(                        @Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {                return new SqlSessionTemplate(sqlSessionFactory);        }}

SlaveDataSourceConfig 对应数据库 db_test2

@Configuration@MapperScan(basePackages = "cn.zwqh.springboot.dao.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory")public class SlaveDataSourceConfig {        @Value("${slave.datasource.driver-class-name}")        private String driverClassName;        @Value("${slave.datasource.url}")        private String url;        @Value("${slave.datasource.username}")        private String username;        @Value("${slave.datasource.password}")        private String password;        @Bean(name = "slaveDataSource")        public DataSource dataSource() {                DruidDataSource dataSource = new DruidDataSource();                dataSource.setDriverClassName(this.driverClassName);                dataSource.setUrl(this.url);                dataSource.setUsername(this.username);                dataSource.setPassword(this.password);                return dataSource;        }        @Bean(name = "slaveSqlSessionFactory")        public SqlSessionFactory sqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {                SqlSessionFactoryBean bean = new SqlSessionFactoryBean();                bean.setDataSource(dataSource);                bean.setMapperLocations(                                new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/slave/*Mapper.xml"));                return bean.getObject();        }        @Bean(name = "slaveTransactionManager")        public DataSourceTransactionManager transactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {                return new DataSourceTransactionManager(dataSource);        }        @Bean(name = "slaveSqlSessionTemplate")        public SqlSessionTemplate testSqlSessionTemplate(                        @Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {                return new SqlSessionTemplate(sqlSessionFactory);        }}

多个数据源在使用的过程中必须指定主库,不然会报错。 @MapperScan(basePackages = "cn.zwqh.springboot.dao.slave") 指定对应 Dao 层的扫描路径。

dao 层和 xml 层

db_test 数据库的 dao 层在 cn.zwqh.springboot.dao.master 包下,db_test2 数据库的 dao 层在 cn.zwqh.springboot.dao.slave 包下。

UserDao

public interface UserDao {        List getAll();}

HeroDao

public interface HeroDao {        List getAllHero();}

db_test 数据库的 xml 层在 /mapper/master/ 文件路径下,db_test2 数据库的 xml 层在 /mapper/slave/ 文件路径下。

UserMapper.xml

                                                                                

HeroMapper.xml

                                                                                

测试

测试可以使用 SpringBootTest,也可以放到 Controller中,个人习惯用 Controller。

@RestController@RequestMapping("/test")public class TestController {                @Autowired        private UserDao userDao;        @Autowired        private HeroDao heroDao;                /**         *  查找所有用户         * @return         */        @RequestMapping("/getAllUser")        public List getAllUser(){                return userDao.getAll();         }        /**         *  查找所有英雄         * @return         */        @RequestMapping("/getAllHero")        public List getAllHero(){                return heroDao.getAllHero();        }        }

浏览器直接访问:http://127.0.0.1:8080/test/ 加上相关测试路径即可。

看完上述内容,你们对Spring Boot 中怎么配置MyBatis多数据源有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

数据 数据库 数据源 配置 文件 路径 内容 用户 英雄 测试 项目 强大 个人 功能 名称 多个 姓名 性别 更多 浏览器 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 肇庆通讯软件开发零售价 深信服科技软件开发笔试题 卸载数据库实例 天龙八部网游服务器人数 命令行读取数据库 sql数据库数据迁移 南充网络安全等级保护测评 如何获取数据库中的数据 贵州手机软件开发多少钱 怎么连接到小爱同学的服务器 网络技术在美术教学中的运用总结 数据库建立的模式是什么模式 柬埔寨到中国的机票服务器 信用卡购买美国服务器 数据库如何修改地址吗 小学生文明网络安全知识 数据库平台售后维保方案 图数据库读后感 怎么把握一个数据库的优点 评价分布式数据库标准 山东春考网络技术考试大纲 北京推广网络技术收费 泰山服务器管理口地址 华为手机的服务器在哪一个页面 武汉市网络安全永久会址 学校网络安全专业培训资料 大庆市网络安全演练 联合国贸发会议服务贸易数据库 调兵山网络安全宣传 评价分布式数据库标准
0