Spring Boot+Mybatis Plus+shardingsphere 整合

1.新建两个数据库shard_one和shard_two,然后两个数据库添加表user_info_0和user_info_1

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user_info_0
-- ----------------------------
DROP TABLE IF EXISTS `user_info_0`;
CREATE TABLE `user_info_0`  (
                                `id` bigint(20) NOT NULL COMMENT '主键',
                                `available` int(1) NULL DEFAULT 1 COMMENT '是否可用,1 可用,0 不可用',
                                `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
                                `deleted` int(1) NULL DEFAULT 0 COMMENT '是否删除,0 未删除, 1 删除',
                                `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
                                `avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像',
                                `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
                                `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
                                `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号',
                                `salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '盐',
                                `sex` int(1) NULL DEFAULT NULL COMMENT '性别 0未知 1女 2男',
                                `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '姓名',
                                PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户信息表' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user_info_1
-- ----------------------------
DROP TABLE IF EXISTS `user_info_1`;
CREATE TABLE `user_info_1`  (
                                `id` bigint(20) NOT NULL COMMENT '主键',
                                `available` int(1) NULL DEFAULT 1 COMMENT '是否可用,1 可用,0 不可用',
                                `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
                                `deleted` int(1) NULL DEFAULT 0 COMMENT '是否删除,0 未删除, 1 删除',
                                `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
                                `avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像',
                                `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
                                `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
                                `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号',
                                `salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '盐',
                                `sex` int(1) NULL DEFAULT NULL COMMENT '性别 0未知 1女 2男',
                                `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '姓名',
                                PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户信息表' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

2.引入相关依赖


    com.alibaba
    druid-spring-boot-starter
    1.1.17


    mysql
    mysql-connector-java


    com.baomidou
    mybatis-plus-boot-starter
    3.4.2



    org.apache.shardingsphere
    sharding-jdbc-spring-boot-starter
    4.0.0-RC1


    org.apache.shardingsphere
    sharding-core-common
    4.0.0-RC1


    com.google.guava
    guava
    28.1-jre

3.配置yml

server:
  port: 8080
  servlet:
    context-path: /
spring:
  application:
    name: mp-generator
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  main:
    allow-bean-definition-overriding: true

  shardingsphere:
    datasource:
      names: ds-master-0,ds-master-1
      ds-master-0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/shard_one?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
        username: root
        password: 123456
      ds-master-1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/shard_two?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
        username: root
        password: 123456
    sharding:
      tables:
        user_info:
          actual-data-nodes: ds-master-$->{0..1}.user_info_$->{0..1}
          table-strategy:
            inline:
              sharding-column: id
              algorithm-expression: user_info_$->{id % 2}
          key-generator:
            column: id
            type: SNOWFLAKE
      default-database-strategy:
        inline:
          sharding-column: id
          algorithm-expression: ds-master-$->{id % 2}
    props:
      sql:
        show: false

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
      logic-delete-field: deleted
  mapper-locations: classpath:/mapper/**.xml

4.相关实体类和服务类

package com.mp.generator.entity;

import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
public abstract class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "主键")
//    @TableId(value = "id", type = IdType.AUTO)
    @TableId(value = "id")
    private Long id;

    @ApiModelProperty(value = "是否删除,0 未删除, 1 删除")
    @TableLogic
    @TableField(value = "deleted", fill = FieldFill.INSERT)
    private Integer deleted;

    @ApiModelProperty(value = "是否可用,1 可用,0 不可用")
    @TableField(value = "available", fill = FieldFill.INSERT)
    private Integer available;

    @ApiModelProperty(value = "创建时间")
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;

    @ApiModelProperty(value = "修改时间")
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}
package com.mp.generator.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * 

* 用户信息表 *

* * @author songshijun * @since 2021-03-20 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("user_info") @ApiModel(value="UserInfo对象", description="用户信息表") public class UserInfo extends BaseEntity { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "头像") @TableField("avatar") private String avatar; @ApiModelProperty(value = "邮箱") @TableField("email") private String email; @ApiModelProperty(value = "密码") @TableField("password") private String password; @ApiModelProperty(value = "手机号") @TableField("phone") private String phone; @ApiModelProperty(value = "盐") @TableField("salt") private String salt; @ApiModelProperty(value = "性别 0未知 1女 2男") @TableField("sex") private Integer sex; @ApiModelProperty(value = "姓名") @TableField("user_name") private String userName; }
package com.mp.generator.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mp.generator.entity.UserInfo;
import org.springframework.stereotype.Repository;

/**
 * 

* 用户信息表 Mapper 接口 *

* * @author songshijun * @since 2021-03-20 */ @Repository public interface UserInfoMapper extends BaseMapper { }
package com.mp.generator.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.mp.generator.entity.UserInfo;

/**
 * 

* 用户信息表 服务类 *

* * @author 宋时俊 * @since 2021-03-20 */ public interface UserInfoService extends IService { String addUser(Integer addCount); }
package com.mp.generator.service.impl;

import com.mp.generator.entity.UserInfo;
import com.mp.generator.mapper.UserInfoMapper;
import com.mp.generator.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * 

* 用户信息表 服务实现类 *

* * @author 宋时俊 * @since 2021-03-20 */ @Slf4j @Service public class UserInfoServiceImpl extends ServiceImpl implements UserInfoService { @Transactional(rollbackFor = Exception.class) @Override public String addUser(Integer addCount) { if (addCount <= 0) { addCount = 10; } for (int i = 1; i <= addCount; i++) { UserInfo user = new UserInfo(); user.setUserName(UUID.randomUUID().toString() + i); user.setPhone("phone-" + (i)); user.setPassword("password" + i); super.save(user); } return "添加成功"; } }
package com.mp.generator.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mp.generator.entity.BaseEntity;
import com.mp.generator.entity.UserInfo;
import com.mp.generator.service.UserInfoService;
import com.mp.generator.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 

* 用户信息表 前端控制器 *

* * @author 宋时俊 * @since 2021-03-20 */ @RestController @RequestMapping("/api/mp-generator/userinfo/userInfo") @Api(value = "/api/mp-generator/userinfo/userInfo", tags = {"用户信息表接口"}) public class UserInfoController { @Autowired private UserInfoService userInfoService; @GetMapping("/listUser") @ApiOperation(value = "获取所有用户") public Result> listUser() { List areas = userInfoService.list(); return Result.>builder().success().data(areas).build(); } @PostMapping("/addUser") @ApiOperation(value = "添加用户") public Result addUser(@RequestParam Integer addCount) { String response = userInfoService.addUser(addCount); return Result.builder().success().data(response).build(); } @GetMapping("/pageUser") @ApiOperation(value = "用户分页") public Result> pageUser(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize ) { IPage page = userInfoService.page(new Page<>(pageNum, pageSize), Wrappers.lambdaQuery().orderByAsc(BaseEntity::getId)); return Result.>builder().success().data(page).build(); } }

你可能感兴趣的:(Spring Boot+Mybatis Plus+shardingsphere 整合)