简体   繁体   English

如何使用javax.persistence.OneToMany在Hibernate 4中的级联上设置更新?

[英]How to setup update on cascade in hibernate 4 with javax.persistence.OneToMany?

I use hibernate 4.2. 我使用休眠4.2。

It doesn't give me hibernate variant of OneToMany annotation, but only javax.persistence.OneToMany . 它没有给我OneToMany注释的休眠变体,而只有javax.persistence.OneToMany

So I use it as 所以我用它作为

public class Parent  {
      ...........
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
        private Set<Child> children = new HashSet<Child>();

When I do update of Parent I expect children collection to be updated by cascade MERGE. 当我更新父项时,我希望子级集合可以通过级联MERGE进行更新。

session.update(parent);

But it doesn't update Child entities of children collection. 但是它不会更新children集合的Child实体。 It only sends update statement for Parent entity. 它仅发送父实体的更新语句。

So how can I update on cascade Child entities of children collection? 因此,如何能在我的级联子实体更新children收集?

I cannot use org.hibernate.annotations.CascadeType because it is not supported by javax.persistence.OneToMany. 我不能使用org.hibernate.annotations.CascadeType因为javax.persistence.OneToMany不支持它。

If you want to use hibernate's CascadeType , define @Cascade(..) separately on field/method level, 如果要使用休眠的CascadeType ,请在字段/方法级别分别定义@Cascade(..)

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
@Cascade({CascadeType.PERSIST, CascadeType.MERGE, CascadeType.SAVE_UPDATE}) //example
private Set<Child> children = new HashSet<Child>();

Instead of persist or merge did you try with all?. 您没有尝试全部保留还是合并?

   @OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)

Try it just in case that you want to remove this child in case that the father would be removed. 请尝试一下,以防万一您想删除此孩子,以防父亲被删除。

In my example works 在我的例子中作品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM