【解决】Springboot+Mybatis数据分表后前端如何根据条件映射到对应子表中查询数据?!
一、问题提出
对于大量数据的存储,使用分库分表方案是解决查询效率问题的关键。实际应用中,前端如何根据条件映射到指定子表进行数据查询呢?今天良哥手把手教你实现该方案。
二、解决方案
1)前端页面增加查询参数:tableName
// 查询参数queryParams: {pageNum: 1,pageSize: 20,//当前查询的历史记录表名tableName: 'chemical_history_data',pid: null,pcode: null,pname: null,ord: null,measureValue: null,alarmStatus: null,alarmMsg: null,receiveTime: null,params: {sort: "receive_time desc, ord"}},
2)提交查询时根据当前条件指定数据所在的子表名称,并将表名更新到查询参数中:this.queryParams.tableName = ‘xxxx’
/** 查询历史数据列表 */getList() {this.loading = true;this.queryParams.tableName = "chemical_history_data";this.queryParams.params.beginReceiveTime = this.queryParams.params.endRecordTime = null;if (null != this.daterangeReceiveTime && '' != this.daterangeReceiveTime) {// 封装查询开始时间和结束时间this.queryParams.params["beginReceiveTime"] = this.daterangeReceiveTime[0];this.queryParams.params["endReceiveTime"] = this.daterangeReceiveTime[1];// 根据开始时间生成要查询的历史数据表名let curDate = new Date();let queryDate = new Date(this.queryParams.params["beginReceiveTime"]);if (curDate.getDate() != queryDate.getDate()) {this.queryParams.tableName += "_" + queryDate.getFullYear()+ (queryDate.getMonth()<9?"0":"") + (queryDate.getMonth()+1)+ (queryDate.getDate()<10?"0":"") + (queryDate.getDate());if (!this.historyTableNames.includes(this.queryParams.tableName)) {this.$message.error("数据源不存在:" + this.queryParams.tableName);this.queryParams.tableName = "chemical_history_data";}}}listHistoryData(this.queryParams).then(response => {this.historyDataList = response.rows;this.total = response.total;this.loading = false;});},
3)后端实体增加查询参数:tableName
public class ChemicalHistoryData extends BaseEntity
{private static final long serialVersionUID = 1L;/** 表名 */private String tableName;/** 测点id */private Long pid;/** 测点编码 */@Excel(name = "测点编码")private String pcode;/** 测点名称 */@Excel(name = "测点名称")private String pname;………………………………………………………………………………
}
4)扩展mapper文件查询语句,添加数据表名接收参数&{tableName}
<sql id="selectChemicalHistoryDataVo">select pid, ord, pname, pcode, measure_value, alarm_status, alarm_msg, receive_time from<if test="tableName == null or tableName == ''"> chemical_history_data </if><if test="tableName != null and tableName != ''"> ${tableName} </if></sql>
三、效果验证
完美实现!!!