记录一个根据分表id查询分表数据报NPE异常,注意参数类型

120 阅读1分钟

 下面是在配置文件中设置的分表策略

#所有数据节点
sharding.jdbc.config.sharding.tables.r_template_data_list.actual-data-nodes=crm.r_template_data_list_${0..9}
#根据这个列分表
sharding.jdbc.config.sharding.tables.r_template_data_list.table-strategy.inline.sharding-column=template_id
#分表规则为:取模
sharding.jdbc.config.sharding.tables.r_template_data_list.table-strategy.inline.algorithm-expression=r_template_data_list_${template_id % 10}

String[] ids = templateIds.split(",");
for (String templateIdStr : ids) {
                if (!StringUtils.isNumeric(templateIdStr)){
                    log.info("参数值中的"+templateIdStr+"非法,跳过");
                    continue;
                }
                Wrapper<RTemplateDataList> wrapper = new EntityWrapper<>();
                wrapper.eq("template_id",templateIdStr);
                List<RTemplateDataList> dataLists =         rTemplateDataListService.selectList(wrapper);
......
}

通过上面的代码运行,会出现NPE异常,shadingjdbc不会捕获和提示这个异常,原因是查询参数也是分表规则取模用的参数,必须保证是表中对应的数据类型,上面应该将参数转为Integer类型即可。

String[] ids = templateIds.split(",");
            for (String templateIdStr : ids) {
                if (!StringUtils.isNumeric(templateIdStr)){
                    log.info("参数值中的"+templateIdStr+"非法,跳过");
                    continue;
                }
                Integer templateId = Integer.parseInt(templateIdStr);
                Wrapper<RTemplateDataList> wrapper = new EntityWrapper<>();
                wrapper.eq("template_id",templateId);
                List<RTemplateDataList> dataLists = rTemplateDataListService.selectList(wrapper);
......
}