1.描述
Srpingboot 项目中 使用多个数据源 如 mysql oracle 等(为什么有这种需求?)
使用 pagehelper 自动获取分页
2 . 方法
2.1 @DS("oracle")
注解放在类上 或方法上 标识这个类或方法使用的是orcale数据库 其余不变
@DS("oracle") // 当前类所有方法都使用 oracle
@RestController
@RequestMapping("/plat/test")
public class demoController {
@Autowired
private IDemo domeImpl;
@PostMapping("/gettest")
@DS("oracle") //仅当前方法使用 oracle
public String gettest(){
Map lst = domeImpl.getDemo("111");
return lst.toString();
}
}
2.2 在配置文件增加配置
spring:
datasource:
# 不能删除 基础框架jar包中有使用! 如果类中没有使用到 @Value("${spring.datasource.url}")
#可以删除
url: jdbc:mysql://192.168.0.0:3306/***?useUnicode=true&characterEncoding=utf8
username: ****
password: *****
driverClassName: com.mysql.cj.jdbc.Driver
dynamic:
primary: mysql #设置默认的数据源或者数据源组,默认值即为mysql
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
mysql: # 类中 或方法中使用注解的名称 @DS("mysql")
url: jdbc:mysql://192.168.0.0:3306/***?useUnicode=true&characterEncoding=utf8
username: ****
password: ****
driverClassName: com.mysql.cj.jdbc.Driver
oracle: # 类中 或方法中使用注解的名称 @DS("oracle")
url: jdbc:oracle:thin:@172.168.0.0:1521/***
username: ***
password: ***
driverClassName: oracle.jdbc.OracleDriver
2.3 引入jar包
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.6.1</version>
</dependency>
3.pagehelper 根据数据库url 自动添加分页
3.1 配置文件添加
pagehelper:
# helperDialect: mysql 删除默认 使用mysql分页配置
reasonable: true
supportMethodsArguments: true
params: count=countSql
banner: false
auto-dialect: true # 自动分页
autoRuntimeDialect: true #根据运行数据库url自动分页 注意不是 auto-runtime-dialect: true
3.2 代码中使用分页
@Override
public PageList<Map> getCount(Vo vo) {
PageHelper.startPage(null == vo.getPageIndex() ? 1 : vo.getPageIndex(), null == vo.getPageSize() ? 15 : vo.getPageSize());
//只有在 startPage 下这个查询才能分页
List<Map> pageList = jkMapper.getCount(vo);
PageInfo page = new PageInfo<>(pageList);
return new PageList(page.getTotal(), page.getList());
}
4.注意
使用 pagehelper 配置文件中 需要用 autoRuntimeDialect: true
正确使用
pagehelper:
auto-dialect: true # 自动分页
autoRuntimeDialect: true #根据运行数据库url自动分页 注意不是 auto-runtime-dialect: true
不能使用 auto-runtime-dialect: true 这个没用 并且是 idea 自动提示的!!!!
在同一方法中使用 不同数据源 需要新建事务
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
@DS("oracle")
public Object select (){
List list = OracleMapper.update(); //oracle 数据库
Mysql.mysqlinsert(); // Mysql 数据库
}
@DS("mysql")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW) // 新建事务
//mysql 库
public Object mysqlinsert(){
MsqMapper.insert()
}