To delete only the association is simple. Suppose the scenario below:
@ManyToMany(cascade = CascadeType.PERSIST)
private List<Foo> foos;
If you remove an element from Foos and save the entity you will delete the record in the Join table.
EDIT
I don’t particularly like to run away from the ORM context. So if going through the list and deleting the elements one by one is a burden I can give two alternatives:
- If you can use java 8, use a Lamda. With a single command you scroll through the list and remove what you want.
- If Java 8 is not a solution, use the utluiz answer. It serves you.
As I told you in the comments: This type of approach you seek is not cool because it creates the need to perform a delete and then a refresh to update your entire session (which will ultimately be less performatic), and make your system error-prone as you are dealing with objects detached who may accidentally be rearward, making your system inconsistent.
Go through the list, delete the elements and then save the object is less costly in most cases as you are working in-memory most of the time, and more robust by not leaving the ORM context.
So if you’re going to work in a different way than this I suggest you evaluate if JDBC won’t suit you better.
The problem is that I won’t delete any of the two objects, I just want to unlink them.
– NilsonUehara
@Nilsonuehara edited my answer, see if it helps.
– Edgar Muniz Berlinck
Yes, that’s what I do now. I wanted to avoid having to iterate all collections to remove one by one. I wanted to do something like: delete from Link Where B.id=1, so all objects that are related to B would have their link deleted.
– NilsonUehara
@Nilsonuehara you have to understand that this is not SQL. Using this type of approach can make your Entity manager confused and cause inconsistencies, if it is to work that way I suggest you use jdbc. Now the answer of utluiz does what you want.
– Edgar Muniz Berlinck
Edgar, your answer is the correct answer from JPA’s point of view. The problem is that this solution is sub-optimal, because JPA is sub-optimal for this type of task. In fact, all these problems have made me think 500 times before using JPA on a project. Jdbctemplate has given me much less headache in projects that have moderate level of complexity at least.
– utluiz
@utluiz I agree in part with you. There is no silver bullet, that’s fact. Now a lot of people use technology in ways that shouldn’t be used, it creates thoughts like what you’ve expressed, which in a way is fair. What user wants with this question is to ask a by-pass in the framework, which should not be done. There is a saying that says: Being able to do something doesn’t mean you should do it.
– Edgar Muniz Berlinck