精通Spring Boot——第十三篇:整合Mybatis多数据源

原创
2018/10/23 10:10
阅读数 658

久违了,最近度过了一段倦怠期,这段时间干什么都没有动力,拖延症复发。好在我回来了.... ——From me .

进入今天的主题——在Spring Boot 项目中整合mybatis多数据源,其实很简单,其实并不难。 整体项目结构以及数据源配置application.yml:

看代码吧.

第一个数据源配置(作为主数据源)

/**
 * @author Lensen
 * @desc
 * @since 2018/9/19 10:22
 */
@Configuration
@MapperScan(basePackages = PrimaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
    static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.primary";
    static final String MAPPER_LOCATION = "classpath:mapper/primary/*.xml";
    @Value("${primary.datasource.url}")
    private String url;

    @Value("${primary.datasource.username}")
    private String user;

    @Value("${primary.datasource.password}")
    private String password;

    @Value("${primary.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "primaryDataSource")
    @Primary
    public DataSource primaryDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "primaryTransactionManager")
    @Primary
    public DataSourceTransactionManager primaryTransactionManager() {
        return new DataSourceTransactionManager(primaryDataSource());
    }

    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(primaryDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(PrimaryDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

第二个数据源配置



/**
 * @author Lensen
 * @desc
 * @since 2018/9/19 10:22
 */
@Configuration
@MapperScan(basePackages = SecondaryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfig {
    static final String PACKAGE = "com.developlee.multipartmybatisdatasource.dao.secondary";
    static final String MAPPER_LOCATION = "classpath:mapper/secondary/*.xml";
    @Value("${secondary.datasource.url}")
    private String url;

    @Value("${secondary.datasource.username}")
    private String user;

    @Value("${secondary.datasource.password}")
    private String password;

    @Value("${secondary.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "secondaryDataSource")
    public DataSource secondaryDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "secondaryTransactionManager")
    public DataSourceTransactionManager secondaryTransactionManager() {
        return new DataSourceTransactionManager(secondaryDataSource());
    }

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(secondaryDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(SecondaryDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

}

其他业务逻辑代码就不贴了,代码可在我的github上找到。文章末尾有地址。

application.yml


## primary 数据源配置
primary:
  datasource:
    url: jdbc:mysql://localhost:3306/javashop?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

## secondary 数据源配置
secondary:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

pom.xml

     <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

测试:


@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipartMybatisDatasourceApplicationTests {

    @Autowired
    UserServiceImpl userService;
    @Autowired
    HomeServiceImpl homeService;
    @Test
    public void contextLoads() {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(1L);
        userEntity.setName("Lensen");
        userEntity.setMobile("13738718660");
        HomeEntity homeEntity = new HomeEntity();
        homeEntity.setId(1L);
        homeEntity.setUserId(1L);
        homeEntity.setCity("杭州");
        homeEntity.setTown("西湖区");

         userService.saveUser(userEntity);
         homeService.saveHome(homeEntity);

         userService.getUserById(1L);
         homeService.getHomeByUserId(1L);
    }

}

代码可以在我的github.com中找到。

我的公众号:如果有兴趣 可以关注下

展开阅读全文
打赏
1
8 收藏
分享
加载中
liululee博主

引用来自“Java成长之路”的评论

请问你原博文是发表在 哪个平台的,这个上的应该是搬迁的把,好多图片打不开
图片已更新。以后会常在oschina上发,之后会搭建个人博客😆
2019/06/11 19:49
回复
举报
请问你原博文是发表在 哪个平台的,这个上的应该是搬迁的把,好多图片打不开
2019/06/09 21:39
回复
举报
更多评论
打赏
2 评论
8 收藏
1
分享
返回顶部
顶部