Thanks to visit codestin.com
Credit goes to help.jeecg.com

跳到主要内容

动态数据源使用

Druid 动态数据源

一、动态数据源配置

/src/main/resources/application.yml

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可以为组名也可以为具体某个库的名称

代码示例:

@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");
}
}