Springboot2.x整合mybatis多数据源(注解完整版,亲测成功)

并发量的不断增加,单个数据库承受不了这么大的压力,因此一个项目使用多个数据库也越来越重要,当然使用数据库的模式可能不一样,比如说主从模式、分布式模式。不管是哪种模式都是使用的多数据源。Springboot整合mybatis实现多数据源有两种方式:分包和AOP。这里使用的分包,因为层次更加清晰。

以下代码在评论区会给出github地址。OK,开始整合。

一、环境配置

名称 版本
Idea 2018专业版(已破解)
Maven 3.6.0
SpringBoot 2.2.2
Mybatis 5.1.44
Navicat(可视化工具) 12(已破解)
jdk 1.8

环境很简单,下面开始整合。

二、代码整合

新建一个Springboot项目名字叫做SpringbootMybatisMutil,开始下面的操作。

第一步:添加依赖

<dependencies>
        <!--springboot开发web项目的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 加载mybatis整合springboot -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- MySQL的jdbc驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
 </dependencies>

第二步:修改属性文件

#数据库1的配置
spring.datasource.test1.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url = jdbc:mysql://localhost:3306/uav
?useUnicode=true&characterEncoding=utf-8&useSSL=false
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://localhost:3306/uav2
?useUnicode=true&characterEncoding=utf-8&useSSL=false
#上面的这一行在uav后面添加,代码太长我换成了两行,
spring.datasource.test2.username = root
spring.datasource.test2.password = root
#mybatis依赖
mybatis.type-aliases-package = com.fdd.bean

第三步:新建一个bean包,创建Person类

@Mapper
public class Person implements Serializable {
    private Integer id ;
    private String name;
    private Integer  age;
    public Person() {
    }
    public Person(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    //getter和setter方法
    //toString方法
}

第四步:新建config包,创建DataSourceConfig1l类

@Configuration //注册到springboot 容器中
@MapperScan(basePackages = "com.fdd.mapper1", 
            sqlSessionTemplateRef  = "test1SqlSessionTemplate")
public class DataSourceConfig1 {
    @Bean(name = "test1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Primary
    @Bean(name = "test1SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory
        (@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        return bean.getObject();
    }
    @Bean(name = "test1TransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager
        (@Qualifier("test1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean(name = "test1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate
        (@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

再建一个DataSourceConfig2类,里面的代码和DataSourceConfig1的一样,把里面的1换成2即可。

第五步:新建mapper1包,创建PersonMapper类

@Mapper
@Repository
public interface PersonMapper {
    //增加一个Person
    @Insert("insert into person(id,name,age)values(#{id},#{name},#{age})")
    int insert(Person person);
    //删除一个Person
    @Delete("delete from person where id = #{id}")
    int deleteByPrimaryKey(Integer id);
    //更改一个Person
    @Update("update person set name =#{name},age=#{age} where id=#{id}")
    int updateByPrimaryKey(Integer id);
    //查询一个Person
    @Select("select id,name ,age from person where id = #{id}")
    Person selectByPrimaryKey(Integer id);
    //查询所有的Person
    @Select("select id,name,age from person")
    List<Person> selectAllPerson();
}

在这里使用注解的形式进行整合。

第六步:新建mapper2包,创建UserMapper类

@Mapper
@Repository
public interface UserMapper {
    //增加一个Person
    @Insert("insert into person(id,name,age)values(#{id},#{name},#{age})")
    int insert(Person person);
    //删除一个Person
    @Delete("delete from person where id = #{id}")
    int deleteByPrimaryKey(Integer id);
    //更改一个Person
    @Update("update person set name =#{name},age=#{age} where id=#{id}")
    int updateByPrimaryKey(Integer id);
    //查询一个Person
    @Select("select id,name ,age from person where id = #{id}")
    Person selectByPrimaryKey(Integer id);
    //查询所有的Person
    @Select("select id,name,age from person")
    List<Person> selectAllPerson();
}

内容和PersonMapper是一样的,但是我在测试的时候出现了一些bean重复定义的错误,所以没有使用Person2Mapper这种方法进行命名。

第七步:新建controller包,创建MyController类

@RestController
public class MyController {
    @Autowired
    private PersonMapper personService;
    @Autowired
    private UserMapper personService2;
    @GetMapping("/add")
    public String test1(){
        Person person = new Person();
        person.setId(14);
        person.setName("java的架构师技术栈");
        person.setAge(18);
        int result = personService.insert(person);
        int result2 = personService2.insert(person);
        System.out.println("插入的结果是:"+result+"  "+result2);
        return "插入的结果是:"+result+"  "+result2;
    }
}

这里只测试了插入的方法,当然如果你需要service层,自行添加就好了。不过对于基本的增删改查功能,mapper足够。

OK,这个就是多数据源的整合,在我自己的电脑亲测成功。

在这里插入图片描述

发布了256 篇原创文章 · 获赞 75 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/SDDDLLL/article/details/103872318
今日推荐