0

I am new with Spring jpa and I am trying to perform the deletion operation on spring jpa many to many database. My database has user and drug. I can delete an user and deletes also the rows associated to it from user_drug table, I can delete a drug that has no linking to the user_drug table, but i cannot delete a drug that is also in the user_drug table. I had a look on this page but the solutions from there do not work for me.. How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

Here is my code for User entity:

 @ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
 @JoinTable(name = "user_drug",
        joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "drug_id", referencedColumnName = "id"))
 private Set<Drug> drugs = new HashSet<>();

Here is the code for Drug entity:

 @ManyToMany(mappedBy = "drugs",  fetch=FetchType.EAGER)
 private Set<User> users = new HashSet<>();

And here is the delet method from DrugServiceImpl:

public void delete(Drug drug)
{
    drug.getUsers().clear();
    drugRepository.delete(drug);
}

I have also printed the size of drug.getUsers() after clear operation and it is 0. Why isn't it delete the drug from database?
I've tried in many ways.. Can someone please send some help?

VladGeo
  • 11
  • 3
  • Create a transaction that deletes it from both sides? – dan1st Apr 09 '20 at 16:48
  • If i want to delete a drug I want it to be deleted from user_drug and from drug. But the users that bought that drug should not be deleted from the user database – VladGeo Apr 09 '20 at 16:53
  • I mean remove the drug's reference from the user, and then (in a transaction) save the user's state and delete the drug from the DB. – dan1st Apr 09 '20 at 16:55
  • Excellent! I did it, now it works. Thank you sooo much! – VladGeo Apr 09 '20 at 17:16

1 Answers1

0

that is how the cascade works it deletes from the relation table only and in the ManyToMany the relation table here is the user_drug table

and for this cases there are many solution one of them is deleting the drug in the same transaction of the deleting user

but another solution that will save the effort that you create the ManyToMany table as entity and put cascade on the drug object in the relation table

like this

But this in the User entity

@ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user")
private Set<UserDrug> drugs = new HashSet<>();

the UserDrug entity

public class UserDrug {
    @ManyToOne
    @JoinColumn(name="user_id")
    User user;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="drug_id")
    Drug drug;

 }
Khaled Ahmed
  • 1,074
  • 8
  • 21