这是我的实体 Product。它与 ProductImages 具有 OneToMany 关系。
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Fetch(value = FetchMode.SELECT)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@org.springframework.data.annotation.Transient
@JsonIgnoreProperties(value = { "product" }, allowSetters = true)
@BatchSize(size = 20)
private Set<ProductImages> productImages = new HashSet<>();
}
当我尝试通过添加另一张图像来更新产品时。它运行良好。但是当我删除一个或多个图像时,它不会更新。
public Product update(Product product) {
log.debug("Request to update Product : {}", product);
Product result = productRepository.save(product);
productSearchRepository.index(result);
return result;
}
有什么解决方案不涉及比较和删除
productRepository.save(product);
之前具有 ProductId 的图像吗?
为了澄清我的问题,是否有任何注释可以自动执行此操作?
尝试比较传入更新方法的
productImages
中的传入和现有 product
哈希集,然后保存新的 productImages
和/或删除已删除的 productImages
,然后再次保存 product
。
public Product update(Product product) {
log.debug("Request to update Product : {}", product);
Product oldProduct = productRepository.findById(product.getId());
//check the difference between
//oldProduct.getProductImages() and product.getProductImages()
//delete old images from ProductImagesRepo
//save newly added images to ProductImagesRepo
Product result = productRepository.save(product);
productSearchRepository.index(result);
return result;
}
这应该可行,但我不明白为什么你不想删除在productRepository.save(product);之前具有ProductId的图像?