java 如何将对象添加到对象列表并保留所有先前存在的对象?

watbbzwu  于 2022-12-10  发布在  Java
关注(0)|答案(1)|浏览(165)

我是Java新手,我想更新一个列表,而不丢失列表中已经存在的产品。

产品列表:

@Entity
@Table(name = "listOfProducts")
public class ProductsList {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "products_id",
            joinColumns = @JoinColumn(name = "id_list"),
            inverseJoinColumns = @JoinColumn(name = "id_product")
    )
    private Set<Product> products;

产品实体

@Entity
@Table(name = "product")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "tabla_id",
            joinColumns = @JoinColumn(name = "id_product"),
            inverseJoinColumns = @JoinColumn(name = "id_list")
    )
    @JsonIgnore
    private List<ProductsList> productsLists;

列出服务

// now it only has the CRUD

我似乎找不到任何解决这个问题的方法。我找到了更新列表的方法,但它总是以删除列表中以前的所有产品而告终。
另外:由于某种原因,现在它也要求我将for (j:listaRepository.findById(id)) {更改为for (j:listaRepository.findById(id);;) {

ac1kyiln

ac1kyiln1#

这是我在我的服务中用来解决这个问题的方法:

public ListOfProducts addProductToList(Integer idList, Integer idProduct) throws ResourceNotFoundException {

    ListOfProducts listOriginal = listRepository.findById(idList).orElseThrow(()-> new  ResourceNotFoundException("The list of products could not be found."));
    Product product = productRepository.findProductById(idProduct).orElseThrow(()->new ResourceNotFoundException("Product not found"));

    listOriginal.getProducts().add(product);

    listRepository.save(listOriginal);
    LOGGER.info(String.format("Product %s was added to the list with id %s ", idProduct, idList));

    return listOriginal;
}

相关问题