springboot中两个数据库的两个表连接执行sql语句,sql是在mapper中写的,显示表或视图不存在
时间: 2024-03-20 10:39:54 浏览: 24
如果在Spring Boot中使用MyBatis进行数据库操作,需要在配置文件中将两个数据源配置到对应的Mapper中,例如:
```
# 第一个数据源配置
spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1
spring.datasource.primary.username=root
spring.datasource.primary.password=root
# 第二个数据源配置
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
# MyBatis配置
mybatis.mapper-locations=classpath*:mapper/*.xml
# 第一个数据源的Mapper配置
mybatis.primary.mapper-locations=classpath*:mapper/primary/*.xml
mybatis.primary.config-location=classpath:mybatis-config-primary.xml
# 第二个数据源的Mapper配置
mybatis.secondary.mapper-locations=classpath*:mapper/secondary/*.xml
mybatis.secondary.config-location=classpath:mybatis-config-secondary.xml
```
在Mapper中使用@Qualifier注解标识要使用的数据源,例如:
```
@Mapper
@Qualifier("primarySqlSessionFactory")
public interface PrimaryMapper {
@Select("SELECT * FROM db1.table1 t1 LEFT JOIN db2.table2 t2 ON t1.id = t2.id")
List<Map<String, Object>> selectData();
}
@Mapper
@Qualifier("secondarySqlSessionFactory")
public interface SecondaryMapper {
// ...
}
```
需要注意的是,不同数据源的Mapper需要使用不同的SqlSessionFactory和TransactionManager,需要在配置文件中分别进行配置。同时,在Mapper中写SQL语句时,需要使用完整的表名(包括数据库名)。