mysql 多数据源

依赖


        
        
            mysql
            mysql-connector-java
            runtime
        

        
        
            com.baomidou
            dynamic-datasource-spring-boot-starter
            3.6.0
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.3
        

        
        
            org.projectlombok
            lombok
            true
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

配置文件

# 应用服务 WEB 访问端口
server.port=8080

#mybatisplus配置mapper位置
mybatis-plus.mapper-locations=classpath*:mapper/*.xml

# 多数据源配置
spring.datasource.dynamic.primary=master
spring.datasource.dynamic.strict=false

spring.datasource.dynamic.datasource.master.url=****
spring.datasource.dynamic.datasource.master.username=****
spring.datasource.dynamic.datasource.master.password=****
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.dynamic.datasource.slave1.url=****
spring.datasource.dynamic.datasource.slave1.username=****
spring.datasource.dynamic.datasource.slave1.password=****
spring.datasource.dynamic.datasource.slave1.driver-class-name=com.mysql.cj.jdbc.Driver

下面是项目文件结构
mysql 多数据源_第1张图片
就是必须的 mapper domain service impl 这些文件,直接用 mybatisplus的idea插件生成即可

还需要在 impl 上面加上注解

mysql 多数据源_第2张图片

开始测试

@RestController
@RequestMapping("/multi")
public class MultiDatasource {
    @Autowired
    private ProductService productService;

    @Autowired
    private TbProductService tbProductService;

    @GetMapping("/product")
    public String product() {

        /*从一个库中查出数据*/
        List products = productService.listByIds(List.of(1));
        Product product = products.get(0);

        //id            //product_name      //product_description
        //pre_price     //now_price         //create_time
        //creator       //update_time       //editor        //yn
        TbProduct tbProduct = new TbProduct();
        tbProduct.setProductName(product.getTitle());
        tbProduct.setProductDescription(product.getDescription());
        tbProduct.setPrePrice(Long.valueOf(product.getOriginalPrice()));
        tbProduct.setNowPrice(Long.valueOf(product.getActualPrice()));
        tbProduct.setCreateTime(product.getCreateTime());
        tbProduct.setCreator("admin");
        tbProduct.setUpdateTime(product.getUpdateTime());
        tbProduct.setEditor("admin");
        tbProduct.setYn(1);

        tbProductService.save(tbProduct);
        return "Hello, MultiDatasource!";
    }
}

结束

你可能感兴趣的:(java,springboot,mybatis)