Why did hibernate / jpa set the @OrderColumn field to null for the deleted item in the matching list before deleting it?

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

// EntityManager em
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?

+3
1

, position:-) , (Chapter). , -:

@Entity 
public class Chapter {
  @Id @GeneratedValue
  private long id;

  @ManyToOne
  private Chapter parent;

  @OneToMany(mappedBy="parent")
  @OrderColumn(name="position")
  private List<Chapter> children;
}

, : . , , Chapter. , ( , Hibernate , "generate ddl" ).

: https://github.com/hibernate/hibernate-core/tree/master/hibernate-core/src/test/java/org/hibernate/test/collection/list/

, , :-)

+2

Source: https://habr.com/ru/post/1777861/


All Articles