公共表屬於系統中數據量較小,變動少,而且屬於高頻聯合查詢的依賴表。參數表、數據字典表等屬於此類型。可以將這類表在每個數據庫都保存一份,所有更新操作都同時發送到所有分庫執行。接下來看一下如何使用Sharding-JDBC實現公共表。
(1)創建數據庫
分別在user_db、order_db_1、order_db_2中創建t_dict表:
CREATE TABLE `t_dict` ( `dict_id` bigint(20) NOT NULL COMMENT '字典id', `type` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '字典類型', `code` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '字典編碼', `value` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '字典值', PRIMARY KEY (`dict_id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
(2)在Sharding-JDBC規則中修改
# 指定t_dict為公共表
spring.shardingsphere.sharding.broadcast-tables=t_dict
(3)數據操作
新增DictDao:
@Mapper @Component public interface DictDao { /** * 新增字典 * * @param type 字典類型 * @param code 字典編碼 * @param value 字典值 * @return */ @Insert("insert into t_dict(dict_id,type,code,value) value(#{dictId},#{type},#{code},#{value})") int insertDict(@Param("dictId") Long dictId, @Param("type") String type, @Param("code") String code, @Param("value") String value); /** * 刪除字典 * * @param dictId 字典id * @return */ @Delete("delete from t_dict where dict_id = #{dictId}") int deleteDict(@Param("dictId") Long dictId); }
(4)字典操作測試
新增單元測試方法:
@Test public void testInsertDict() { dictDao.insertDict(1L, "user_type", "0", "管理員"); dictDao.insertDict(2L, "user_type", "1", "操作員"); } @Test public void testDeleteDict() { dictDao.deleteDict(1L); dictDao.deleteDict(2L); }
執行testInsertDict:

通過日志可以看出,對t_dict的表的操作被廣播至所有數據源。
測試刪除字典,觀察是否把所有數據源中該 公共表的記錄刪除。
(5)字典關聯查詢測試
字典表已在各各分庫存在,各業務表即可和字典表關聯查詢。
定義用戶關聯查詢dao:
在UserDao中定義:
/** * 根據id列表查詢多個用戶,關聯查詢字典表 * * @param userIds 用戶id列表 * @return */ @Select({"<script>", " select", " * ", " from t_user t ,t_dict b", " where t.user_type = b.code and t.user_id in", "<foreach collection='userIds' item='id' open='(' separator=',' close=')'>", "#{id}", "</foreach>", "</script>" }) List<Map> selectUserInfobyIds(@Param("userIds") List<Long> userIds);
定義測試方法:
@Test public void testSelectUserInfobyIds(){ List<Long> userIds = new ArrayList<>(); userIds.add(1L); userIds.add(2L); List<Map> users = userDao.selectUserInfobyIds(userIds); JSONArray jsonUsers = new JSONArray(users); System.out.println(jsonUsers); }
執行測試方法,查看日志,成功關聯查詢字典表: 
