Java 如何在休眠注释中使用级联类型保存、删除、更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21230688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use cascade type save,delete, update in hibernate annotation
提问by user3214269
Can any one explain me the hibernate annotation how to use different types of cascade like delete,upadte,save-update?
任何人都可以向我解释休眠注释如何使用不同类型的级联,如删除、更新、保存更新?
How can I make sure that when an Owner is deleted, its car is deleted as well (but not the other way around)
我如何确保当所有者被删除时,它的汽车也被删除(但不是相反)
@Entity
public class Owner
{
@OneToOne(cascade=CascadeType.ALL)
private DrivingLicense license;
@OneToMany(mappedBy="owner", cascade={CascadeType.PERSIST, CascadeType.MERGE})
private Collection cars;
...
}
@Entity
public class DrivingLicense
{
private String serialNumber;
...
}
@Entity
public class Car
{
private String registrationNumber;
@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE})
private Owner owner;
...
}
回答by Joeri Hendrickx
The pitfall here is that there are two CascadeType enums. One is of javax.persistence, the other is from hibernate. In general I would prefer to use the persistence one.
这里的缺陷是有两个 CascadeType 枚举。一个是javax.persistence,另一个来自hibernate。一般来说,我更喜欢使用持久性。
For cascade update, keep in mind that "update" is a hibernate term, and jpa doesn't know this. Jpa doesnt need it, because in JPA the idea is that your updated fields will flush to the database automatically. If you made any changes in relations, those will flush as well. So you dont need a cascade on update.
对于级联更新,请记住“更新”是一个休眠术语,而 jpa 不知道这一点。Jpa 不需要它,因为在 JPA 中的想法是您更新的字段将自动刷新到数据库。如果您对关系进行了任何更改,它们也会刷新。所以你不需要级联更新。
For save-update, this is a hibernate shortcut to using either persist or update depending on the state of the object. Since you're already covering persist and update(see above), you dont need a cascade on this.
对于保存更新,这是根据对象的状态使用持久或更新的休眠快捷方式。由于您已经涵盖了持久和更新(见上文),因此您不需要级联。
To cascade a delete, you probably want to use @OrphanRemoval
instead. This will make sure that if the parent of a relation is removed, the child is gone, too (but not the other way around).
要级联删除,您可能想@OrphanRemoval
改用。这将确保如果关系的父级被删除,子级也消失了(但不是相反)。
@OneToMany(mappedBy="owner", cascade={CascadeType.PERSIST, CascadeType.MERGE})
@OrphanRemoval
private Collection cars;