SpringBoot2整合多數據源--基於分包結構(一)

SpringBoot-2.2.1.RELEASE版本-整合多數據源-基於分包結構

需求:項目如何連接、操作多數據庫?

MySQL數據庫擁有test、test1兩個數據庫,需要操作兩個數據庫的user表。爲了方便操作,兩個數據庫的user表相同。

SpringBoot2整合多數據源:

項目結構:

配置多數據源:application.yml文件內容如下:

spring:
  datasource:
    test:
     jdbc-url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
     username: root
     password: 123456
     driver-class-name: com.mysql.jdbc.Driver
    test1:
     jdbc-url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
     username: root
     password: 123456
     driver-class-name: com.mysql.jdbc.Driver

 

數據庫連接配置:

test數據庫:

package com.ls.springboot.config.test;


import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * @title: 數據庫連接配置類
 * @description: test數據庫
 * @author: LiShun
 * @time: 2020/6/14 15:08
 * @since Java8
 */
@Configuration
@MapperScan(basePackages = "com.ls.springboot.test.mapper", sqlSessionTemplateRef = "TestSqlSessionTemplate")
public class TestDataSourceConfig {
    /**
     * 創建dataSource
     * @return
     */
    @Bean(name = "TestDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     *
     * @description:  test sql會話工廠
     * @return:
     * @author: LiShun
     * @time: 2019/12/17 14:09
     */
    @Bean(name = "TestSqlSessionFactory")
    public SqlSessionFactory TestSqlSessionFactory(@Qualifier("TestDataSource")DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    /**
     *
     * @description:  test 創建事務管理器
     * @return:
     * @author: LiShun
     * @time: 2019/12/17 14:09
     */
    @Bean(name = "TestTransactionManager")
    public DataSourceTransactionManager TestTransactionManager(@Qualifier("TestDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "TestSqlSessionTemplate")
    public SqlSessionTemplate TestSqlSessionTemplate(
            @Qualifier("TestSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

 

test1數據庫:

package com.ls.springboot.config.test;


import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * @title: 數據庫連接配置類
 * @description: test數據庫
 * @author: LiShun
 * @time: 2020/6/14 15:08
 * @since Java8
 */
@Configuration
@MapperScan(basePackages = "com.ls.springboot.test.mapper", sqlSessionTemplateRef = "TestSqlSessionTemplate")
public class TestDataSourceConfig {
    /**
     * 創建dataSource
     * @return
     */
    @Bean(name = "TestDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     *
     * @description:  test sql會話工廠
     * @return:
     * @author: LiShun
     * @time: 2019/12/17 14:09
     */
    @Bean(name = "TestSqlSessionFactory")
    public SqlSessionFactory TestSqlSessionFactory(@Qualifier("TestDataSource")DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    /**
     *
     * @description:  test 創建事務管理器
     * @return:
     * @author: LiShun
     * @time: 2019/12/17 14:09
     */
    @Bean(name = "TestTransactionManager")
    public DataSourceTransactionManager TestTransactionManager(@Qualifier("TestDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "TestSqlSessionTemplate")
    public SqlSessionTemplate TestSqlSessionTemplate(
            @Qualifier("TestSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

 

注:配置SpringBoot2版本時,不需要加@Primary註解。在SpringBoot1時,test1加@Primary主鍵,標識爲單例模式,不然運行會報錯。 

service:

 test:

package com.ls.springboot.test.service;

import com.ls.springboot.test.mapper.UserMapperTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceTest {
   @Autowired
   private UserMapperTest userMapperTest;

   public String insertTest(String name, Integer age) {
      userMapperTest.insert(name, age);
      return "success";
   }
}

 

test1:

package com.ls.springboot.test1.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;


/**
 * @author lishun
 */
@Mapper
public interface UserMapperTest1 {
   @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
   int insert(@Param("name") String name, @Param("age") Integer age);
}

mapper:

test:

package com.ls.springboot.test.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

/**
 * @author lishun
 */
@Mapper
public interface UserMapperTest {
   @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
   int insert(@Param("name") String name, @Param("age") Integer age);
}

test1:

package com.ls.springboot.test1.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;


/**
 * @author lishun
 */
@Mapper
public interface UserMapperTest1 {
   @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
   int insert(@Param("name") String name, @Param("age") Integer age);
}

 

Controller:

package com.ls.springboot.controller;


import com.ls.springboot.test.service.UserServiceTest;
import com.ls.springboot.test1.service.UserServiceTest1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
   @Autowired
   private UserServiceTest userServiceTest;
   @Autowired
   private UserServiceTest1 userServiceTest1;


   @RequestMapping("/insertTest")
   public String insertTest(String name, Integer age) {
      userServiceTest.insertTest(name, age);
      return "success";
   }

   @RequestMapping("/insertTest1")
   public String insertTest1(String name, Integer age) {
      userServiceTest1.insertTest1(name, age);
      return "success";
   }
}

 

 

運行測試:

查看數據庫添加數據成功,至此,項目已經能對test、test1數據庫user表進行操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章