在 onetomany 关联上使用 hibernate 一键删除
在一对多关联上,我尝试删除所有多个关联,并看到正在执行多个删除语句。
// 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();
上面的代码可以删除手机,只是我看到多个删除语句被发送到数据库。我宁愿更喜欢类似于以下内容的单个声明:
delete from phone where userid = 220;
描述 一次性删除 令人困惑,实际上会导致错误。特别是提到的部分:
幸运的是,您可以随时通过丢弃(即取消引用)原始集合并返回包含所有当前元素的新实例化集合来强制执行此行为(即第二种策略)。
用新集合替换该集合会导致异常。然后有这一行:
一次性删除不适用于映射 inverse="true" 的集合。
我不知道为什么。有人可以详细说明一下吗? 如何使用 Hibernate 对一对多关联执行一次性删除?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该文档并不令人困惑 - 它只是说这不适用于反向控制(映射为)。您所需要做的就是删除多对一一侧和一对多中的映射声明。然后由用户完成关系的控制,然后将发生单一删除。
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.