开发者

one shot delete with hibernate on onetomany association

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)
    开发者_JS百科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?


The doc is not confusing - it just says that this would not work with inversed control (mapped by). All you need to do it remove the many-to-one side and the mapped by declaration in the one-to-many. Then control of the relation is done by users and then single delete will happen.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜