Old data is deleted in OneToMany Mapping

Product and ProductLine. One ProductLine can have many products.

Product.java: -

@Entity
    @Table(name ="PRODUCT")
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        private String name;
    Product(String name){
            this.name=name;
        }
    }

ProductLine.java

   public class ProductLine {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        @OneToMany(cascade = CascadeType.ALL)
        @JoinTable(name = "PRODUCTLINE_PRODUCT", joinColumns = @JoinColumn(name = "PRODUCTLINE_ID"), inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID"))
        private List<Product> products=new ArrayList<>();

     public ProductLine(String name){
        this.name=name;
        }
    }

ProductLineRepository.java

 public interface ProductLineRepository extends JpaRepository<ProductLine,Integer> {
            ProductLine findOneById(String id);
        ProductLine findOneByName(String name);
        }

Controller: -

In the controller, I parse the list of products associated with the Product from the user in json form and save it in the database.

public void addData(){
        List<Product> products=new ArrayList<>();
        Product product1=new Product("Iphone");
        Product product2=new Product("Mac");
        products.add(product1);
        products.add(product2);
        ProductLine productLine=productLineRepository.findOneByName("Apple");
        productLine.setProducts(products);
        productLineRepository.save(productLine);
    }

Now, if the Apple product line already exists, it deletes the entry in the Product Line table with the name Apple, and then inserts the IPhone and Mac data again. But I do not want the old data to be deleted. What should I do?

+4
source share
3 answers

orphanRemoval, ( , ), .

JPA 2.0 orphanRemoval , , , , , , , orphanRemoval

@OneToMany(cascade = CascadeType.ALL, orphanRemoval="false")
@JoinTable(name = "PRODUCTLINE_PRODUCT", joinColumns = @JoinColumn(name = "PRODUCTLINE_ID"), inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID"))
private List<Product> products=new ArrayList<>();
0

, ProductLine "Apple" persistence findByName(), , Line, .

0

, ...

, @ManyToMany:

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "PRODUCTLINE_PRODUCT", joinColumns = @JoinColumn(name = "PRODUCTLINE_ID"), inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID"))

, ... @OneToMany, :

@OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
0
source

Source: https://habr.com/ru/post/1685071/


All Articles