我正在更新几个实体以进行更新,如下所示。基本上,我想在ArchiveProduct实体中保存2或3个产品条目,以跟踪更改了哪些列以稍后通知用户。但是以某种方式在更新过程中,出现了死锁错误“ com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException:尝试获取锁时发现了死锁;尝试重新启动事务”。
long current = System.currentTimeMillis();
List<ProductEntity> products = productRepository.findProductsBySupplier(supplierEntity, productIds);
for (ProductEntity productEntity : products) {
List<ArchiveProductEntity> archiveProducts = productEntity.getArchiveProducts();
if (archiveProducts != null && archiveProducts.size() > 2) {
ArchiveProductEntity archiveProduct = archiveProducts.get(0);
archiveProductRepository.removeArchiveProduct(archiveProduct);
}
ArchiveProductEntity archiveProductEntity = new ArchiveProductEntity();
BeanUtils.copyProperties(productEntity, archiveProductEntity);
archiveProductEntity.setDataChangeDate(current);
archiveProductEntity.setProduct(productEntity);
archiveProductRepository.saveArchiveProduct(archiveProductEntity);
productEntity.setQuantity(quantity);
productEntity.setUpdatedTime(System.currentTimeMillis());
}
但是在我像下面那样更改代码后,我不再遇到死锁错误。有人知道这个问题吗?如果以下代码有效,我肯定会使用,但是我想知道为什么...
long current = System.currentTimeMillis();
List<ArchiveProductEntity> updatedArchiveProducts = new ArrayList<>();
List<ProductEntity> products = productRepository.findProductsBySupplier(supplierEntity, productIds);
for (ProductEntity productEntity : products) {
List<ArchiveProductEntity> archiveProducts = productEntity.getArchiveProducts();
if (archiveProducts != null && archiveProducts.size() > 2) {
ArchiveProductEntity archiveProduct = archiveProducts.get(0);
archiveProductRepository.removeArchiveProduct(archiveProduct);
}
ArchiveProductEntity archiveProductEntity = new ArchiveProductEntity();
BeanUtils.copyProperties(productEntity, archiveProductEntity);
archiveProductEntity.setDataChangeDate(current);
archiveProductEntity.setProduct(productEntity);
updatedArchiveProducts.add(archiveProductEntity);
//archiveProductRepository.saveArchiveProduct(archiveProductEntity);
productEntity.setQuantity(quantity);
productEntity.setUpdatedTime(System.currentTimeMillis());
}
for (ArchiveProductEntity archiveProduct : updatedArchiveProducts) {
archiveProductRepository.saveArchiveProduct(archiveProduct);
}
奇怪的是,即使我看到此错误消息,数据仍在更新。
谢谢。