In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to configure MyBatis multi-data sources in Spring Boot. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
Create a database db_test
SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0Mutual-Table structure for tweeted UserRose-DROP TABLE IF EXISTS `t _ user` CREATE TABLE `tuser` (`id` int (8) NOT NULL AUTO_INCREMENT COMMENT 'ID', `user_ name` varchar (20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT' user name', `user_ sex` char (1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user gender', PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 -Records of tweak user VALUES-BEGIN;INSERT INTO `t _ user` VALUES (1, 'Liu Bei', 'male'); INSERT INTO `t _ user` VALUES (2, 'Sun Shangxiang', 'female') INSERT INTO `t _ user`VALUES (3, 'Zhou Yu', 'male'); INSERT INTO `tuser` VALUES (4, 'Xiao Qiao', 'female'); INSERT INTO `tuser`VALUES (5, 'Zhuge Liang', 'male'); INSERT INTO `tuser`User`VALUES (7, 'Guan Yu', 'male'); INSERT INTO `tuser`User` VALUES (8, 'Zhang Fei', 'male') INSERT INTO `tuser`VALUES (9, 'Zhao Yun', 'male'); INSERT INTO `tuser` VALUES (10, 'Mr. Huang', 'male'); INSERT INTO `tuser`VALUES (11, 'Cao Cao', 'male'); INSERT INTO `tuser`VALUES (12, 'Sima Yi', 'male'); INSERT INTO `tuser`VALUES (13, 'Diao Chan', 'female'); INSERT INTO `tuser`VALUES (14,'Lv Bu', 'male') INSERT INTO `t _ user`VALUES (15,'Ma Chao', 'male'); INSERT INTO `tuser` VALUES (16, 'Wei Yan', 'male'); INSERT INTO `tuser` VALUES (17, 'Meng Huo', 'male'); INSERT INTO `tuser` VALUES (18, 'Big Joe', 'female'); INSERT INTO `tuser`VALUES (19, 'Liu Chan', 'male'); INSERT INTO `tuser`VALUES (20, 'Jiang Wei', 'male') INSERT INTO `t _ user`VALUES (21, 'Liao Hua', 'male'); INSERT INTO `t _ user`VALUES (22, 'Guanping', 'male'); COMMIT;SET FOREIGN_KEY_CHECKS = 1
Dbb_test2
SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0Mutual-Table structure for tantalizable color-DROP TABLE IF EXISTS `t _ room` CREATE TABLE `t_ play` (`id`int (11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `hero_ code` varchar (32) DEFAULT NULL COMMENT' hero code', `hero_ name` varchar (20) DEFAULT NULL COMMENT 'hero name', PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 -Records of tweets color color-BEGIN;INSERT INTO `t _ room` VALUES (1, '001mm,' Demacia'); COMMIT;SET FOREIGN_KEY_CHECKS = 1
Build project, project directory structure
Pom File 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's druid database connection pool is used here, and Druid can provide powerful monitoring and extension capabilities. Here we only do simple applications for the time being.
Configuration file # master data source configuration 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 data source configuration 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 data source configuration
MasterDataSourceConfig corresponding database 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 corresponding database 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);}}
Multiple data sources must specify the main library in the process of use, otherwise an error will be reported. @ MapperScan (basePackages = "cn.zwqh.springboot.dao.slave") specifies the scanning path of the corresponding Dao layer.
Dao layer and xml layer
The dao layer of the db_test database is under the cn.zwqh.springboot.dao.master package, and the dao layer of the db_test2 database is under the cn.zwqh.springboot.dao.slave package.
UserDao
Public interface UserDao {List getAll ();}
HeroDao
Public interface HeroDao {List getAllHero ();}
The xml layer of the db_test database is under the / mapper/master/ file path, and the xml layer of the db_test2 database is under the / mapper/slave/ file path.
UserMapper.xml
Select * from t_user
HeroMapper.xml
Select * from t_hero Test
Tests can be done using SpringBootTest, or you can put them in Controller, and you are used to using Controller.
@ RestController@RequestMapping ("/ test") public class TestController {@ Autowired private UserDao userDao; @ Autowired private HeroDao heroDao; / * find all users * @ return * / @ RequestMapping ("/ getAllUser") public List getAllUser () {return userDao.getAll () } / * * find all heroes * @ return * / @ RequestMapping ("/ getAllHero") public List getAllHero () {return heroDao.getAllHero ();}}
Browser direct access: http://127.0.0.1:8080/test/ plus the relevant test path.
After reading the above, do you have any further understanding of how to configure MyBatis multiple data sources in Spring Boot? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.