On a onetomany associations I am attempting to delete all the many associations and see that multiple delete statements are being executed.
// The entities
class Users{
...
public void setPhones(Set<Phone> phones){
this.phones = phones;
}
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="users", orphanRemoval=true)
public Set<Phone> getPhones(){
return this.phones;
}
...
}
class Phone{
...
@ManyToOne()
@JoinColumn(name="USER_ID")
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
...
}
//The application code...
Users u = (Users)s.get(Users.class, new Integer(220));
u.getPhones().clear();
The above code deletes the phones alright, except that I see multiple delete statements being sent to the database. I'd rather prefer a single statement similar to:
delete from phone where userid = 220;
The hibernate manual that describes the one-shot delete is confusing and in fact results in an error. Specifically the section that mentions:
Fortunately, you can force this behavior (i.e. the second strategy) at any time by discarding (i.e. dereferencing) the original collection and returning a newly instantiated collection with all the current elements.
Replacing the collection with a new collection results in an exception. And then there is this line:
One-shot-delete does not apply to collections mapped inverse="true".
I am not sure why. Can some one please elaborate on this? How does one perform a one-shot delete using Hibernate on a onetomany association?