GitHub:SpringBootDemo
Gitee:SpringBootDemo
微信公众号:
多数据源即动态数据源,随着项目开发逐渐扩大,单个数据源、单一数据源已经无法满足需求项目的支撑需求。
或是单一数据库无法承载大数据量的访问,需使用多个数据库进行数据的读写分离;
或是某些特殊业务需求,需操作不同的数据库。
在 Spring Boot整合MyBatis连接数据库 文章中,展示了Spring Boot整合MyBatis连接数据库的方法,基于此,Spring Boot 整合MyBatis 配置多数据源。
使用Mybatis Plus 配置多数据源参考:Spring Boot整合MyBatis Plus配置多数据源
0 开发环境
- JDK:1.8
- Spring Boot:2.1.1.RELEASE
- MySQL:5.7.13
1 引入依赖
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version><scope>runtime</scope></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.30</version><scope>provided</scope></dependency>
2 引入数据源
server:port:8090spring:datasource:master:jdbc-url: jdbc:mysql://127.0.0.1:3306/test_master?characterEncoding=utf8&serverTimezone=GMT%2B8username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
slave:jdbc-url: jdbc:mysql://127.0.0.1:3306/test_slave?characterEncoding=utf8&serverTimezone=GMT%2B8username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
#mybatis:mapper-locations: classpath:mapper/**/*.xmltype-aliases-package: cn.wbnull.springbootdemo.entity
该配置方式下,需要操作的两个数据库的Mapper需放置在不同文件夹下,如下图所示:
3 配置master库的源连接
@Configuration@MapperScan(basePackages ="cn.wbnull.springbootdemo.mapper.master", sqlSessionFactoryRef ="masterSqlSessionFactory")publicclassMasterDataSourceConfig{@Primary@Bean("masterDataSource")@ConfigurationProperties(prefix ="spring.datasource.master")publicDataSourcemasterDataSource(){returnDataSourceBuilder.create().build();}@Primary@Bean("masterDataSourceTransactionManager")publicDataSourceTransactionManagermasterDataSourceTransactionManager(@Qualifier("masterDataSource")DataSource dataSource){returnnewDataSourceTransactionManager(dataSource);}@Primary@Bean("masterSqlSessionFactory")publicSqlSessionFactorymasterSqlSessionFactory(@Qualifier("masterDataSource")DataSource dataSource)throwsException{SqlSessionFactoryBean sqlSessionFactory =newSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);Resource[] resources =newPathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml");
sqlSessionFactory.setMapperLocations(resources);return sqlSessionFactory.getObject();}}
4 配置slave库的源连接
@Configuration@MapperScan(basePackages ="cn.wbnull.springbootdemo.mapper.slave", sqlSessionFactoryRef ="slaveSqlSessionFactory")publicclassSlaveDataSourceConfig{@Bean("slaveDataSource")@ConfigurationProperties(prefix ="spring.datasource.slave")publicDataSourceslaveDataSource(){returnDataSourceBuilder.create().build();}@Bean("slaveDataSourceTransactionManager")publicDataSourceTransactionManagerslaveDataSourceTransactionManager(@Qualifier("slaveDataSource")DataSource dataSource){returnnewDataSourceTransactionManager(dataSource);}@Bean("slaveSqlSessionFactory")publicSqlSessionFactoryslaveSqlSessionFactory(@Qualifier("slaveDataSource")DataSource dataSource)throwsException{SqlSessionFactoryBean sqlSessionFactory =newSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);Resource[] resources =newPathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml");
sqlSessionFactory.setMapperLocations(resources);return sqlSessionFactory.getObject();}}
5 测试
5.1 新建数据库表
CREATESCHEMA`test_master`DEFAULTCHARACTERSET utf8mb4 ;CREATETABLE`test_master`.`user`(`id`INTNOTNULLAUTO_INCREMENT,`name`VARCHAR(45)NOTNULL,PRIMARYKEY(`id`));INSERTINTO`test_master`.`user`(`name`)VALUES('张三');INSERTINTO`test_master`.`user`(`name`)VALUES('李四');INSERTINTO`test_master`.`user`(`name`)VALUES('王五');INSERTINTO`test_master`.`user`(`name`)VALUES('周六');CREATESCHEMA`test_slave`DEFAULTCHARACTERSET utf8mb4 ;CREATETABLE`test_slave`.`user_info`(`id`INTNOTNULLAUTO_INCREMENT,`userCode`VARCHAR(20)NOTNULL,`userName`VARCHAR(45)NULL,`password`VARCHAR(40)NOTNULL,PRIMARYKEY(`id`));INSERTINTO`test_slave`.`user_info`(`id`,`userCode`,`userName`,`password`)VALUES('1','zhangsan','张三三','zhangsan');INSERTINTO`test_slave`.`user_info`(`id`,`userCode`,`userName`,`password`)VALUES('2','lisi','李四四','lisi');INSERTINTO`test_slave`.`user_info`(`id`,`userCode`,`userName`,`password`)VALUES('3','wangwu','王五五','wangwu');INSERTINTO`test_slave`.`user_info`(`id`,`userCode`,`userName`,`password`)VALUES('4','zhouliu','周六六','zhouliu');
5.2 新建实体类
@DatapublicclassUser{privateint id;privateString name;}
@DatapublicclassUserInfo{privateInteger id;privateString userCode;privateString userName;privateString password;}
5.3 新建Mapper
@RepositorypublicinterfaceUserMapper{voidadd(@Param("user")User user);List<User>query();voidupdate(@Param("id")int id,@Param("name")String name);voiddelete(@Param("id")int id);}
@RepositorypublicinterfaceUserInfoMapper{List<User>query();}
5.4 新建映射文件
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="cn.wbnull.springbootdemo.mapper.master.UserMapper"><!-- 通用查询映射结果 --><resultMapid="BaseResultMap"type="cn.wbnull.springbootdemo.entity.User"><idcolumn="id"property="id"/><resultcolumn="name"property="name"/></resultMap><!-- 通用查询结果列 --><sqlid="Base_Column_List">
id, name
</sql><insertid="add">
INSERT INTO user(<includerefid="Base_Column_List"/>)
VALUES
(
#{user.id},
#{user.name}
)
</insert><selectid="query"resultMap="BaseResultMap">
SELECT * FROM user
</select><updateid="update">
UPDATE user SET name = '${name}' WHERE id = '${id}'
</update><updateid="delete">
DELETE FROM user where id = '${id}'
</update></mapper>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="cn.wbnull.springbootdemo.mapper.slave.UserInfoMapper"><!-- 通用查询映射结果 --><resultMapid="BaseResultMap"type="cn.wbnull.springbootdemo.entity.UserInfo"><idcolumn="id"property="id"/><resultcolumn="userCode"property="userCode"/><resultcolumn="userName"property="userName"/><resultcolumn="password"property="password"/></resultMap><!-- 通用查询结果列 --><sqlid="Base_Column_List">
id, userCode, userName, password
</sql><selectid="query"resultMap="BaseResultMap">
SELECT * FROM user_info
</select></mapper>
5.5 新建Service
@ServicepublicclassUserService{@AutowiredprivateUserMapper userMapper;publicStringadd(String name){User user =newUser();
user.setName(name);
userMapper.add(user);return"操作成功";}publicList<User>query(){return userMapper.query();}publicStringupdate(int id,String name){
userMapper.update(id, name);return"操作成功";}publicStringdelete(int id){
userMapper.delete(id);return"操作成功";}}
@ServicepublicclassUserInfoService{@AutowiredprivateUserInfoMapper userInfoMapper;publicList<User>query(){return userInfoMapper.query();}}
5.6 新建Controller
@RestController@RequestMapping("user")publicclassUserController{@AutowiredpublicUserService userService;@PostMapping(value ="add")publicStringadd(@RequestParam(value ="name")String name){return userService.add(name);}@PostMapping(value ="query")publicList<User>query(){return userService.query();}@PostMapping(value ="update")publicStringupdate(@RequestParam(value ="id")int id,@RequestParam(value ="name")String name){return userService.update(id, name);}@PostMapping(value ="delete")publicStringdelete(@RequestParam(value ="id")int id){return userService.delete(id);}}
@Controller@RequestMapping("userInfo")publicclassUserInfoController{@AutowiredpublicUserInfoService userInfoService;@PostMapping(value ="query")publicList<User>query(){return userInfoService.query();}}
5.7 测试
使用Postman测试,输出结果如下
5.8.1 master select
5.8.2 master insert
数据库中插入成功
5.8.3 master update
数据库中更新成功
5.8.4 master delete
数据库中删除成功
5.8.5 slave select
截至这里,Spring Boot已经成功整合MyBatis多数据源,并连接上了数据库,且测试正常。
版权归原作者 程序员null 所有, 如有侵权,请联系我们删除。