Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Old Data is getting 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 have a am parsing the list of products associated with the Product from the user in the json form and persisting it into DB.

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 Product Line "Apple" already exists then it deletes the entry in the Product Line table with the name "Apple" and then again inserts the data "IPhone" and "Mac" . But i do not want the old data to be deleted . What should i do?

like image 277
Sunny Avatar asked Oct 17 '22 06:10

Sunny


1 Answers

This behavior is called orphanRemoval, when an entity is removed from the relation (this is what you are doing when setting new product list) it will be removed.

since JPA 2.0 the default value for orphanRemoval is false so if you are using this version or higher this behavior should not be there so i guess you are using lower version, either you use higher version or you can set the orphanRemoval attribute to false

@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<>();
like image 152
Amer Qarabsa Avatar answered Nov 03 '22 02:11

Amer Qarabsa