SpringBoot整合多数据源实现

项目架构

 

1.导入相关依赖

 1 <dependency>
 2             <groupId>org.springframework.boot</groupId>
 3             <artifactId>spring-boot-starter-web</artifactId>
 4         </dependency>
 5 
 6         <dependency>
 7             <groupId>org.springframework.boot</groupId>
 8             <artifactId>spring-boot-starter-test</artifactId>
 9             <scope>test</scope>
10         </dependency>
11 
12         <!--freemarker支持-->
13         <dependency>
14             <groupId>org.springframework.boot</groupId>
15             <artifactId>spring-boot-starter-freemarker</artifactId>
16         </dependency>
17 
18         <!-- mysql驱动 -->
19         <dependency>
20             <groupId>mysql</groupId>
21             <artifactId>mysql-connector-java</artifactId>
22         </dependency>
23 
24         <!--整合mybatis-->
25         <dependency>
26             <groupId>org.mybatis.spring.boot</groupId>
27             <artifactId>mybatis-spring-boot-starter</artifactId>
28             <version>1.1.1</version>
29         </dependency>

2.application.properties

 1 ## test1 数据源配置
 2 #spring.datasource.test1.driverClassName=com.mysql.jdbc.Driver
 3 #spring.datasource.test1.jdbc-url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8
 4 #spring.datasource.test1.username=root
 5 #spring.datasource.test1.password=123
 6 
 7 
 8 ## test2 数据源配置
 9 #spring.datasource.test2.driverClassName=com.mysql.jdbc.Driver
10 #spring.datasource.test2.jdbc-url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8
11 #spring.datasource.test2.username=root
12 #spring.datasource.test2.password=123

3.创建datasource包  下TestMyBatisConfig1    

 1 @Configuration
 2 @MapperScan(basePackages = "cn.happy.test1", sqlSessionFactoryRef =  "test1SqlSessionFactory")
 3 public class DataSource1Config {
 4         @Bean(name = "test1DataSource")
 5         @ConfigurationProperties(prefix = "spring.datasource.test1")
 6         @Primary
 7         public DataSource testDataSource() {
 8             return DataSourceBuilder.create().build();
 9         }
10 
11         @Bean(name = "test1SqlSessionFactory")
12         @Primary
13         public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
14             SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
15             bean.setDataSource(dataSource);
16             //读取mybatis小配置文件
17            // bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
18             return bean.getObject();
19         }
20 
21         @Bean(name = "test1TransactionManager")
22         @Primary
23         public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
24             return new DataSourceTransactionManager(dataSource);
25         }
26 
27         @Bean(name = "test1SqlSessionTemplate")
28         @Primary
29         public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
30             return new SqlSessionTemplate(sqlSessionFactory);
31         }
32 }

 

 @Primary注解标识默认使用的数据源 

如果不加启动会报如下错误:意思是有两个数据源  不知需要使用哪个数据源

 

 

3.创建datasource包  下TestMyBatisConfig2

 1 @Configuration
 2 @MapperScan(basePackages = "cn.happy.test2", sqlSessionFactoryRef =  "test2SqlSessionFactory")
 3 public class DataSource2Config {
 4         @Bean(name = "test2DataSource")
 5         @ConfigurationProperties(prefix = "spring.datasource.test2")
 6         public DataSource testDataSource() {
 7             return DataSourceBuilder.create().build();
 8         }
 9 
10         @Bean(name = "test2SqlSessionFactory")
11         public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
12             SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
13             bean.setDataSource(dataSource);
14             //读取mybatis小配置文件
15            // bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml"));
16             return bean.getObject();
17         }
18 
19         @Bean(name = "test2TransactionManager")
20         public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
21             return new DataSourceTransactionManager(dataSource);
22         }
23 
24         @Bean(name = "test2SqlSessionTemplate")
25         public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
26             return new SqlSessionTemplate(sqlSessionFactory);
27         }
28 
29     }

 

4.entity层

 1 /**
 2  * author:  刘涛
 3  *
 4  * @create 2018-04-04 11:18
 5  */
 6 public class Book {
 7 
 8     private Integer bookid;
 9 
10     private String bookname;
11 
12     private Integer bookprice;
13 
14 get  set省略。。
15 }

5.test1下的dao中BookMapperTest1

 1 public interface BookMapperTest1 {
 2 
 3     @Select("select * from book where bookname=#{bookname}")
 4     public Book findByName(@Param("bookname") String bookname);
 5 
 6     @Insert("insert into book(bookname,bookprice) values (#{bookname},#{bookprice})")
 7     public int insertBook(@Param("bookname") String bookname, @Param("bookprice") Double bookprice);
 8 
 9     @Select("select * from book")
10     public Book findBook(@Param("Book") Book book);
11 }

6.test2下的dao中BookMapperTest2

1 public interface BookMapperTest2 {
2 
3     @Select("select * from book where bookname=#{bookname}")
4     public Book findByName(@Param("bookname") String bookname);
5 
6     @Insert("insert into book(bookname,bookprice) values (#{bookname},#{bookprice})")
7     public int insertBook(@Param("bookname") String bookname, @Param("bookprice") Double bookprice);
8 }

7.controller层

@RestController
public class BookController {
    @Autowired
    private BookMapperTest1 bookMapperTest1;

    @Autowired
    private BookMapperTest2 bookMapperTest2;

    @RequestMapping("insert001")
    public String insert001(String bookname,Double bookprice){
        bookMapperTest1.insertBook(bookname,bookprice);
        return "success";
    }

    @RequestMapping("insert002")
    public String insert002(String bookname,Double bookprice){
        bookMapperTest2.insertBook(bookname,bookprice);
        return "success";
    }
}

 

 8.启动项目

test1数据库

test2数据库

 

 

 

转载于:https://www.cnblogs.com/liutao1122/p/8727292.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
springboot可以通过使用dynamic-datasource-spring-boot-starter来实现多数据源整合。该启动器基于springboot,可以快速集成多个数据源。一般的思路是根据自定义的配置数据源信息初始化数据源,并使用druid连接池和mybatis进行相关配置。引用 具体步骤可以包括以下几个方面: 1. 引入相关依赖:在项目的pom.xml文件中添加dynamic-datasource-spring-boot-starter、druid-spring-boot-starter和mybatis-spring-boot-starter等依赖。引用 2. 配置数据源信息:在application.yml或application.properties文件中配置多个数据源的信息,包括数据库连接地址、用户名、密码等。可以使用@ConfigurationProperties注解来绑定配置文件中的数据源信息到对应的实体类中。 3. 初始化数据源:使用Configuration类来初始化数据源。可以自定义一个DynamicDataSourceConfig类,并在其中使用@Bean注解来配置数据源。在该类中可以通过读取配置文件的方式来获取数据源信息,并将其初始化为对应的数据源。 4. 配置mybatis:在application.yml或application.properties文件中配置mybatis的相关信息,如mapper的扫描路径等。 通过以上步骤,就可以实现springboot多数据源整合。当然,以上只是一个基本的思路,具体实现还需要根据项目的实际需求进行调整和扩展。引用<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot实现多数据源的两种方式](https://blog.csdn.net/m0_67401761/article/details/126114612)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringBoot整合多数据源的两种方式](https://blog.csdn.net/hongs468/article/details/128469985)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值