springboot+shardingsphere+mybatis 分表

springboot:2.1.9
cloud:Greenwich.SR2
sharding:4.0.0-RC1

本文的主要目的是通过shardingsphere对同一库中的数据进行分表处理。

1:首先在数据库中新建3张表tab_user0、tab_user1、tab_user2
2:再对配置文件进行响应修改
pom文件

<?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 https://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.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.sharding</groupId>
    <artifactId>stuTab</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>stuTab</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <druid>1.1.16</druid>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
    </properties>

    <dependencies>
        <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>2.1.4</version>
        </dependency>
        <!--druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid}</version>
        </dependency>
        <!--shardingsphere最新版本-->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.0.0-RC1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-namespace</artifactId>
            <version>4.0.0-RC1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.2</version>
        </dependency>
        <!--加入分页依赖-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
        <finalName>stuTab</finalName>    #项目名称
    </build>

</project>

application

server.port=8066
spring.shardingsphere.datasource.names=master #设置库的别名

# 数据源 
spring.shardingsphere.datasource.master.type=com.alibaba.druid.pool.DruidDataSource  
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master.url=jdbc:mysql://xxx:3306/xxx?characterEncoding=utf-8
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=welcome123

#数据分表规则
#指定所需分的表
spring.shardingsphere.sharding.tables.tab_user.actual-data-nodes=master.tab_user$->{0..2}
#指定主键
spring.shardingsphere.sharding.tables.tab_user.table-strategy.inline.sharding-column=id
#分表规则为主键除以3取模
spring.shardingsphere.sharding.tables.tab_user.table-strategy.inline.algorithm-expression=tab_user$->{id % 3}

#设置mybatis相关信息
mybatis.typeAliasesPackage=com.sharding.stuTab.pojo
mybatis.mapperLocations=classpath:mapper/*.xml

#打印sql
spring.shardingsphere.props.sql.show=true
spring.main.allow-bean-definition-overriding=true

#设置springcloud相关
spring.application.name=stuTab
spring.cloud.nacos.discovery.server-addr=10.241.95.109:8848,10.241.95.110:8848,10.241.95.111:8848
spring.cloud.nacos.discovery.cluster-name=stuTab
spring.cloud.nacos.discovery.service=stuTab
spring.cloud.nacos.discovery.register-enabled=true
spring.cloud.nacos.discovery.namespace=public
spring.cloud.nacos.discovery.heart-beat-timeout=5000
nacos.config.server-addr=10.241.95.109:8848,10.241.95.110:8848,10.241.95.111:8848

3:配置相关完成后进入实际代码部分
启动类

package com.sharding.stuTab;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
// cloud相关
@EnableDiscoveryClient
@Configuration
@SpringBootApplication
// 事务支持'
@EnableTransactionManagement
public class StuTabApplication {

    public static void main(String[] args) {
        SpringApplication.run(StuTabApplication.class, args);
    }

}

接口类

package com.sharding.stuTab.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.sharding.stuTab.mapper.TabUserMapper;
import com.sharding.stuTab.pojo.TabUser;
import com.sharding.stuTab.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
    protected static final Logger logger = LoggerFactory
            .getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private TabUserMapper tabUserMapper;

    /**
     * 数据插入测试
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/dataInsert",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject dataInsert(HttpServletRequest request, HttpServletResponse response ) throws Exception{
        try {
            ArrayList<TabUser> arr = new ArrayList<>();
            for (int i=0;i<10;i++){
                TabUser user = new TabUser();
                arr.add(user);
            }
            userService.dataInsert(arr);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("return_code", "0");
            jsonObject.put("operation","2");
            return jsonObject;
        } catch (Exception e) {
            logger.error("UserController.dataInsert error", e);
            return getBusinessJson("参数异常,请联系管理员");
        }
    }


    /**
     * 分页查询+数据删除
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/dataDelete",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject dataDelete(HttpServletRequest request, HttpServletResponse response ) throws Exception{
        try {
            TabUser queryBean = new TabUser();
            PageHelper.startPage(1,10);
            List<TabUser> tabUsers = tabUserMapper.selectAll(queryBean);
            PageInfo pageInfo = new PageInfo(tabUsers);
            tabUsers = pageInfo.getList();
            for (TabUser record : tabUsers){
                tabUserMapper.deleteByPrimaryKey(record.getId());
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("return_code", "0");
            jsonObject.put("operation","2");
            jsonObject.put("data",tabUsers);
            return jsonObject;
        } catch (Exception e) {
            logger.error("UserController.dataDelete error", e);
            return getBusinessJson("参数异常,请联系管理员");
        }
    }

    /**
     * 数据全删
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/dataDestory",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject dataDestory(HttpServletRequest request, HttpServletResponse response ) throws Exception{
        try {
            tabUserMapper.deleteAll();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("return_code", "0");
            jsonObject.put("operation","2");

            return jsonObject;
        } catch (Exception e) {
            logger.error("UserController.dataDestory error", e);
            return getBusinessJson("参数异常,请联系管理员");
        }
    }

    public JSONObject getBusinessJson(String msg){
        if(Strings.isNullOrEmpty(msg)) {
            msg="数据不合法,请重试!";
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("return_code", "-1002");
        jsonObject.put("return_msg", msg);
        return jsonObject;
    }
}

服务层

package com.sharding.stuTab.service;

import com.sharding.stuTab.pojo.TabUser;

import java.util.List;

public interface UserService {

    void dataInsert(List<TabUser> tabUserList);

}
package com.sharding.stuTab.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.sharding.stuTab.mapper.TabUserMapper;
import com.sharding.stuTab.pojo.TabUser;
import com.sharding.stuTab.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TabUserMapper tabUserMapper;


    @Override
    public void dataInsert(List<TabUser> tabUserList) {
       // 通过雪花算法来获取主键
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        for (TabUser user : tabUserList) {
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setStatus(0);
            user.setId(snowflake.nextId());
            user.setAge(28);
            user.setName("tudinle");
            user.setSex("男");
            tabUserMapper.insertSelective(user);
        }
    }

}

实体类

package com.sharding.stuTab.pojo;

import java.util.Date;

public class TabUser {
    private Long id;

    private String name;

    private String sex;

    private Integer age;

    private Date createTime;

    private Date updateTime;

    private Integer status;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }
}

dao层

package com.sharding.stuTab.mapper;

import com.sharding.stuTab.pojo.TabUser;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface TabUserMapper {
    int deleteByPrimaryKey(Long id);

    int insert(TabUser record);

    int insertSelective(TabUser record);

    TabUser selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(TabUser record);

    int updateByPrimaryKey(TabUser record);

    List<TabUser> selectAll(TabUser record);

    int deleteAll();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sharding.stuTab.mapper.TabUserMapper">
  <resultMap id="BaseResultMap" type="com.sharding.stuTab.pojo.TabUser">
    <!--@mbg.generated-->
    <!--@Table tab_user-->
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
    <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
    <result column="status" jdbcType="INTEGER" property="status" />
  </resultMap>
  <sql id="Base_Column_List">
    <!--@mbg.generated-->
    id, `name`, sex, age, create_time, update_time, `status`
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    <!--@mbg.generated-->
    select 
    <include refid="Base_Column_List" />
    from tab_user
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    <!--@mbg.generated-->
    delete from tab_user
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.sharding.stuTab.pojo.TabUser">
    <!--@mbg.generated-->
    insert into tab_user (id, `name`, sex, 
      age, create_time, update_time, 
      `status`)
    values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, 
      #{status,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.sharding.stuTab.pojo.TabUser">
    <!--@mbg.generated-->
    insert into tab_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        `name`,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="age != null">
        age,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="updateTime != null">
        update_time,
      </if>
      <if test="status != null">
        `status`,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="status != null">
        #{status,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.sharding.stuTab.pojo.TabUser">
    <!--@mbg.generated-->
    update tab_user
    <set>
      <if test="name != null">
        `name` = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        update_time = #{updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="status != null">
        `status` = #{status,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.sharding.stuTab.pojo.TabUser">
    <!--@mbg.generated-->
    update tab_user
    set `name` = #{name,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = #{updateTime,jdbcType=TIMESTAMP},
      `status` = #{status,jdbcType=INTEGER}
    where id = #{id,jdbcType=BIGINT}
  </update>

  <select id="selectAll" parameterType="com.sharding.stuTab.pojo.TabUser" resultMap="BaseResultMap">
    <!--@mbg.generated-->
    select
    <include refid="Base_Column_List" />
    from tab_user
  </select>

  <delete id="deleteAll" >
    <!--@mbg.generated-->
    delete from tab_user
  </delete>
</mapper>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容