在 Spring Boot 中整合 MyBatis 多数据源是一种常见的需求,尤其是在需要操作多个数据库或实现读写分离的场景中。以下是整合 MyBatis 多数据源的详细步骤和应用示例:
1. 引入依赖
在 pom.xml 中引入 MyBatis 和多数据源相关的依赖:
<dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis Starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- Druid 数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.8</version> </dependency> </dependencies>
2. 配置多数据源
在 application.yml 中配置多个数据源:
spring: datasource: primary: url: jdbc:mysql://localhost:3306/db1 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource secondary: url: jdbc:mysql://localhost:3306/db2 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource
3. 配置数据源 Bean
在 Spring Boot 中配置多个数据源和对应的 SqlSessionFactory 和 SqlSessionTemplate:
import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.example.mapper.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate") public class PrimaryDataSourceConfig { @Bean(name = "primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.primary") @Primary public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "primarySqlSessionFactory") @Primary public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml")); return bean.getObject(); } @Bean(name = "primarySqlSessionTemplate") @Primary public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.example.mapper.secondary", sqlSessionTemplateRef = "secondarySqlSessionTemplate") public class SecondaryDataSourceConfig { @Bean(name = "secondaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "secondarySqlSessionFactory") public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/secondary/*.xml")); return bean.getObject(); } @Bean(name = "secondarySqlSessionTemplate") public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
4. 编写 Mapper 和 XML
在 src/main/resources/mapper 目录下分别创建 primary 和 secondary 文件夹,并编写对应的 Mapper XML 文件。
例如,primary 数据源的 Mapper XML:
<!-- src/main/resources/mapper/primary/UserMapper.xml --> <mapper namespace="com.example.mapper.primary.UserMapper"> <select id="selectUserById" resultType="com.example.entity.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper>
secondary 数据源的 Mapper XML:
<!-- src/main/resources/mapper/secondary/OrderMapper.xml --> <mapper namespace="com.example.mapper.secondary.OrderMapper"> <select id="selectOrderById" resultType="com.example.entity.Order"> SELECT * FROM order WHERE id = #{id} </select> </mapper>
5. 编写 Service 和 Controller
在 Service 层中分别调用不同数据源的 Mapper:
import com.example.mapper.primary.UserMapper; import com.example.mapper.secondary.OrderMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { @Autowired private UserMapper userMapper; @Autowired private OrderMapper orderMapper; public User getUserById(int id) { return userMapper.selectUserById(id); } public Order getOrderById(int id) { return orderMapper.selectOrderById(id); } }
在 Controller 层中调用 Service:
import com.example.entity.User; import com.example.entity.Order; import com.example.service.MyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/user/{id}") public User getUser(@PathVariable int id) { return myService.getUserById(id); } @GetMapping("/order/{id}") public Order getOrder(@PathVariable int id) { return myService.getOrderById(id); } }
6. 运行和测试
启动 Spring Boot 应用后,访问以下接口:
/user/{id}:从 primary 数据源查询用户信息。
/order/{id}:从 secondary 数据源查询订单信息。
总结
通过以上步骤,可以在 Spring Boot 中成功整合 MyBatis 多数据源,并实现对多个数据库的操作。这种方式适用于需要读写分离、多数据库操作等场景。
0条评论
点击登录参与评论