Why does hibernate/jpa set @OrderColumn field to null for a removed element in a mapped list before deleting it? -
i'd map tree structure of "chapters". every chapter has reference parent, , ordered list (by "position") of subchapters. jpa 2.0, hibernate 3.5, entity "chapter" looks 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, if 1 of elements of subchapters
removed
// 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 tries execute statement
update chapter set parentchapter_id=null, position=null parentchapter_id=? , id=?
which fails because of not null
constraint of position
. if @ordercolumn(name="position")
removed, hibernate doesn't update position
(and therefore works) , removes (sub)chapter
afterwards. causes hibernate first update future orphan , then remove it?
the problem conceptual one, specially position
property :-) it's property of list itself, not list-element (chapter). so, differently:
@entity public class chapter { @id @generatedvalue private long id; @manytoone private chapter parent; @onetomany(mappedby="parent") @ordercolumn(name="position") private list<chapter> children; }
note have 2 structs here: chapter , list. point list state must persistent, it's not related struct chapter. so, deserves table (and that's hibernate try if enable "generate ddl").
you can see example test suite: https://github.com/hibernate/hibernate-core/tree/master/hibernate-core/src/test/java/org/hibernate/test/collection/list/
you'll see not using annotations, can translate :-)
Comments
Post a Comment