I have a parent child relationship with automatic versioning (optimistic locking). We have noticed when we create a new parent and child and then save it, Hibernate performs an insert on each table (parent and child) and then does an additional update on the parent.
If I remove the version number the update does not happen, so I presume it is updating the version number because of the child entity. This will be doing high volume so the additional update places a large overhead on the insertion, so is there a way of stopping this from happening?
We are using Hibernate 3.6.10. I have created simple example of the classes below.
Code:
@Entity
public class Parent {
@EntityField(display=false)
protected Long id;
private Set<Child> children = new HashSet<>();
private String name;
@EntityField(display=false)
private int version = 0;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToMany(mappedBy = "parent",orphanRemoval=true,cascade = {CascadeType.ALL}, fetch=FetchType.EAGER)
public Set<Child> getChildren() {
return children;
}
public void setChildren(Set<Child> children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Version
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
@Entity
public class Child {
@EntityField(display=false)
protected Long id;
private Parent parent;
private String name;
@EntityField(display=false)
private int version = 0;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name = "parentId")
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Version
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
and this is what I see in the logs
Hibernate: insert into Parent (name, version) values (?, ?)
Hibernate: insert into Child (name, parentId, version) values (?, ?, ?)
Hibernate: update Parent set name=?, version=? where id=? and version=?