分庫分表之_分庫分表+讀寫分離

前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

1、開始Demo

1.1、hlj-07-sharding_db_table-read_write.sql

drop database if exists ds_0;
create database ds_0 character set 'utf8' collate 'utf8_general_ci';
use ds_0;

drop table if exists user_0;
create table `user_0`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists user_1;
create table `user_1`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;


drop table if exists user_2;
create table `user_2`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;



drop table if exists company_0;
create table `company_0`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists company_1;
create table `company_1`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;



CREATE TABLE `demo_entity`
(
    `id`          bigint(20) unsigned NOT NULL COMMENT '主鍵',
    `name`        varchar(64)         NOT NULL,
    `phone`       varchar(20)                  DEFAULT '' COMMENT '手機號',
    `email`       varchar(64)                  DEFAULT '' COMMENT '郵箱',
    `age`         int(10)                      DEFAULT NULL,
    `status`      varchar(8)          NOT NULL COMMENT '狀態',
    `create_user` bigint(16) unsigned          DEFAULT NULL COMMENT '創建人',
    `create_name` varchar(64)                  DEFAULT '' COMMENT '創建人名稱',
    `create_time` datetime            NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',
    `update_user` bigint(16) unsigned          DEFAULT NULL COMMENT '更新人',
    `update_name` varchar(64)                  DEFAULT '' COMMENT '更新人名稱',
    `update_time` datetime            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;






drop database if exists ds0slave;
create database ds0slave character set 'utf8' collate 'utf8_general_ci';
use ds0slave;

drop table if exists user_0;
create table `user_0`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists user_1;
create table `user_1`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;


drop table if exists user_2;
create table `user_2`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;



drop table if exists company_0;
create table `company_0`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists company_1;
create table `company_1`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;



CREATE TABLE `demo_entity`
(
    `id`          bigint(20) unsigned NOT NULL COMMENT '主鍵',
    `name`        varchar(64)         NOT NULL,
    `phone`       varchar(20)                  DEFAULT '' COMMENT '手機號',
    `email`       varchar(64)                  DEFAULT '' COMMENT '郵箱',
    `age`         int(10)                      DEFAULT NULL,
    `status`      varchar(8)          NOT NULL COMMENT '狀態',
    `create_user` bigint(16) unsigned          DEFAULT NULL COMMENT '創建人',
    `create_name` varchar(64)                  DEFAULT '' COMMENT '創建人名稱',
    `create_time` datetime            NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',
    `update_user` bigint(16) unsigned          DEFAULT NULL COMMENT '更新人',
    `update_name` varchar(64)                  DEFAULT '' COMMENT '更新人名稱',
    `update_time` datetime            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;





drop database if exists ds_1;
create database ds_1 character set 'utf8' collate 'utf8_general_ci';
use ds_1;

drop table if exists user_0;
create table `user_0`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists user_1;
create table `user_1`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists user_2;
create table `user_2`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;




drop table if exists company_0;
create table `company_0`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists company_1;
create table `company_1`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;















drop database if exists ds1slave;
create database ds1slave character set 'utf8' collate 'utf8_general_ci';
use ds1slave;

drop table if exists user_0;
create table `user_0`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists user_1;
create table `user_1`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists user_2;
create table `user_2`
(
    `id`        bigint(20) unsigned not null,
    city        varchar(20)         not null default '',
    name        varchar(20)         not null default '',
    status      int(10)             not null default '0' comment '狀態',
    create_time datetime            not null default current_timestamp comment '創建時間',
    update_time datetime            not null default current_timestamp on update current_timestamp comment '修改時間',
    primary key (`id`)
) engine = innodb
  default charset = utf8;




drop table if exists company_0;
create table `company_0`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;

drop table if exists company_1;
create table `company_1`
(
    `id`                 bigint(20) unsigned not null comment '主鍵',
    name                 varchar(20)         not null default '' comment '企業名稱',
    company_name_english varchar(128)        not null default '' comment '企業英文名稱',
    status               int(10)             not null default '0' comment '狀態',
    create_time          datetime            not null default current_timestamp comment '創建時間',
    update_time          datetime            not null default current_timestamp on update current_timestamp comment '修改時間',

    primary key (`id`)
) engine = innodb
  default charset = utf8;
ƒ

1.1.1、數據庫圖文

1585560832811

1.2、依賴


<!--shardingsphere-->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.0.0-RC1</version>
</dependency>

1.3、配置文件:application.properties

server.port=8888


# 配置 mybatis的一些配置,也可以在 application.properties 中配置,如果配置了就不需要了mybatis.xml
#mybatis-plus.config-location=classpath:mybatis.xml
#Maven 多模塊項目的掃描路徑需以 classpath*: 開頭 (即加載多個 jar 包下的 XML 文件)
mybatis-plus.mapper-locations=classpath*:mapper/*.xml
mybatis-plus.type-aliases-package=com.healerjean.proj.pojo
##主鍵類型  0:"數據庫ID自增,非常大", 1:"用戶輸入ID(如果用戶不輸入,則默認是0)",2:"全局唯一ID (數字類型唯一ID)", 3:"全局唯一ID UUID";
mybatis-plus.id-type: 0
#字段策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
mybatis-plus.field-strategy: 2
#數據庫大寫下劃線轉換
mybatis-plus.capital-mode: true
mybatis-plus.refresh-mapper: true


# #當遇到同樣名字的時候,是否允許覆蓋註冊
spring.main.allow-bean-definition-overriding=true
# 顯示SQL
spring.shardingsphere.props.sql.show=true




##############################
## 分庫分表 + 讀寫分離
#############################
spring.shardingsphere.datasource.names=master0,master0slave,master1,master1slave
## 默認數據源指定(不分庫的表)
spring.shardingsphere.sharding.default-data-source-name=ds0


# 數據源
spring.shardingsphere.datasource.master0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master0.url=jdbc:mysql://localhost:3306/ds_0?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.shardingsphere.datasource.master0.username=root
spring.shardingsphere.datasource.master0.password=123456

spring.shardingsphere.datasource.master0slave.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master0slave.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master0slave.url=jdbc:mysql://localhost:3306/ds0slave?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.shardingsphere.datasource.master0slave.username=root
spring.shardingsphere.datasource.master0slave.password=123456

spring.shardingsphere.datasource.master1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master1.url=jdbc:mysql://localhost:3306/ds_1?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.shardingsphere.datasource.master1.username=root
spring.shardingsphere.datasource.master1.password=123456

spring.shardingsphere.datasource.master1slave.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master1slave.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master1slave.url=jdbc:mysql://localhost:3306/ds1slave?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.shardingsphere.datasource.master1slave.username=root
spring.shardingsphere.datasource.master1slave.password=123456

# 讀寫分離
spring.shardingsphere.sharding.master-slave-rules.ds0.master-data-source-name=master0
spring.shardingsphere.sharding.master-slave-rules.ds0.slave-data-source-names=master0slave

spring.shardingsphere.sharding.master-slave-rules.ds1.master-data-source-name=master1
spring.shardingsphere.sharding.master-slave-rules.ds1.slave-data-source-names=master1slave


# 分庫配置
spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds$->{id % 2}
#spring.shardingsphere.sharding.default-database-strategy.standard.sharding-column=id
#spring.shardingsphere.sharding.default-database-strategy.standard.precise-algorithm-class-name=com.healerjean.proj.config.datasource.CustomShardingDBAlgorithm


# user  company 分表
# user_0,user_1,user_2(自定義分表算法)
spring.shardingsphere.sharding.tables.user.actual-data-nodes=ds$->{0..1}.user_$->{0..2}
spring.shardingsphere.sharding.tables.user.table-strategy.standard.sharding-column=id
spring.shardingsphere.sharding.tables.user.table-strategy.standard.precise-algorithm-class-name=com.healerjean.proj.config.datasource.CustomShardingTableAlgorithm
# company_0,company_1 (inline分表策略 表達式 id%2)
spring.shardingsphere.sharding.tables.company.actual-data-nodes=ds$->{0..1}.company_$->{0..1}
spring.shardingsphere.sharding.tables.company.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.company.table-strategy.inline.algorithm-expression=company_${id.longValue() % 2}



1.4、具體測試方法和類

1.4.1、實體類

1.4.1.1、User.java

@Data
@Accessors(chain = true)
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    /** 主鍵  */
    private Long id;
    private String name;
    private String city;
    private String status;
    private Date createTime;
    private Date updateTime;
}


1.4.1.2、Company.java

@Data
public class Company {

	private Long id;
	private String name;
	private String companyNameEnglish;
	private String status;
	private Date createTime;
	private Date updateTime;
}

1.4.1.3、DemoEntity.java

@Data
@Accessors(chain = true)
public class DemoEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 主鍵
     */
    private Long id;
    /** 姓名 */
    private String name;
    /** 手機號  */
    private String phone;
    /**  郵箱 */
    private String email;
    /** 年齡  */
    private Integer age;
    /**  10可用,99刪除  */
    private String status;
    /** 創建人 */
    private Long createUser;
    /** 創建人名稱  */
    private String createName;
    /**  創建時間 */
    private java.util.Date createTime;
    /**  更新人 */
    private Long updateUser;
    /** 更新人名稱 */
    private String updateName;
    /**  更新時間 */
    private java.util.Date updateTime;

}

1.4.2、DTO數據

1.4.2.1、UserDTO.java

@Data
@Accessors(chain = true)
@ApiModel(value = "demo實體類")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserDTO {


    @ApiModelProperty(value = "主鍵", hidden = true)
    @JsonSerialize(using = JsonLongSerializer.class )
    private Long id;

    @ApiModelProperty(value = "姓名")
    @NotBlank(message = "姓名不能爲空", groups = ValidateGroup.HealerJean.class)
    private String name;

    @ApiModelProperty(value = "城市")
    private String city;

    @ApiModelProperty(value = "狀態", hidden = true)
    private String status;


    @ApiModelProperty(value = "創建時間", hidden = true)
    @JsonFormat(pattern = DateUtils.YYYY_MM_dd_HH_mm_ss, timezone = "GMT+8")
    private Date createTime;

    @ApiModelProperty(value = "修改時間", hidden = true)
    @JsonFormat(pattern = DateUtils.YYYY_MM_dd_HH_mm_ss, timezone = "GMT+8")
    private Date updateTime;

}


1.4.2.2、CompanyDTO.java


@Data
public class CompanyDTO {

	@JsonSerialize(using = JsonLongSerializer.class )
	private Long id;
	private String name;
	private String companyNameEnglish;
	private String status;


	@ApiModelProperty(value = "創建時間", hidden = true)
	@JsonFormat(pattern = DateUtils.YYYY_MM_dd_HH_mm_ss, timezone = "GMT+8")
	private Date createTime;

	@ApiModelProperty(value = "修改時間", hidden = true)
	@JsonFormat(pattern = DateUtils.YYYY_MM_dd_HH_mm_ss, timezone = "GMT+8")
	private Date updateTime;
}

1.4.2.3、DemoDTO.java

@Data
@Accessors(chain = true)
@ApiModel(value = "demo實體類")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DemoDTO extends PageQuery {

    @JsonSerialize(using = JsonLongSerializer.class )
    private Long id;

    @ApiModelProperty(value = "姓名")
    @NotBlank(message = "姓名不能爲空", groups = ValidateGroup.HealerJean.class)
    private String name;

    @ApiModelProperty(value = "年齡")
    private Integer age;

    @ApiModelProperty(value = "手機號")
    private String phone;

    @ApiModelProperty(value = "郵箱")
    private String email;

    @ApiModelProperty(value = "是否刪除,10可用,99刪除 ", hidden = true)
    private String status;

    @ApiModelProperty(value = "創建人", hidden = true)
    private Long createUser;

    @ApiModelProperty(value = "創建人名字", hidden = true)
    private String createName;

    @ApiModelProperty(value = "創建時間", hidden = true)
    private java.util.Date createTime;

    @ApiModelProperty(value = "更新人", hidden = true)
    private Long updateUser;

    @ApiModelProperty(value = "更新人名稱", hidden = true)
    private String updateName;

    @ApiModelProperty(hidden = true)
   private java.util.Date updateTime;

}

1.4.3、Mapper

1.4.3.1、UserMapper.java

public interface UserMapper extends BaseMapper<User> {


}

1.4.3.1、CompanyMapper.java

public interface CompanyMapper  extends BaseMapper<Company> {


}

1.4.3.1、DemoEntityMapper.java

public interface DemoEntityMapper extends BaseMapper<DemoEntity> {

}

1.4.4、Service

1.4.4.1、 UserService.java

public interface UserService {


    UserDTO insert(UserDTO userDTO);

    UserDTO findById(Long id);

    List<UserDTO> list();

}

1.4.4.2、 CompanyService.java

public interface CompanyService {


    CompanyDTO insert(CompanyDTO companyDTO);

    CompanyDTO findById(Long id);

    List<CompanyDTO> list();
}

1.4.4.3、 DemoEntityService.java

public interface DemoEntityService {


    DemoDTO insert(DemoDTO demoEntity);

    DemoDTO findById(Long id);

    List<DemoDTO> list();

}

1.4.5、ServiceImpl.java

1.4.5.1、UserServiceImpl.java

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;


    @Override
    public UserDTO insert(UserDTO userDTO) {
        User user = BeanUtils.dtoToUserDTO(userDTO);
        user.setStatus(StatusEnum.生效.code);
        userMapper.insert(user);
        userDTO.setId(user.getId());
        return userDTO;
    }

    @Override
    public UserDTO findById(Long id) {
        User user = userMapper.selectById(id);
        return user == null ? null : BeanUtils.userToDTO(user);
    }

    @Override
    public List<UserDTO> list() {
        List<User> users = userMapper.selectList(null);
        List<UserDTO> list = null;
        if (!EmptyUtil.isEmpty(users)) {
            list = users.stream().map(BeanUtils::userToDTO).collect(Collectors.toList());
        }
        return list;
    }

}

1.4.5.2、CompanyServiceImpl.java

@Service
public class CompanyServiceImpl implements CompanyService {

    @Resource
    private CompanyMapper companyMapper;

    @Override
    public CompanyDTO insert(CompanyDTO companyDTO) {
        Company company = BeanUtils.dtoToCompany(companyDTO);
        company.setStatus(StatusEnum.生效.code);
        companyMapper.insert(company);
        companyDTO.setId(company.getId());
        return companyDTO;
    }

    @Override
    public CompanyDTO findById(Long id) {
        Company company = companyMapper.selectById(id);
        return company == null ? null : BeanUtils.companyToDTO(company);
    }

    @Override
    public List<CompanyDTO> list() {
        List<Company> companys = companyMapper.selectList(null);
        List<CompanyDTO> list = null;
        if (!EmptyUtil.isEmpty(companys)) {
            list = companys.stream().map(BeanUtils::companyToDTO).collect(Collectors.toList());
        }
        return list;
    }
}

1.4.5.3、DemoEntityServiceImpl.java

@Service
@Slf4j
public class DemoEntityServiceImpl implements DemoEntityService {


    @Resource
    private DemoEntityMapper demoEntityMapper;

    @Resource
    private CompanyService companyService;
    @Resource
    private UserService userService;

    @Override
    public DemoDTO insert(DemoDTO demoDTO) {
        DemoEntity demoEntity = BeanUtils.dtoToDemo(demoDTO);
        demoEntity.setStatus(StatusEnum.生效.code);
        demoEntityMapper.insert(demoEntity);
        demoDTO.setId(demoEntity.getId());
        return demoDTO;
    }


    @Override
    public DemoDTO findById(Long id) {
        DemoEntity demoEntity = demoEntityMapper.selectById(id);
        return demoEntity == null ? null : BeanUtils.demoToDTO(demoEntity);
    }

    @Override
    public List<DemoDTO> list() {
        List<DemoDTO> collect = null;
        List<DemoEntity> list = demoEntityMapper.selectList(null);
        if (!EmptyUtil.isEmpty(list)) {
            collect = list.stream().map(BeanUtils::demoToDTO).collect(Collectors.toList());
        }
        return collect;
    }


}

1.4.6、Controller

1.4.6.1、UserController.java

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "訪問正常"),
        @ApiResponse(code = 301, message = "邏輯錯誤"),
        @ApiResponse(code = 500, message = "系統錯誤"),
        @ApiResponse(code = 401, message = "未認證"),
        @ApiResponse(code = 403, message = "禁止訪問"),
        @ApiResponse(code = 404, message = "url錯誤")
})
@Api(description = "demo控制器")
@Controller
@RequestMapping("hlj/demo")
@Slf4j
public class UserController {



    @Autowired
    private UserService userService;

    @ApiOperation(value = "insert",
            notes = "insert",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @PostMapping(value = "insert", produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResponseBean insert(UserDTO userDTO) {
        log.info("樣例--------mybaits-plus添加demo實體------數據信息{}", userDTO);
        String validate = ValidateUtils.validate(userDTO, ValidateGroup.HealerJean.class);
        if (!validate.equals(CommonConstants.COMMON_SUCCESS)) {
            throw new BusinessException(ResponseEnum.參數錯誤, validate);
        }
        return ResponseBean.buildSuccess(userService.insert(userDTO));
    }


    @ApiOperation(notes = "findById",
            value = "findById",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "demo主鍵", required = true, paramType = "path", dataType = "long"),
    })
    @GetMapping("findById/{id}")
    @ResponseBody
    public ResponseBean findById(@PathVariable Long id) {
        log.info("樣例--------findById------數據:id:{}", id);
        return ResponseBean.buildSuccess(userService.findById(id));
    }

    @ApiOperation(notes = "list",
            value = "list",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @GetMapping("list")
    @ResponseBody
    public ResponseBean list() {
        log.info("樣例--------list------");
        return ResponseBean.buildSuccess(userService.list());
    }


}

1.4.6.2、CompanyController.java

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "訪問正常"),
        @ApiResponse(code = 301, message = "邏輯錯誤"),
        @ApiResponse(code = 500, message = "系統錯誤"),
        @ApiResponse(code = 401, message = "未認證"),
        @ApiResponse(code = 403, message = "禁止訪問"),
        @ApiResponse(code = 404, message = "url錯誤")
})
@Api(description = "demo控制器")
@Controller
@RequestMapping("hlj/company")
@Slf4j
public class CompanyController {


    @Autowired
    private CompanyService companyService;

    @ApiOperation(value = "insert",
            notes = "insert",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @PostMapping(value = "insert", produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResponseBean insert(CompanyDTO companyDTO) {
        log.info("user--------insert------請求參數:{}", companyDTO);
        return ResponseBean.buildSuccess(companyService.insert(companyDTO));
    }


    @ApiOperation(notes = "findById",
            value = "findById",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "demo主鍵", required = true, paramType = "path", dataType = "long"),
    })
    @GetMapping("findById/{id}")
    @ResponseBody
    public ResponseBean findById(@PathVariable Long id) {
        log.info("company--------findById------id:{}", id);
        return ResponseBean.buildSuccess(companyService.findById(id));
    }



    @ApiOperation(notes = "list",
            value = "list",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @GetMapping("list")
    @ResponseBody
    public ResponseBean list() {
        log.info("company--------list------");
        return ResponseBean.buildSuccess(companyService.list());
    }

}

1.4.6.3、DemoController.java

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "訪問正常"),
        @ApiResponse(code = 301, message = "邏輯錯誤"),
        @ApiResponse(code = 500, message = "系統錯誤"),
        @ApiResponse(code = 401, message = "未認證"),
        @ApiResponse(code = 403, message = "禁止訪問"),
        @ApiResponse(code = 404, message = "url錯誤")
})
@Api(description = "demo控制器")
@Controller
@RequestMapping("hlj/demo")
@Slf4j
public class DemoController {

    @Autowired
    private DemoEntityService demoEntityService;


    @ApiOperation(value = "insert",
            notes = "insert",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @PostMapping(value = "insert", produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResponseBean insert(DemoDTO demoDTO) {
        log.info("demo--------insert------請求參數:{}", demoDTO);
        return ResponseBean.buildSuccess(demoEntityService.insert(demoDTO));
    }


    @ApiOperation(notes = "findById",
            value = "findById",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "demo主鍵", required = true, paramType = "path", dataType = "long"),
    })
    @GetMapping("findById/{id}")
    @ResponseBody
    public ResponseBean findById(@PathVariable Long id) {
        log.info("demo--------findById------id:{}", id);
        return ResponseBean.buildSuccess(demoEntityService.findById(id));
    }



    @ApiOperation(notes = "list",
            value = "list",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE,
            response = UserDTO.class)
    @GetMapping("list")
    @ResponseBody
    public ResponseBean list() {
        log.info("demo--------list------");
        return ResponseBean.buildSuccess(demoEntityService.list());
    }

}

1.4.6、自定義分表算法 CustomShardingTableAlgorithm

@Slf4j
public class CustomShardingTableAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        for (String tableName : availableTargetNames) {
            if (tableName.endsWith(shardingValue.getValue() % 3 + "")) {
                log.info("表爲:{}, 主鍵爲:{}, 最終被分到的表爲:{}", availableTargetNames, shardingValue, tableName);
                return tableName;
            }
        }
        throw new IllegalArgumentException();
    }
}

1.4.7、自定義分庫算法:CustomShardingDBAlgorithm

@Slf4j
public class CustomShardingDBAlgorithm implements PreciseShardingAlgorithm<Long> {


    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        for (String dbName : availableTargetNames) {
            if (dbName.endsWith(shardingValue.getValue() % 2 + "")) {
                log.info("庫爲:{}, 主鍵爲:{}, 最終被分到的庫爲:【{}】", availableTargetNames, shardingValue, dbName);
                return dbName;
            }
        }
        throw new IllegalArgumentException();
    }
}

1.5、開始測試

測試成功

感興趣的,歡迎添加博主微信

哈,博主很樂意和各路好友交流,如果滿意,請打賞博主任意金額,感興趣的在微信轉賬的時候,備註您的微信或者其他聯繫方式。添加博主微信哦。

請下方留言吧。可與博主自由討論哦

微信 微信公衆號 支付寶
微信 微信公衆號 支付寶
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章