springboot整合mybatis多数据源

·  阅读 1022

引入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.14</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
复制代码

修改配置文件

spring:
datasource:
#使用druid连接池
druid:
#数据源1的名称
one:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.211.128:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
#数据源2的名称
two:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.211.129:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
复制代码

mybatis配置类

多个数据源配置相似,修改参数即可


@Configuration
//指定扫描的dao包和SqlSession实例
@MapperScan(basePackages = "demo.springboot.multipledatasource.dao1", sqlSessionTemplateRef="oneSqlSessionTemplate")
public class DataSource1Config {

/**
* 连接池
* @return
*/

@Bean
@Primary
@ConfigurationProperties("spring.datasource.druid.one")
public DataSource oneDataSource(){
return DruidDataSourceBuilder.create().build();
}

/**
* SqlSessionFactory
* @param dataSource
* @return
* @throws Exception
*/

@Bean
@Primary
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//mapper文件位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/one/*.xml"));
return bean.getObject();
}

/**
* 事务管理器
* 注解@Primary:当程序中使用@Transactional时,优先使用该事务管理器。
* 如果不使用@Primary注解,需要在@Transactional(value="oneTransactionManager")指定事务管理器
* @param dataSource
* @return
*/

@Bean
@Primary
public DataSourceTransactionManager oneTransactionManager(@Qualifier("oneDataSource")DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}

/**
* SqlSession实例
* @param sqlSessionFactory
* @return
*/

@Bean
@Primary
public SqlSessionTemplate oneSqlSessionTemplate(@Qualifier("oneSqlSessionFactory")SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
复制代码

DAO与实体类

public interface User1DAO {

List<User> selectAll();
}
@Data
public class User {

private String username;

private String age;
}
复制代码

测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipleDatasourceApplicationTests {

@Autowired
private User1DAO user1DAO;

@Autowired
private User2DAO user2DAO;

@Test
public void test() {
List<User> users1 = user1DAO.selectAll();
System.out.println(users1);
List<User> users2 = user2DAO.selectAll();
System.out.println(users2);
}
}
复制代码

项目路径


作者博客

作者公众号 在这里插入图片描述

分类:
后端
标签:
分类:
后端
标签: