I would like to display the tree structure of the "chapters". Each chapter has a link to its parent and an ordered list (by "position") of the sub-chapter. With JPA 2.0, Hibernate 3.5, the Chapter entity is as follows:
@Entity
public class Chapter {
@Id
@GeneratedValue
private long id;
@Column(name="position", nullable=false)
private int position;
@ManyToOne
@JoinColumn(name="parentChapter_id", updatable=false, insertable=false)
private Chapter parentChapter;
@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
@OrderColumn(name="position")
@JoinColumn(name="parentChapter_id")
private List<Chapter> subChapters = new ArrayList<Chapter>();
public List<Chapter> getSubChapters() {
return subChapters;
}
}
The problem is that if one of the items is subChaptersdeleted
Chapter parent = em.find(Chapter.class, 1);
subChapters = parent.getSubChapters();
subChapters.remove(1);
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(parent);
tx.commit();
then hibernate is trying to fulfill this statement
update
Chapter
set
parentChapter_id=null,
position=null
where
parentChapter_id=?
and id=?
which fails due to limitation NOT NULL position. If @OrderColumn(name="position")deleted, Hibernate does not update position(and therefore it works) and then deletes (sub) Chapter. What makes Hibernate update the future orphan first and then delete it?