多数据源是在开发中比较常见的需求之一。对于企业级的应用系统来说,通常会面临多个数据库的操作,比如公共的数据库和业务数据的数据库等。在这种情况下,实现多数据源是至关重要的。Spring Boot 是一个非常流行的 Java 开发框架,它提供了一种方便的方式来实现多数据源。通过配置文件中的数据源属性和注解,开发人员可以轻松地切换不同的数据源。
进入今天的主题——在Spring Boot 项目中整合mybatis多数据源,其实很简单,其实并不难。
整体项目结构以及数据源配置application.yml:
看代码吧.
1.第一个数据源配置(作为主数据源)
/**
* @author Lensen
* @desc
* @since 2018/9/19 10:22
*/
@Configuration
@MapperScan(basePackages = PrimaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.primary";
static final String MAPPER_LOCATION = "classpath:mapper/primary/*.xml";
@Value("${primary.datasource.url}")
private String url;
@Value("${primary.datasource.username}")
private String user;
@Value("${primary.datasource.password}")
private String password;
@Value("${primary.datasource.driverClassName}")
private String driverClass;
@Bean(name = "primaryDataSource")
@Primary
public DataSource primaryDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "primaryTransactionManager")
@Primary
public DataSourceTransactionManager primaryTransactionManager() {
return new DataSourceTransactionManager(primaryDataSource());
}
@Bean(name = "primarySqlSessionFactory")
@Primary
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(primaryDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(PrimaryDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
2.第二个数据源配置
/**
* @author Lensen
* @desc
* @since 2018/9/19 10:22
*/
@Configuration
@MapperScan(basePackages = SecondaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfig {
static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.secondary";
static final String MAPPER_LOCATION = "classpath:mapper/secondary/*.xml";
@Value("${secondary.datasource.url}")
private String url;
@Value("${secondary.datasource.username}")
private String user;
@Value("${secondary.datasource.password}")
private String password;
@Value("${secondary.datasource.driverClassName}")
private String driverClass;
@Bean(name = "secondaryDataSource")
public DataSource secondaryDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "secondaryTransactionManager")
public DataSourceTransactionManager secondaryTransactionManager() {
return new DataSourceTransactionManager(secondaryDataSource());
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(secondaryDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(SecondaryDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
其他业务逻辑代码就不贴了,代码可在我的github上找到。文章末尾有地址。
application.yml
## primary 数据源配置
primary:
datasource:
url: jdbc:mysql://localhost:3306/javashop?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
driverClassName: com.mysql.jdbc.Driver
## secondary 数据源配置
secondary:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
driverClassName: com.mysql.jdbc.Driver
pom.xml
<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>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
3.测试数据源
@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipartMybatisDatasourceApplicationTests {
@Autowired
UserServiceImpl userService;
@Autowired
HomeServiceImpl homeService;
@Test
public void contextLoads() {
UserEntity userEntity = new UserEntity();
userEntity.setId(1L);
userEntity.setName("Lensen");
userEntity.setMobile("13738718660");
HomeEntity homeEntity = new HomeEntity();
homeEntity.setId(1L);
homeEntity.setUserId(1L);
homeEntity.setCity("杭州");
homeEntity.setTown("西湖区");
userService.saveUser(userEntity);
homeService.saveHome(homeEntity);
userService.getUserById(1L);
homeService.getHomeByUserId(1L);
}
}
4.总结
上一篇教程:精通Spring Boot: 分页查询功能的实现
Spring Boot 的多数据源特性是非常强大的,它可以帮助开发者快速实现在一个应用程序中操作多个数据库。以下是要点总结:
多数据源的配置可以在应用程序的配置文件中完成,使得配置变得非常简单和易于维护。对于多个数据源的操作,我们可以使用 Spring Boot 提供的多个注解来进行管理。
多数据源的切换可以根据需要进行配置,切换也是非常简单的。每一个数据源都需要一个对应的数据库连接池,这可以在 Spring Boot 的配置文件中配置。
综上所述,Spring Boot 的多数据源实现非常值得开发者尝试,可以帮助开发者提高开发效率和代码的可维护性。
代码可以在我的github.com中找到
[…] 精通Spring Boot:整合Mybatis多数据源 突然想mybatis虽然功能强大,但是对sql的要求还是算高的。Spring Data […]