springboot+mybatis-plus实现两个数据库的两张表相连查询数据
时间: 2024-03-20 16:45:26 浏览: 201
可以使用Mybatis-Plus提供的多数据源配置,然后在查询时指定使用哪个数据源。以下是示例代码:
1. 配置多数据源
在application.yml文件中配置两个数据源:
```yaml
spring:
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: root
slave:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: root
```
在配置类中添加多数据源配置:
```java
@Configuration
@MapperScan(basePackages = "com.example.mapper")
public class DataSourceConfig {
@Bean("master")
@ConfigurationProperties("spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean("slave")
@ConfigurationProperties("spring.datasource.slave")
public DataSource slaveDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactory(@Qualifier("master") DataSource masterDataSource,
@Qualifier("slave") DataSource slaveDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(routingDataSource(masterDataSource, slaveDataSource));
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sessionFactory.setMapperLocations(resolver.getResources("classpath*:mapper/**/*.xml"));
return sessionFactory.getObject();
}
@Bean
public DataSource routingDataSource(@Qualifier("master") DataSource masterDataSource,
@Qualifier("slave") DataSource slaveDataSource) {
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("master", masterDataSource);
dataSourceMap.put("slave", slaveDataSource);
RoutingDataSource routingDataSource = new RoutingDataSource();
routingDataSource.setDefaultTargetDataSource(masterDataSource);
routingDataSource.setTargetDataSources(dataSourceMap);
return routingDataSource;
}
}
```
2. 实现两个表的关联查询
在mapper中编写SQL语句,可以使用Mybatis-Plus提供的Wrapper类来实现多条件查询。
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user u JOIN order o ON u.id = o.user_id WHERE u.id = #{userId}")
@Results({
@Result(column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "id", property = "orders", many = @Many(select = "com.example.mapper.OrderMapper.selectByUserId")),
})
User selectUserWithOrders(@Param("userId") Long userId);
}
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
@Select("SELECT * FROM order WHERE user_id = #{userId}")
List<Order> selectByUserId(Long userId);
}
```
在service中调用mapper方法即可实现两个表的关联查询。
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserWithOrders(Long userId) {
return userMapper.selectUserWithOrders(userId);
}
}
```
阅读全文