简体   繁体   中英

Hibernate @version not incrementing when adding to collection of children

I'm using Hibernate 4.1.4.Final and I have a parent with a version and a list of children in a separate table.

The problem I'm running into is that when I add to the list of children the version on the parent is not being incremented. I could do it manually, but that partially defeats the purpose of using the @version annotation.

How do I get the parent's version to increment when I update the children or add to the list of children?

Parent:

@Entity
@Table(name = "Parent")
public class Parent implements java.io.Serializable {

  @Version
  @Column(name = "version")
  private int _version;

  @OneToMany(mappedBy = "_parent", cascade = javax.persistence.CascadeType.ALL)
  @OrderBy(clause = "id")
  @Cascade({CascadeType.ALL})
  private List<Child> _children= new ArrayList<Children>();
}

Child:

@Entity
@Table(name = "Child")
public class Child {


   @Id
   @Column(name = "id")
   @GeneratedValue(generator = "native")
   @GenericGenerator(name = "native", strategy = "native")
   private Integer _id;

   @ManyToOne
   @JoinColumn(name = "parentId")
   private Parent _parent;
}

Thank you

Though undocumented, you can add @OptimisticLock(excluded = false) on the one-to-many side. I tested it using hibernate-core 4.3.5.Final.

To be JPA compliant, you need to make Parent - instead of Child - the owning side of the collection. AFAIK, there are three ways to do that:

  1. Make Child an embeddable object. See both 7.2.3 and 9.2 in the Hibernate documentation.
  2. Use @OneToMany with a @JoinColumn
  3. Use @OneToMany with a @JoinTable

The way you have it coded used to work, but it was a bug that's since been fixed even if section 23.1 of the documentation still seems incorrect - or at least confusing - to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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