一、引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join</artifactId>
<version>1.2.4</version>
</dependency>
这里建议使用此版本!!!
二、修改yml文件
server:
port: 10001
spring:
application:
name: special_work_upload
datasource:
dynamic:
primary: master
strict: false # 是否启用严格模式,默认不启动. 严格模式下未匹配到数据源直接报错, 非严格模式下则使用默认数据源primary所设置的数据源
datasource:
master:
url: jdbc:mysql://localhost:3306/enterprise_psm?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: # 用户名
password: # 密码
driver-class-name: com.mysql.cj.jdbc.Driver
slave_1:
url: jdbc:mysql://localhost:3306/enterprise_authorization?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: # 用户名
password: # 密码
driver-class-name: com.mysql.cj.jdbc.Driver
#
#mybatis-plus:
# configuration:
# # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
三、修改主启动类
添加@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
四、自定义注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@DS("master")
public @interface Master {
}
Slave也同样如此
五、添加Mapper类,指定数据源
@Mapper
@Slave
public interface UserMapper extends MPJBaseMapper<User> {
}
六、添加Service类以及其实现
public interface UserService extends IService<User> {
/**
* 获取分析人信息
* @return
*/
List<AnalystVO> getAnalystList();
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
@Resource
private WorkJsaMapper workJsaMapper;
@Override
public List<AnalystVO> getAnalystList() {
List<AnalystVO> analystVOList = new ArrayList<>();
List<Long> analystList = workJsaMapper.selectList(null).stream().map(WorkJsa::getAnalyst).collect(Collectors.toList());
this.getBaseMapper().selectBatchIds(analystList).parallelStream().forEach(user -> {
AnalystVO analystVO = new AnalystVO();
analystVO.setAnalyst(user.getId());
analystVO.setUserName(user.getNickName());
analystVOList.add(analystVO);
});
return analystVOList;
}
}