SpringBoot2.x + Mapper4 + 多数据源

【简介】

本文在SpringBoot2.x整合MyBatis通用Mapper4SpringBoot2.x + MyBatis + 多数据源 ,基础上做整合。实现 SpringBoot2.x + Mapper4 + 多数据源


【本文Demo】

https://github.com/qidasheng2012/springboot2.x_ssm/tree/branch-Mapper4-DataSources

建议先clone下本项目到本地,再结合本文章及注意事项,就能一目了然了


【pom.xml】

mapper-spring-boot-starter中包含MyBatis的相关包,所以不需要再引入MyBatis的相关包
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.springboot</groupId>
    <artifactId>springboot2.x_ssm</artifactId>
    <version>1.0.0</version>
    <description>Spring Boot2.x 搭建 SSM 项目</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!-- 支持 @ConfigurationProperties 注解 读取properties或yml配置文件中的值 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

【application.yml】

#服务器配置
server:
  port: 80

spring:
  #数据源
  datasource:
    # 系统数据源
    system:
      url: jdbc:mysql://localhost:3306/system?serverTimezone=Asia/Shanghai&characterEncoding=utf8
      username: root
      password: 123456
      configuration:
        maximum-pool-size: 10

    # 业务数据源
    server:
      url: jdbc:mysql://localhost:3306/server?serverTimezone=Asia/Shanghai&characterEncoding=utf8
      username: root
      password: 123456
      configuration:
        maximum-pool-size: 10

# 日志
logging:
  level:
    com.springboot.ssm.mapper: debug # 显示执行sql

【config】

这里是配置多数据源的核心

注意事项:

  1. @MapperScan 引入的是 tk.mybatis.spring.annotation.MapperScan 包下的
  2. 使用多数据源,其中一个配置类需要添加 @Primary 注解 (有且仅有一个配置类需要添加)
  3. 在配置类中需要同时配置 dao 层所在的包和 xml 所在的路径

【DB1Config】

package com.springboot.ssm.config.db;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@MapperScan(
        basePackages = {"com.springboot.ssm.mapper.system"}, // 扫描mapper层所在的包
        sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DB1Config {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.system")
    public DataSourceProperties db1DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.system.configuration")
    public DataSource db1DataSource() {
        return db1DataSourceProperties()
                .initializeDataSourceBuilder()
                .type(HikariDataSource.class) // 可以显示指定连接池,也可以不显示指定;即此行代码可以注释掉
                .build();
    }

    @Bean
    @Primary
    public SqlSessionFactory db1SqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(db1DataSource());
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath:mapper/system/*.xml")); // xml 所在路径
        factoryBean.setTypeAliasesPackage("com.springboot.ssm.domain"); // 设置扫描别名包路径
        return factoryBean.getObject();
    }

    @Bean
    @Primary
    public DataSourceTransactionManager db1TransactionManager() {
        return new DataSourceTransactionManager(db1DataSource());
    }

    @Bean
    @Primary
    public SqlSessionTemplate db1SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(db1SqlSessionFactory());
    }

}

【DB2Config】

package com.springboot.ssm.config.db;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@MapperScan(
        basePackages = {"com.springboot.ssm.mapper.server"}, // 1. 扫描mapper层所在的包
        sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DB2Config {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.server")
    public DataSourceProperties db2DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.server.configuration")
    public DataSource db2DataSource() {
        return db2DataSourceProperties()
                .initializeDataSourceBuilder()
                .type(HikariDataSource.class) // 可以显示指定连接池,也可以不显示指定;即此行代码可以注释掉
                .build();
    }

    @Bean
    public SqlSessionFactory db2SqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(db2DataSource());
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath:mapper/server/*.xml")); // xml 所在路径
        factoryBean.setTypeAliasesPackage("com.springboot.ssm.domain"); // 设置扫描别名包路径
        return factoryBean.getObject();
    }

    @Bean
    public DataSourceTransactionManager db2TransactionManager() {
        return new DataSourceTransactionManager(db2DataSource());
    }

    @Bean
    public SqlSessionTemplate db2SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(db2SqlSessionFactory());
    }

}

【实体类】

package com.springboot.ssm.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "JDBC")
    private Integer id;
    private String name;
    private Integer age;
}
package com.springboot.ssm.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "t_product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "JDBC")
    private Integer id;
    private String productName;
}

【自定义通用Mapper接口】

package com.springboot.ssm.common.mapper;

import tk.mybatis.mapper.common.IdsMapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface MysqlBaseMapper<T> extends Mapper<T>, MySqlMapper<T>, IdsMapper<T> {
}

【Mapper】

package com.springboot.ssm.mapper.system;

import com.springboot.ssm.common.mapper.MysqlBaseMapper;
import com.springboot.ssm.domain.User;

public interface UserMapper extends MysqlBaseMapper<User> {

}
package com.springboot.ssm.mapper.server;

import com.springboot.ssm.common.mapper.MysqlBaseMapper;
import com.springboot.ssm.domain.Product;

public interface ProductMapper extends MysqlBaseMapper<Product> {

}

【service】

package com.springboot.ssm.service;

import com.springboot.ssm.domain.User;

import java.util.List;

public interface UserService {
    // 查询所有用户信息
    List<User> getAll();
}
package com.springboot.ssm.service.impl;

import com.springboot.ssm.domain.User;
import com.springboot.ssm.mapper.system.UserMapper;
import com.springboot.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAll() {
        return userMapper.selectAll();
    }

}
package com.springboot.ssm.service;

import com.springboot.ssm.domain.Product;

import java.util.List;

public interface ProductService {
    /**
     * 获取所有产品信息
     *
     * @return
     */
    List<Product> getAll();
}
package com.springboot.ssm.service.impl;

import com.springboot.ssm.domain.Product;
import com.springboot.ssm.mapper.server.ProductMapper;
import com.springboot.ssm.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;


    @Override
    public List<Product> getAll() {
        return productMapper.selectAll();
    }
}

【controller】

package com.springboot.ssm.controller;

import com.springboot.ssm.domain.User;
import com.springboot.ssm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getAll")
    public List<User> getAll() {
        return userService.getAll();
    }

}
package com.springboot.ssm.controller;

import com.springboot.ssm.domain.Product;
import com.springboot.ssm.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/getAll")
    public List<Product> getAll() {
        return productService.getAll();
    }
}

【测试】

访问:http://127.0.0.1/user/getAll
在这里插入图片描述
访问:http://127.0.0.1/product/getAll
在这里插入图片描述
OK!大功告成

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

猜你喜欢

转载自blog.csdn.net/qidasheng2012/article/details/103119695
今日推荐