问题:saveBatch时 遇到Duplicate entry '1828978156126666754' for key
分析:1.检查数据库里是否有重复ID
2.检查代码中是否有id赋值
3.
以上排查都没发现问题,以下代码分析了一下,为了节省空间,我在for循环上面new了一个封装类,
执行for时,把封装类放到了数组,但是数组里放的其实都是同一个对象,这样saveBatch的时候,第一次执行成功时,
会把id写回该对象,同时list中元素的id值,也将被改变为同一个。
解决:
放入List中的元素,要保证是不同的对象
错误代码:
AssetLedger assetsLedger = new AssetLedger(); assetsLedger.setBrand(brand); assetsLedger.setModel(model); assetsLedger.setAssetsName(assetsName); assetsLedger.setPriority(1); BeanUtil.packAddBaseProps(assetsLedger, request); if (entryNum > residueNum) { entryNum -= residueNum; assetsEntryService.reduceResidueNum(assetEntryVO.getId(), residueNum); for (int j = 0; j < residueNum; j++) { assetsLedger.setEntryId(assetEntryVO.getId()); assetsLedger.setReceiveId(receifeId); assetsLedger.setState(LedgerStateEnum.RECIVE.getValue()); assetsLedger.setUserId(assetReceifeDTO.getReceiveUser()); assetsLedger.setNumber(1); assetsLedger.setId(null); assetsLedgers.add(assetsLedger); } } assetLedgerService.saveBatch(assetsLedgers);
正确代码:
for (int j = 0; j < residueNum; j++) { AssetLedger assetsLedger = new AssetLedger(); assetsLedger.setBrand(brand); assetsLedger.setModel(model); assetsLedger.setAssetsName(assetsName); assetsLedger.setPriority(1); BeanUtil.packAddBaseProps(assetsLedger, request); assetsLedger.setEntryId(assetEntryVO.getId()); assetsLedger.setReceiveId(receifeId); assetsLedger.setState(LedgerStateEnum.RECIVE.getValue()); assetsLedger.setUserId(assetReceifeDTO.getReceiveUser()); assetsLedger.setNumber(1); assetsLedger.setId(null); assetsLedgers.add(assetsLedger); }
标签:assetsLedger,saveBatch,residueNum,AssetLedger,Duplicate,1828978156126666754,key, From: https://www.cnblogs.com/charkey/p/18386092