前言

前一篇中我们使用spring boot+mybatis创建了单一数据源,其中单一数据源不需要我们自己手动创建,spring boot自动配置在程序启动时会替我们创建好数据源。

准备工作

application.yml中配置connection的4个属性

spring:
datasource:
read:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.80.129:3306/test
username: root
password: 123456
write:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.80.129:3306/test
username: root
password: 123456

  

多数据源创建方法

1、多数据源主要是需要我们手动来创建DataSource、SqlSessionFactory、SqlSessionTemplate。这里我们基于同一个库来创建读写分离的数据源。这里两个方法的返回值都是javax.sql.DataSource。

@Configuration
public class DataSourceConfig { @Primary
@Bean(name="readDataSource")
@ConfigurationProperties(prefix = "spring.datasource.read")
public DataSource readDataSource(){
return DataSourceBuilder.create().build();
} @Bean(name="writeDataSource")
@ConfigurationProperties(prefix = "spring.datasource.write")
public DataSource writeDataSource(){
return DataSourceBuilder.create().build();
} }

 2、读写分离的配置类。也就是分别创建读写的SqlSessionFactory和SqlSessionTemplate

@Configuration
@MapperScan(basePackages = {"com.zhangfei.dao.read"},sqlSessionFactoryRef = "readSqlSessionFactory")
public class MyBatisDbAConfig { @Autowired
@Qualifier("readDataSource")
private DataSource dataSource; @Bean
public SqlSessionFactory readSqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resource=resolver.getResources("classpath:mybatis/read/*.xml");
sqlSessionFactoryBean.setMapperLocations(resource); return sqlSessionFactoryBean.getObject();
} @Bean
public SqlSessionTemplate readSqlSession() throws Exception{
SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(readSqlSessionFactory()); return sqlSessionTemplate;
}
}

  

@Configuration
@MapperScan(basePackages = {"com.zhangfei.dao.write"},sqlSessionFactoryRef = "writeSqlSessionFactory")
public class MyBatisDbBConfig { @Autowired
@Qualifier("writeDataSource")
private DataSource dataSource; @Bean
public SqlSessionFactory writeSqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resource=resolver.getResources("classpath:mybatis/write/*.xml");
sqlSessionFactoryBean.setMapperLocations(resource); return sqlSessionFactoryBean.getObject();
} @Bean
public SqlSessionTemplate writeSqlSession() throws Exception{
SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(writeSqlSessionFactory()); return sqlSessionTemplate;
} }

  3、read包下的dao接口

public interface StudentReadDao {

    List<Student> getStudentList();

    Student getById(long id);

}

 4、wite包下的dao接口

public interface StudentWriteDao {

    int delete(long id);

    int insert(Student student);

    int update(Student student);

}

 5、分别创建读写的mapper文件。我本地分别创建了:resources/mybatis/read/studentdao.xml、/resources/mybatis/write/studentdao.xml

<?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.zhangfei.dao.read.StudentReadDao">
<select id="getStudentList" resultType="com.zhangfei.entity.Student">
select * from student;
</select> <select id="getById" resultType="com.zhangfei.entity.Student">
select * from student where id=#{id};
</select> </mapper>

  

<?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.zhangfei.dao.write.StudentWriteDao"> <insert id="insert" parameterType="com.zhangfei.entity.Student">
insert into student (name,age) values (#{name},#{age})
</insert> <update id="update" parameterType="com.zhangfei.entity.Student">
update student set name=#{name},age=#{age} where id=#{id}
</update> <delete id="delete" parameterType="long">
delete from student where id=#{id}
</delete>
</mapper>

  OK。以上几部就搞定了读写分离的准备工作,接着就可以在controller里调用了。 准备工作完成后,还有重要的一点就是需要在程序入口处排除springboot自动属性提供的数据源  @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

@RestController
@RequestMapping("/student")
public class StudentController { @Autowired
StudentReadDao studentDao; @GetMapping("/getbyid/{id}/")
public Student getById(@PathVariable("id")long id){ Student student=studentDao.getById(id);
return student;
} @GetMapping("/all/")
public List<Student> getAll(){
return studentDao.getStudentList();
} }

  

总结

好了,基本上又是3分钟就搞定了SpringBoot+MyBatis多数据源或者叫做读写分离的工作。那么不知道你又没有反问我们手动创建的DataSource具体类型是什么呢? 这里我们在这里只写了javax.sql.DataSource接口。 我本地用的是springboot 2.0.2 ,当前 DataSourceBuilder 只支持3种类型的数据源: com.zaxxer.hikari.HikariDataSource、org.apache.tomcat.jdbc.pool.DataSource、org.apache.commons.dbcp2.BasicDataSource。可以在DataSourceBuilder类中看到相关代码。那么现在这种情况因为我们引用的内嵌tomcat,所以我们这里返回的数据源类型是org.apache.tomcat.jdbc.pool.DataSource。 可以用instanceof验证一下具体的数据源类型。

spring boot(四) 多数据源的更多相关文章

  1. Spring Boot(四) Mybatis-MySql

    Spring Boot(四) Mybatis-MySql 0.准备数据库表 -- ---------------------------- -- Table structure for person ...

  2. Spring Boot配置多数据源并实现Druid自动切换

    原文:https://blog.csdn.net/acquaintanceship/article/details/75350653 Spring Boot配置多数据源配置yml文件主数据源配置从数据 ...

  3. spring boot项目自定义数据源,mybatisplus分页、逻辑删除无效解决方法

    Spring Boot项目中数据源的配置可以通过两种方式实现: 1.application.yml或者application.properties配置 2.注入DataSource及SqlSessio ...

  4. Spring Boot与多数据源那点事儿~

    持续原创输出,点击上方蓝字关注我 目录 前言 写这篇文章的目的 什么是多数据源? 何时用到多数据源? 整合单一的数据源 整合Mybatis 多数据源如何整合? 什么是动态数据源? 数据源切换如何保证线 ...

  5. Spring Boot + Druid 多数据源绑定

    date: 2019-12-19 14:40:00 updated: 2019-12-19 15:10:00 Spring Boot + Druid 多数据源绑定 版本环境:Spring Boot 2 ...

  6. 工具篇-Spring boot JPA多数据源

    写这篇博文是因为这个东西坑太多,首先说明下边实现的多数据源不是动态切换的,应该算是静态的. 坑一.pom文件 pom中spring boot以及mysql connector的版本一定要注意. < ...

  7. spring boot 配置双数据源mysql、sqlServer

    背景:原来一直都是使用mysql数据库,在application.properties 中配置数据库信息 spring.datasource.url=jdbc:mysql://xxxx/test sp ...

  8. spring boot:shardingsphere多数据源,支持未分表的数据源(shardingjdbc 4.1.1)

    一,为什么要给shardingsphere配置多数据源? 1,shardingjdbc默认接管了所有的数据源, 如果我们有多个非分表的库时,则最多只能设置一个为默认数据库, 其他的非分表数据库不能访问 ...

  9. spring boot(四):thymeleaf使用详解

    在上篇文章springboot(二):web综合开发中简单介绍了一下thymeleaf,这篇文章将更加全面详细的介绍thymeleaf的使用.thymeleaf 是新一代的模板引擎,在spring4. ...

随机推荐

  1. Linux yun命令使用报错:File "/usr/bin/yum", line 30 except KeyboardInterrupt, e:

    原文参考:https://www.cnblogs.com/caiji/p/7891923.html 使用yum更新perl源,报错 问题出现原因: yum包管理是使用python2.x写的,将pyth ...

  2. SpringMvc 中的实用工具类介绍(包括 ResponseEntity、 RestTemplate、WebUtils 等)

    此部分内容将包含 ResponseEntity. RestTemplate.WebUtils 等 1. ResponseEntity ① Sprring Mvc 中作为方法的返回值使用法 @Reque ...

  3. swust oj 1012

    哈希表(链地址法处理冲突) 1000(ms) 10000(kb) 2542 / 6517 采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用链地址法.建立链表的时候采用尾插法 ...

  4. [Swift]LeetCode367. 有效的完全平方数 | Valid Perfect Square

    Given a positive integer num, write a function which returns True if num is a perfect square else Fa ...

  5. [Swift]LeetCode488. 祖玛游戏 | Zuma Game

    Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), gre ...

  6. [Swift]LeetCode693. 交替位二进制数 | Binary Number with Alternating Bits

    Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will a ...

  7. [Swift]LeetCode796. 旋转字符串 | Rotate String

    We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost ...

  8. [Swift]LeetCode963. 最小面积矩形 II | Minimum Area Rectangle II

    Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these ...

  9. Mysql优化之索引和字段

    Mysql优化是一个老生常谈的问题, 优化的方向也优化很多:从架构层;从设计层;从存储层;从SQL语句层; 今天讲解一下从索引和字段: 字段优化: ①  尽量使用TINYINT.SMALLINT.ME ...

  10. Python内置函数(14)——delattr

    英文文档: delattr(object, name) This is a relative of setattr(). The arguments are an object and a strin ...