# 动态数据源使用
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/02.%20%E5%90%8E%E7%AB%AF%E5%BC%80%E5%8F%91/01.%20%E5%90%8E%E7%AB%AF%E8%A7%84%E8%8C%83/05.%20%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3/%E5%8A%A8%E6%80%81%E6%95%B0%E6%8D%AE%E6%BA%90%E4%BD%BF%E7%94%A8


# 动态数据源使用

## 动态数据源使用

Druid 动态数据源

### 一、动态数据源配置

/src/main/resources/application.yml

```js
datasource:
   datasource: 
          master: 
            url: jdbc:mysql://127.0.0.1:3306/jeecg-boot?characterEncoding=UTF-8&useUnicode=true&useSSL=false
            username: root
            password: root
            driver-class-name: com.mysql.jdbc.Driver   
          multi-datasource1: 
            url: jdbc:mysql://localhost:3306/jeecg-boot2?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
            username: root
            password: root
            driver-class-name: com.mysql.jdbc.Driver
```

复制

master 为主数据源，系统默认数据源

multi-datasource1 ：自定义的第三方数据源，multi-datasource1 名称随便定义

### 二、动态数据源使用

使用 @DS 切换数据源。

@DS 可以注解在方法上和类上，同时存在方法注解优先于类上注解。

注解在 service 实现或 mapper 接口方法上，但强烈不建议同时在 service 和 mapper 注解。 (可能会有问题)

| 注解 | 结果 |
| --- | --- |
| 没有@DS | 默认数据源 |
| @DS("dsName") | dsName 可以为组名也可以为具体某个库的名称 |

代码示例：

```js
@Service
@DS("multi-datasource1")
public class JeecgDemoServiceImpl implements JeecgDemoService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public List<Map<String, Object>> selectAll() {
    return  jdbcTemplate.queryForList("select * from user");
  }
  
  @Override
  @DS("multi-datasource2")
  public List<Map<String, Object>> selectByCondition() {
    return  jdbcTemplate.queryForList("select * from user where age >10");
  }
}
```

复制
