需求:springboot后台需要访问其他数据库的数据,同时操作多个数据库的数据。
pom.xml文件配置:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
application.yml配置:
# 注意这里前面的空格很重要,否则不起作用
spring:
datasource:
dynamic:
primary: aaa
strict: false
initialization-mode: always
aaa:
longi:
url: jdbc:mysql:urla
username: root
password: aaaa
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
connection-timeout: 30000 # 连接超时时间,默认30秒
idle-timeout: 600000 # 连接空闲超时时间
max-lifetime: 120000 # 连接最大存活时间,30分钟
bbb:
url: jdbc:urlb
username: root
password: bbbb
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
connection-timeout: 30000 # 连接超时时间,默认30秒
idle-timeout: 600000 # 连接空闲超时时间
max-lifetime: 120000 # 连接最大存活时间,30分钟
ccc:
url: jdbc:urlc
username: root
password: cccc
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
connection-timeout: 30000 # 连接超时时间,默认30秒
idle-timeout: 600000 # 连接空闲超时时间
max-lifetime: 120000 # 连接最大存活时间,30分钟
mapper文件代码:
@DS("aaa")
@Mapper
public interface DeviceMapper {
@Select("select * from ${tableName} where type = #{type};")
List<DeviceStatus> getDeviceStatusByType(String tableName, String type);
}
service文件代码:
@Service
public class UserService {
@Autowired
AAAMapper aaarMapper;
@Autowired
BBBMapper bbbMapper;
@Autowired
CCCMapper cccMapper;
public Object SelectUser(String phone)
{
AAAUser aaaUser = aaarMapper.SelectUser(phone);
if (aaaUser != null)
return aaaUser ;
BBBUser bbbUser = bbbMapper.SelectUser(phone);
if (bbbUser != null)
return bbbUser ;
CCCUser cccUser = cccMapper.SelectUser(phone);
if (cccUser != null)
return cccUser ;
return null;
}
}
效果: