springboot+shardingsphere+mybatis 分表

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

本文的主要目的是通過shardingsphere對(duì)同一庫中的數(shù)據(jù)進(jìn)行分表處理。

1:首先在數(shù)據(jù)庫中新建3張表tab_user0戴而、tab_user1劳曹、tab_user2
2:再對(duì)配置文件進(jìn)行響應(yīng)修改
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數(shù)據(jù)源-->
        <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>    #項(xiàng)目名稱
    </build>

</project>

application

server.port=8066
spring.shardingsphere.datasource.names=master #設(shè)置庫的別名

# 數(shù)據(jù)源 
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

#數(shù)據(jù)分表規(guī)則
#指定所需分的表
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
#分表規(guī)則為主鍵除以3取模
spring.shardingsphere.sharding.tables.tab_user.table-strategy.inline.algorithm-expression=tab_user$->{id % 3}

#設(shè)置mybatis相關(guān)信息
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

#設(shè)置springcloud相關(guān)
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:配置相關(guān)完成后進(jìn)入實(shí)際代碼部分
啟動(dòng)類

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相關(guān)
@EnableDiscoveryClient
@Configuration
@SpringBootApplication
// 事務(wù)支持'
@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;

    /**
     * 數(shù)據(jù)插入測(cè)試
     * @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("參數(shù)異常,請(qǐng)聯(lián)系管理員");
        }
    }


    /**
     * 分頁查詢+數(shù)據(jù)刪除
     * @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("參數(shù)異常,請(qǐng)聯(lián)系管理員");
        }
    }

    /**
     * 數(shù)據(jù)全刪
     * @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("參數(shù)異常固灵,請(qǐng)聯(lián)系管理員");
        }
    }

    public JSONObject getBusinessJson(String msg){
        if(Strings.isNullOrEmpty(msg)) {
            msg="數(shù)據(jù)不合法降狠,請(qǐng)重試!";
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("return_code", "-1002");
        jsonObject.put("return_msg", msg);
        return jsonObject;
    }
}

服務(wù)層

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);
        }
    }

}

實(shí)體類

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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末溜畅,一起剝皮案震驚了整個(gè)濱河市捏卓,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌慈格,老刑警劉巖怠晴,帶你破解...
    沈念sama閱讀 210,978評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異浴捆,居然都是意外死亡蒜田,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,954評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門选泻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來物邑,“玉大人,你說我怎么就攤上這事滔金∩猓” “怎么了?”我有些...
    開封第一講書人閱讀 156,623評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵餐茵,是天一觀的道長(zhǎng)科阎。 經(jīng)常有香客問我,道長(zhǎng)忿族,這世上最難降的妖魔是什么锣笨? 我笑而不...
    開封第一講書人閱讀 56,324評(píng)論 1 282
  • 正文 為了忘掉前任,我火速辦了婚禮道批,結(jié)果婚禮上错英,老公的妹妹穿的比我還像新娘。我一直安慰自己隆豹,他們只是感情好椭岩,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,390評(píng)論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般判哥。 火紅的嫁衣襯著肌膚如雪献雅。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,741評(píng)論 1 289
  • 那天塌计,我揣著相機(jī)與錄音挺身,去河邊找鬼。 笑死锌仅,一個(gè)胖子當(dāng)著我的面吹牛章钾,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播热芹,決...
    沈念sama閱讀 38,892評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼贱傀,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了剿吻?” 一聲冷哼從身側(cè)響起窍箍,我...
    開封第一講書人閱讀 37,655評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤串纺,失蹤者是張志新(化名)和其女友劉穎丽旅,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體纺棺,經(jīng)...
    沈念sama閱讀 44,104評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡榄笙,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了祷蝌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片茅撞。...
    茶點(diǎn)故事閱讀 38,569評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖巨朦,靈堂內(nèi)的尸體忽然破棺而出米丘,到底是詐尸還是另有隱情,我是刑警寧澤糊啡,帶...
    沈念sama閱讀 34,254評(píng)論 4 328
  • 正文 年R本政府宣布拄查,位于F島的核電站,受9級(jí)特大地震影響棚蓄,放射性物質(zhì)發(fā)生泄漏堕扶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,834評(píng)論 3 312
  • 文/蒙蒙 一梭依、第九天 我趴在偏房一處隱蔽的房頂上張望稍算。 院中可真熱鬧,春花似錦役拴、人聲如沸糊探。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽侧到。三九已至勃教,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間匠抗,已是汗流浹背故源。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評(píng)論 1 264
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留汞贸,地道東北人绳军。 一個(gè)月前我還...
    沈念sama閱讀 46,260評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像矢腻,于是被迫代替她去往敵國(guó)和親门驾。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,446評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容