Spring Boot 使用 MyBatis 访问 Oracle 多数据库
Spring Boot 使用 MyBatis 访问 Oracle 多数据库
本文将介绍如何在 Spring Boot 项目中使用 MyBatis 访问多个 Oracle 数据库。
多数据库配置
在 application.properties 文件中配置多个数据源,如下所示:
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db1
spring.datasource.username=user1
spring.datasource.password=pass1
spring.datasource.db2.url=jdbc:oracle:thin:@localhost:1521:db2
spring.datasource.db2.username=user2
spring.datasource.db2.password=pass2
这里配置了两个数据源,分别对应两个不同的 Oracle 数据库。
数据源注入
在 Java 代码中可以使用 @Qualifier 注解指定具体的数据源,如下所示:
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Autowired
@Qualifier("db2")
private DataSource db2;
MyBatis 访问数据库
使用 MyBatis Starter 并定义 Mapper 接口中的 SQL 语句,如下所示:
@Mapper
public interface UserMapper {
@Select('SELECT * FROM users')
List<User> getAllUsers();
}
在 Service 层中注入 Mapper 接口,并调用其中的方法访问数据库:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
}
总结
本文介绍了如何在 Spring Boot 项目中配置多个 Oracle 数据库并使用 MyBatis 框架访问这些数据库。通过在 application.properties 文件中配置数据源,并在 Java 代码中使用 @Qualifier 注解指定数据源,可以实现多数据库访问。
原文地址: https://www.cveoy.top/t/topic/ovkz 著作权归作者所有。请勿转载和采集!