更新 OneToMany 记录时无法删除

问题描述 投票:0回答:1

这是我的实体 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 的图像的解决方案?

java spring jpa spring-data
1个回答
0
投票

尝试比较传入更新方法的

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的图像?

© www.soinside.com 2019 - 2024. All rights reserved.