springboot 使用mybatis1.3.2和druid-spring-boot-starter1.2.16和spring-boot-starter-parent2.3.9.RELEASE编写一个mybatis的动态连接程序,可随时切换连接源,其中需要准备一个默认mysql库,用于存放动态连接用户与密码的库,连接到这个默认的库之后使用mybatis查询出所有默认的库来进行动态连接其他库,通过传入的指定字符串来判断是要写换哪个数据源,并且不使用配置文件的方式来决定,指定通过传入的额参数决定,请问这个程序该怎么编写,代码
时间: 2024-02-15 19:02:31 浏览: 68
通过springboot+mybatis+druid配置动态数据源
以下是一个简单的代码实现,供参考:
1. 在默认的mysql库中创建一个表来存储动态连接的库的信息:
```sql
CREATE TABLE dynamic_datasource (
id int(11) NOT NULL AUTO_INCREMENT,
db_name varchar(50) NOT NULL COMMENT '数据库名称',
db_url varchar(100) NOT NULL COMMENT '数据库连接url',
db_username varchar(50) NOT NULL COMMENT '数据库用户名',
db_password varchar(50) NOT NULL COMMENT '数据库密码',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
```
2. 在启动类中配置DruidDataSource和SqlSessionFactory:
```java
@SpringBootApplication
public class Application {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource dataSource() {
return new DruidDataSource();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DruidDataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage("com.example.demo.model");
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return sessionFactory.getObject();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
3. 在mapper接口中定义方法查询存储动态连接库信息的表:
```java
@Mapper
public interface DynamicDataSourceMapper {
@Select("SELECT * FROM dynamic_datasource")
List<DynamicDatasource> findAll();
}
```
4. 在Service层中,动态创建数据源,并将其存储到一个Map中:
```java
@Service
public class DynamicDataSourceService {
private final DruidDataSource defaultDataSource;
private final DynamicDataSourceMapper mapper;
private final Map<String, DruidDataSource> dataSources = new HashMap<>();
public DynamicDataSourceService(DruidDataSource dataSource, DynamicDataSourceMapper mapper) {
this.defaultDataSource = dataSource;
this.mapper = mapper;
init();
}
private void init() {
List<DynamicDatasource> datasourceList = mapper.findAll();
for (DynamicDatasource datasource : datasourceList) {
DruidDataSource ds = new DruidDataSource();
ds.setUrl(datasource.getDbUrl());
ds.setUsername(datasource.getDbUsername());
ds.setPassword(datasource.getDbPassword());
dataSources.put(datasource.getDbName(), ds);
}
}
public DruidDataSource getDataSource(String dbName) {
if (StringUtils.isEmpty(dbName)) {
return defaultDataSource;
}
return dataSources.get(dbName);
}
}
```
5. 在Controller中,根据传入的参数,切换数据源,然后进行操作:
```java
@RestController
public class UserController {
private final DynamicDataSourceService service;
public UserController(DynamicDataSourceService service) {
this.service = service;
}
@GetMapping("/users")
public List<User> getUsers(@RequestParam(required = false) String dbName) throws SQLException {
DruidDataSource dataSource = service.getDataSource(dbName);
Connection connection = dataSource.getConnection();
try {
SqlSession sqlSession = new SqlSessionFactoryBuilder().build(connection).openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.findAll();
} finally {
connection.close();
}
}
}
```
这是一个简单的实现,具体的实现方式可能因项目需求而异。另外,代码中省略了一些异常处理和日志记录等细节,请在实际开发中自行添加。
阅读全文