对广播表操作步骤是:添加实体类、添加repository、添加配置信息、添加测试

1、在每个库中都创建广播表

  1. CREATE TABLE `city` (
  2. `Id` bigint(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(256) DEFAULT NULL,
  4. `province` varchar(256) DEFAULT NULL,
  5. PRIMARY KEY (`Id`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2、创建实体类

package com.slin.entity;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "city")
public class City implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "province")
    private String province;

    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 getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }
}

3、添加repository

package com.slin.repository;

import com.slin.entity.City;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CityRepository extends JpaRepository<City,Long> {
}

4、添加配置信息

image.png

##########配置广播表的实现broadcast##########
spring.shardingsphere.sharding.broadcast-tables=city
#配置广播表的id主键,采用雪花片算法
spring.shardingsphere.sharding.tables.city.key-generator.column=id
spring.shardingsphere.sharding.tables.city.key-generator.type=SNOWFLAKE

5、添加测试

package com.slin.test;

import com.slin.RunBoot;
import com.slin.entity.City;
import com.slin.entity.Position;
import com.slin.entity.PositionDetail;
import com.slin.repository.CityRepository;
import com.slin.repository.PositionDetailRepository;
import com.slin.repository.PositionRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;


//通过它来启动
@RunWith(SpringRunner.class)
//通过RunBoot来创建boot容器
@SpringBootTest(classes = RunBoot.class)
public class TestSharding {

    @Resource
    private CityRepository cityRepository;

    @Test
    public void testAdd3(){
        City city = new City();
        city.setName("北京");
        city.setProvince("北京");
        cityRepository.save(city);
    }
}

6、查看效果

两个库都同时添加了同一条记录信息
image.png image.png