Note that there are some explanatory texts on larger screens.

plurals
  1. POHibernate: shuffling child nodes in a bidirectional ordered tree
    primarykey
    data
    text
    <p>I have a basic tree structure composed of a simple <code>Node</code> class, linking bidirectionally to it's single parent <em>(can be null for root nodes)</em> and an ordered list of children:</p> <pre><code>public class Node { private Integer xid; private Node parent; private List&lt;Node&gt; children; // getters and setters... } </code></pre> <p>I map this using hibernate to the following simple database table:</p> <pre><code> &gt; select * from node; xid | parent | xorder -----+--------+-------- 1 | NULL | 0 2 | 1 | 0 3 | 1 | 1 4 | 1 | 2 (4 rows) </code></pre> <p>Using the following <code>.hbm</code> hibernate mapping file:</p> <pre><code>&lt;class name="Node" table="node"&gt; &lt;id name="xid" type="int"&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;many-to-one name="parent" /&gt; &lt;list name="children" table="node"&gt; &lt;key column="parent" /&gt; &lt;list-index column="xorder" /&gt; &lt;one-to-many class="Node" /&gt; &lt;/list&gt; &lt;/class&gt; </code></pre> <p>However, when I try to shuffle elements order within one parent using the following code:</p> <pre><code>@Transactional public void testNode() { Node parent = (Node) getSession().get(Node.class, 1); Node child0 = parent.getChildren().remove(0); parent.getChildren().add(1, child0); // Swap first and second child getSession().update(parent); } </code></pre> <p>I get an exception when hibernate flush the transaction: (<code>org.hibernate.exception.ConstraintViolationException ... set parent=null, xorder=null where parent='1' and xid='2'</code>): basically the update try to set <code>xorder</code> to <code>null</code>, which is obviously forbidden by the database schema. </p> <p>I tried many combination on the hbm mapping, with no success. When I set the <code>&lt;list&gt;</code> to <code>inverse="true"</code> hibernate does not do any update, setting <code>insert="false" update="false"</code> on the <code>&lt;many-to-one&gt;</code> element does not help neither.</p> <p>I probably miss something here, either in the <code>hbm</code> mapping or in my code, my feeling is that it should be pretty obvious... Any idea?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload