前言:今天在开发数据库插入数据的过程中,发现之前的数据插入都是先将 json 数据转为 model,再将model 转为数据集,这样再往数据库里面存储的方式。今天开发过程中,发现需要被存储的数据是 Map 格式的,如果还按照原来的思路来处理,Map 数据------>Json 数据------>Model 对象------>ValuesBucket数据,再执行存储,相当于多了步骤,虽然也可以这么操作,但是对于我们来说,如果数据量比较大,就加大了处理器的负担,所以我直接将 Map 数据转为ValuesBucket数据,这样中间就节省了处理器的开支,并且成功存储数据。 下面是 Map 转ValuesBucket的方法:
typescript
function mapToValuesBucket(map: Map<string, string | number | boolean>): ValuesBucket {
let valuesBucket: ValuesBucket = {}
map.forEach((value, key) => {
valuesBucket[key] = value
});
return valuesBucket;
}
const prodDisMap = new Map<string, string>();
prodDisMap.set('name', '产品 1');
prodDisMap.set('code', '00001');
const valuesBucket = mapToValuesBucket(prodDisMap);
console.info(`valuesBucket:${JSON.stringify(valuesBucket)}`)
我们项目中的存储数据库方法如下:
typescript
function parseBaseStoreProductDisData(context: Context, jsonData: string, serverNode:string) {
DatabaseManager.deleteTableDataByTabName(context,"base_store_prod_dis",serverNode);
try {
//整理数据
//分销规则数组,暂时写死处理,后续再从登录数据获取
let sepcList:string[] = ["drid", "pid", "dist", "pri", "inv", "aging", "disp", "sdisp", "cmpt", "oos", "mtd", "ord", "gofa", "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10", "genid"]
//原始数据模型
let originalStoreProDisList:BaseProductDisModel[] = JSON.parse(jsonData)[serverNode];
let allProdDisList: Map<string,string>[] = []
let parseProductDisList: ValuesBucket[] = [];
//转为需要存储回显表的数据模型
for (let i = 0; i < originalStoreProDisList.length; i++) {
const valueBucket1: ValuesBucket = {}
let element = originalStoreProDisList[i];
let prodDisMap = new Map<string, string>();
let pStr:string = element.p as string;
if (pStr!=undefined&&pStr.length>0) {
let propertyList:string[] = pStr.split(',');
for (let index = 0; index < propertyList.length; index++) {
const columnValue:string = propertyList[index] as string;
let columnName:string = '';
if (sepcList.length > index) {
columnName = sepcList[index] as string;
if (columnName.length>0&&(columnName == 'sid' || columnName == 'drid' || columnName == 'drId')) {
columnName = 'store_id'
}else if (columnName.length>0 && columnName =='pid'){
columnName = 'prod_id'
}
}
prodDisMap.set(columnName,columnValue);
}
if (element.gen_id&&element.gen_id.length>0) {
prodDisMap.set('genid',element.gen_id);
}
if (serverNode&&serverNode.length>0){
prodDisMap.set('server_node',serverNode);
}
if (prodDisMap) {
//Map 转valuesBucket
const valuesBucket = mapToValuesBucket(prodDisMap);
parseProductDisList.push(valuesBucket);
}
}
}
DatabaseManager.batchInsertTableData(context, "base_store_prod_dis", parseProductDisList);
} catch (error) {
WinLog.info("base_product insert error" + error)
}
}
完美实现我想要的方法。 数据库插入报错:10-11 17:17:23.730 17950-17950 A03d00/JSAPP net.winch...l.winsfa I [INFO ] 2024-10-11 17:17:23,729 [Index:54] Winchannel--->base_product insert errorTypeError: Cannot read property length of undefined 各位有遇到?