直接因为懒就在网上随便找了个方法直接cv 后面发现不行,公司统一技术栈 然后又不能用mybatis-plus。 考虑到用注解方式得每个方法加注解就比较麻烦
然后就参考了这篇博客园大佬的文章,后面又经常有人在贴下问我解决这个问题又没有,还有北京的小姐姐打电话同问,于是本不喜欢写文章的我还是给大家分享一下cv拿去用,但是还是会给大家讲一下原理
这是博客园大佬参考链接 :https://www.cnblogs.com/aizen-sousuke/p/11756279.html#4883041,欢迎cv 但是不欢迎这个方法不行,就换个帖子cv 这是没有开拓思维的!
我参考文章的时候采用的是第一种方式 也就是如下方式
1.2 application.yml 配置文件
server:
port: 8080 # 启动端口
spring:
datasource:
db1: # 数据源1
jdbc-url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
db2: # 数据源2
jdbc-url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
注意事项
- 各个版本的 springboot 配置 datasource 时参数有所变化,例如低版本配置数据库 url 时使用 url 属性,高版本使用 jdbc-url 属性,请注意区分。
1.3 建立连接数据源的配置文件
第一个数据源配置
@Configuration
@MapperScan(basePackages = "com.example.multipledatasource.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DataSourceConfig1 {
@Primary // 表示这个数据源是默认数据源, 这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)
@Bean("db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db1") //读取application.yml中的配置参数映射成为一个对象
public DataSource getDb1DataSource(){
return DataSourceBuilder.create().build();
}
@Primary
@Bean("db1SqlSessionFactory")
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// mapper的xml形式文件位置必须要配置,不然将报错:no statement (这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致)
bean.setMap