Maxim Sukhodolets
Maxim Sukhodolets

Reputation: 129

Delete record only from parent entity

In my project i have 2 entities related @OneToMany and @ManyToOne. Check these pictures -

enter image description here enter image description here

My problem-when i delete record from Supplies also delete records from Products but i don't wont it.If i remove CascadeType.ALL and then try this opertion again there will be an error

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (shop.products, CONSTRAINT FK65gu3e053fcnl70hwq8vp7b2g FOREIGN KEY (supplies) REFERENCES supplies (id))

How resolve this problem???

Upvotes: 0

Views: 38

Answers (1)

Maxim Sukhodolets
Maxim Sukhodolets

Reputation: 129

Oh,after 30 minutes of thinking i solved it. I just added this code in my delete method

@Override
public void deleteSupply(Long id) {
    Supplies supplies = supplyRepository.findById(id).orElse(null);
    Set<Products> productsList = supplies.getProducts();
    productsList.forEach(products -> products.setSupplies(null));

    supplyRepository.deleteById(id);
}

Upvotes: 0

Related Questions