mapper怎么切换数据源?
时间: 2023-05-15 11:05:51 浏览: 88
对于切换数据源,可以使用 MyBatis 提供的动态数据源切换功能,具体实现方式如下:
1. 在配置文件中配置多个数据源,如:
```
<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db1"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db2"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
```
2. 在 MyBatis 的 Mapper 接口中定义多个方法,每个方法对应一个数据源,如:
```
public interface UserMapper1 {
@Select("select * from user")
List<User> getAllUsers();
}
public interface UserMapper2 {
@Select("select * from user")
List<User> getAllUsers();
}
```
3. 在 Service 层中使用动态数据源切换功能,如:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper1 userMapper1;
@Autowired
private UserMapper2 userMapper2;
@Override
public List<User> getAllUsers(String dataSource) {
if ("dataSource1".equals(dataSource)) {
DynamicDataSourceContextHolder.setDataSourceKey("dataSource1");
return userMapper1.getAllUsers();
} else if ("dataSource2".equals(dataSource)) {
DynamicDataSourceContextHolder.setDataSourceKey("dataSource2");
return userMapper2.getAllUsers();
}
return null;
}
}
```
其中,DynamicDataSourceContextHolder 是一个线程安全的数据源上下文管理器,用于存储当前线程使用的数据源 key。在每次访问数据库之前,需要先设置当前线程使用的数据源 key,访问完毕后需要清除当前线程使用的数据源 key。