dynamic-datasource+Mybatis多数据源使用

Gitee地址:dynamic-datasource: 基于 SpringBoot 多数据源 动态数据源 主从分离 快速启动器 支持分布式事务

依赖

<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>3.0.3</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>
<!--dynamic-datasource -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
    <version>4.3.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.21</version>
</dependency>

application.properties

spring.application.name=dynamic-datasource


server.port=8088

#设置默认的数据源或者数据源组,默认值即为master
spring.datasource.dynamic.primary=master
#严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
spring.datasource.dynamic.strict=false

spring.datasource.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/dy?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=root
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.master.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.dynamic.datasource.slave.url=jdbc:mysql://localhost2:3306/dy?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
spring.datasource.dynamic.datasource.slave.username=root
spring.datasource.dynamic.datasource.slave.password=root
spring.datasource.dynamic.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver
#去掉默认使用HikariCP
spring.datasource.dynamic.datasource.slave.type=com.alibaba.druid.pool.DruidDataSource


logging.level.com.example.dynamicdatasource=debug

mybatis.type-aliases-package=com.example.dynamicdatasource.pojo
mybatis.mapper-locations=classpath*:mappers/*Mapper.xml
#驼峰
mybatis.configuration.map-underscore-to-camel-case=true

package com.example.dynamicdatasource.controller;

import com.example.dynamicdatasource.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hrui
 * @date 2024/8/6 15:49
 */
@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/saveProduct")
    public String saveProduct(){
        productService.saveProduct();
        return "saveProduct success";
    }
}

package com.example.dynamicdatasource.controller;

import com.example.dynamicdatasource.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hrui
 * @date 2024/8/6 16:10
 */
@RestController
public class TransactionController {

    @Autowired
    private TransactionService transactionService;


    @GetMapping("/trans")
    public String saveUserAndProduct() {
        transactionService.saveUserAndProduct();
        return "success";
    }
}

package com.example.dynamicdatasource.controller;

import com.example.dynamicdatasource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hrui
 * @date 2024/8/6 15:49
 */
@RestController
public class UserController {


    @Autowired
    private UserService userService;
    @GetMapping("/saveUser")
    public String saveUser() {
        userService.saveUser();
        return "success";
    }
}

package com.example.dynamicdatasource.service;

/**
 * @author hrui
 * @date 2024/8/6 15:49
 */
public interface ProductService {
    void saveProduct();
}

package com.example.dynamicdatasource.service;

/**
 * @author hrui
 * @date 2024/8/6 16:11
 */
public interface TransactionService {
    void saveUserAndProduct();
}

package com.example.dynamicdatasource.service;

/**
 * @author hrui
 * @date 2024/8/6 15:49
 */
public interface UserService {
    void saveUser();
}

package com.example.dynamicdatasource.service.impl;

import com.example.dynamicdatasource.mapper.ProductMapper;
import com.example.dynamicdatasource.pojo.Product;
import com.example.dynamicdatasource.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author hrui
 * @date 2024/8/6 15:49
 */
@Service
public class ProductServiceImpl implements ProductService {



    @Autowired
    private ProductMapper productMapper;
    @Override
    public void saveProduct() {
        Product product = new Product();
        product.setName("product");
        product.setPrice(new BigDecimal(100));
        int i=productMapper.saveProduct(product);
        System.out.println(i>0?"插入成功":"插入失败");
    }
}

package com.example.dynamicdatasource.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.example.dynamicdatasource.mapper.ProductMapper;
import com.example.dynamicdatasource.mapper.UserMapper;
import com.example.dynamicdatasource.pojo.Product;
import com.example.dynamicdatasource.pojo.User;
import com.example.dynamicdatasource.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;

/**
 * @author hrui
 * @date 2024/8/6 16:11
 */
@Service
public class TransactionServiceImpl implements TransactionService {



    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProductMapper productMapper;


    @DSTransactional
    //使用@Transaction时候 配置类启动类加  @TransactionServiceImpl  现在不加也行
   //@Transactional//切换时候注意maven清理  这个注解此时不允许使用  报表不存在因数据源还在主库里 Table 'dy.t_product' doesn't exist
    public void saveUserAndProduct() {
        //判断是否开启事务
//        if( TransactionSynchronizationManager.isActualTransactionActive()){
//            System.out.println("开启事务");
//        }else{
//            System.out.println("未开启事务");
//        }
        User user = new User(null, "李四", "123456", 18, "男", "北京");
        Product product = new Product(null, "手机", new BigDecimal(1000));
        int i=userMapper.saveUser(user);
        int i2=productMapper.saveProduct(product);
        System.out.println(1/0);
        System.out.println(i>0&&i2>0?"插入成功":"插入失败");
    }
}

package com.example.dynamicdatasource.service.impl;

import com.example.dynamicdatasource.mapper.UserMapper;
import com.example.dynamicdatasource.pojo.User;
import com.example.dynamicdatasource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author hrui
 * @date 2024/8/6 15:49
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveUser() {
        User user = new User(null, "张三", "123456", 18, "男", "北京");
        int i=userMapper.saveUser(user);
        System.out.println(i>0?"插入成功":"插入失败");
    }
}

package com.example.dynamicdatasource.mapper;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.example.dynamicdatasource.pojo.Product;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;

/**
 * @author hrui
 * @date 2024/8/6 15:50
 */
@DS("slave")
public interface ProductMapper {


    @Insert("insert into t_product(name,price) values(#{name},#{price})")
    //返回自增主键
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int saveProduct(Product product);

}

package com.example.dynamicdatasource.mapper;

import com.example.dynamicdatasource.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;

/**
 * @author hrui
 * @date 2024/8/6 15:50
 */
public interface UserMapper {


    @Insert("insert into t_user(name,sex,age,address,password) values(#{name},#{sex},#{age},#{address},#{password})")
    //返回自增主键
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int saveUser(User user);
}

package com.example.dynamicdatasource.pojo;

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

import java.math.BigDecimal;

/**
 * @author hrui
 * @date 2024/8/6 15:50
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
    private Integer id;
    private String name;
    private BigDecimal price;
}

package com.example.dynamicdatasource.pojo;

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

/**
 * @author hrui
 * @date 2024/8/6 15:50
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
    private String password;
    private Integer age;
    private String sex;
    private String address;
}

### 回答1: dynamic-datasource-spring-boot-starter是一个基于Spring Boot的动态数据源管理工具。它提供了一种简单而强大的方式来配置和管理多个数据源,并能在运行时动态切换数据源。 在3.4.1版本中,该工具进行了一些改进和增强。首先,它支持了Spring Boot 2.x版本,这意味着我们可以在使用最新版本的Spring Boot框架的同时,依然能够使用该工具来管理数据源。 此外,3.4.1版本对多数据源的配置进行了优化,使得配置更加简洁和灵活。我们可以通过在application.properties或application.yml配置文件中指定数据源相关的属性来定义多个数据源,而不再需要编写繁琐的代码。 另外一项改进是在动态数据源切换方面。在之前的版本中,我们需要手动编写代码来切换数据源,而在3.4.1版本中,该工具已经提供了自动切换数据源的功能。我们只需要在需要切换数据源的方法或类上加上@DS注解,并指定要切换的数据源,即可实现自动切换数据源的功能。 最后值得一提的是,dynamic-datasource-spring-boot-starter 3.4.1还提供了一些其他的功能和特性,比如数据源监控,可扩展性和高可用性等。这些功能使得该工具在实际项目中的使用更加方便和可靠。 综上所述,dynamic-datasource-spring-boot-starter 3.4.1是一个功能强大、易于使用的动态数据源管理工具,它适用于Spring Boot框架,并在多数据源配置和动态数据源切换方面进行了改进和优化。它的出现为我们开发和管理多数据源的项目提供了便利,同时也提高了项目的可维护性和灵活性。 ### 回答2: dynamic-datasource-spring-boot-starter是一个基于Spring Boot的动态数据源管理的工具包。它提供了一种简单而灵活的方式来配置和管理多数据源。 首先,dynamic-datasource-spring-boot-starter可以方便地集成到Spring Boot项目中。通过在pom.xml文件中引入相应的依赖,即可将该工具包引入项目中。然后,在application.yml文件中进行相应的配置,即可使用该工具包提供的功能。 其次,dynamic-datasource-spring-boot-starter可以轻松地配置多数据源。在配置文件中,可以指定多个数据源的连接信息,包括数据库的url、用户名、密码等。在需要使用数据源的地方,可以通过@DS注解来指定要使用的数据源。这样,就可以很方便地切换不同的数据源,实现读写分离或者分库分表等需求。 此外,dynamic-datasource-spring-boot-starter还提供了一些高级功能。比如,支持动态添加和删除数据源,可以在程序运行中动态地切换数据源;支持AOP切面,方便地对方法进行切面处理;支持多数据源的事务管理,保证了数据的一致性。 总之,dynamic-datasource-spring-boot-starter是一个功能强大而又灵活的动态数据源管理工具包。它使得在Spring Boot项目中配置和管理多数据源变得非常简单和方便,可以满足各种复杂的数据源切换和管理需求。它的出现极大地简化了多数据源的配置和管理工作,同时提供了一些高级功能,使得开发人员可以更加专注于业务逻辑的实现。 ### 回答3: dynamic-datasource-spring-boot-starter 3.4.1 是一个用于Spring Boot项目的动态数据源管理工具。它提供了一种简单而强大的方式来配置和管理多个数据源。 动态数据源管理是在一个应用程序中使用多个数据源的一种常见需求。通过使用 dynamic-datasource-spring-boot-starter,我们可以在一个Spring Boot应用程序中轻松地设置和切换多个数据源。 使用 dynamic-datasource-spring-boot-starter 的好处之一是它能够自动根据配置文件中的信息来创建和管理数据源。我们只需要在配置文件中指定要使用的数据源的名称、连接信息、用户名和密码等,dynamic-datasource-spring-boot-starter 就能自动根据这些信息创建数据源,并将其注册到应用程序的数据源管理器中。 另一个优点是 dynamic-datasource-spring-boot-starter 支持动态切换数据源。在应用程序运行时,我们可以通过调用相应的API来切换数据源。这在一些需要根据用户角色或环境设置不同数据源的场景中非常有用。 除了基本的数据源管理功能,dynamic-datasource-spring-boot-starter 还提供了一些其他有用的特性,例如动态创建数据源、多数据源的事务管理、数据源监控和统计等。 总而言之,dynamic-datasource-spring-boot-starter 3.4.1 是一个强大的工具,它简化了在Spring Boot应用程序中创建和管理多个数据源的过程,并提供了一些额外的功能来满足不同场景下的需求。如果你的应用程序需要使用多个数据源,dynamic-datasource-spring-boot-starter 可能是一个很好的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hrui0706

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值