SpringBoot2 Mybatis3 多数据源

本文以分包的方式来区分不同的数据源,也就是不同的包,连接不同的数据库
开发背景
1. SpringBoot2.0.4
2. Mybatis3.4.4
3. jdk1.8

dataSource1 连接数据库为springboot(调用UserTest1Service中方法,即操作springboot 数据库)
dataSource2 连接数据库为springboot1(调用UserTest2Service中方法,即操作springboot1 数据库)

项目结构
—-这里写图片描述这里写图片描述

pom文件依赖

<dependencies>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

    </dependencies>

1.数据源配置文件application.yml

##数据源1
##driverClassName driver-class-name
spring.datasource.test1.driver-class-name: com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url:  jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.test1.username: root
spring.datasource.test1.password: root

#数据源2
spring.datasource.test2.driver-class-name: com.mysql.jdbc.Driver
spring.datasource.test2.jdbc-url:  jdbc:mysql://127.0.0.1:3306/springboot1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.test2.username: root
spring.datasource.test2.password: root

不要怀疑,application.yml内容就只有这么多接下来看具体代码

2.dataSource1下mapper层代码(dataSource2下mappe2代码相同)

这里写图片描述

@Mapper
public interface UserMapper {

     @Select("SELECT * FROM USER WHERE id = #{id}")
     User selectUser(Integer id);

     @Select("SELECT * FROM USER ")
     List<User> findByPage();

     @Insert("insert into user ( name, age, password) values(#{name},#{age},#{password})")
     Integer save(User user);
}

3.dataSource1下UserTest1Service层代码(dataSource2下UserTest2Service代码相同)

这里写图片描述

public interface UserTest1Service {
     User selectUser(Integer id);
     PageInfo<User> findByPage(Integer pageNum, Integer pageSize);

     Integer save(User user);
}

4.dataSource1下UserServicetTest1Impl层代码(dataSource2UserServicetTest2Impl代码相同)

这里写图片描述

@Service("userService1")
public class UserServicetTest1Impl implements UserTest1Service {
    @Autowired
    private UserMapper userDao;

    @Override
    public PageInfo<User> findByPage(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userDomains = userDao.findByPage();
        PageInfo result = new PageInfo(userDomains);
        return result;
    }

    @Override
    public Integer save(User user) {
        return this.userDao.save(user);
    }

    @Override
    public User selectUser(Integer id) {
        System.out.println();
        return userDao.selectUser(id);
    }

5.公用模块model下User实体类

public class User {

    private Integer id;
    private String name;
    private Integer age;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

6.数据源配置类

这里写图片描述

  1. DataSource1Config.java
@Configuration //注册到springboot 容器中
@MapperScan(basePackages = "com.jessDl.dataSource1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")
public class DataSource1Config {

    @Bean(name = "test1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test1SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //加载其他文件,如mapper.xml
       // bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
        return bean.getObject();
    }

    //事务管理
    @Bean(name = "test1TransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "test1SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
  1. DataSource2Config.java
@Configuration //注册到springboot 容器中
@MapperScan(basePackages = "com.jessDl.dataSource2", sqlSessionTemplateRef  = "test2SqlSessionTemplate")
public class DataSource2Config {

    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //加载其他文件,如mapper.xml
       // bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
        return bean.getObject();
    }

    //事务管理
    @Bean(name = "test2TransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "test2SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

7.DataSourcesController

@RestController
@RequestMapping("/datasource")
public class DataSourcesController {
    @Autowired
    @Qualifier("userService1")
    private UserTest1Service userService1;

    @Autowired
    @Qualifier("userService2")
    private UserTest2Service userService2;

    @RequestMapping("/user1")
    public User getUser(){
        return this.userService1.selectUser(1);
    }

    @RequestMapping("/user2")
    public User getUser2(){
        return this.userService2.selectUser(1);
    }

    @RequestMapping("/save")
    public Integer save1(){
        User user = new User();
        user.setAge(22);
        user.setName("多数据源");
        user.setPassword("3333333");
        return this.userService2.save(user);
    }

    @RequestMapping("findPage")
    public PageInfo<User> findByPage(@RequestParam(name = "pageNum", required = false, defaultValue = "1")
                                             int pageNum,
                                     @RequestParam(name = "pageSize", required = false, defaultValue = "5")
                                             int pageSize){
        return userService2.findByPage(pageNum,pageSize);
    }
}

8启动类DataSourceApplication

@SpringBootApplication
public class DataSourceApplication {
    public static void main(String[] args) {
        SpringApplication.run(DataSourceApplication.class, args);
    }
}

启动后在浏览器访问http://localhost:8080/datasource/save2,往数据源2(数据库springboot1)中user表插入一条数据
这里写图片描述
返回1,说明已经添加数据成功
这里写图片描述
好了,SpringBoot Mybatis 已分包的方式实现 多数据源配置到这里就结束了,如果有误或者撸友们有其他方式欢迎提出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值