java 如何在休眠中进行级联保存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6763181/
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 do a cascade save in hibernate
提问by akshay
I have objects A and B.
我有对象 A 和 B。
Object A is like
对象 A 就像
class A{
Set<B>
}
Now when I save A I want that all objects in Set<B>
of A should be automatically saved in DB. How can I do it?
现在,当我保存 AI 时,希望Set<B>
A中的所有对象都应自动保存在 DB 中。我该怎么做?
回答by Ransom Briggs
// Use the cascade option in your annotation
@OneToMany(cascade = {CascadeType.ALL}, orphanRemoval = true)
public List<FieldEntity> getB() {
return fields;
}
回答by Nikola
The question from Ransom will work if you are working through EntityManager and using pure JPA annotations. But if you are using Hibernate directly, then you need to use its own annotation for cascading.
如果您通过 EntityManager 工作并使用纯 JPA 注释,那么来自 Ransom 的问题将起作用。但是如果直接使用Hibernate,那么就需要使用它自己的注解进行级联。
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
...
@OneToMany
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
public List<FieldEntity> getB() {
return fields;
}