title: Mapping a tree with MyBatis?
body: <p>I'm trying to muddle my way thru setting up a tree structure and mapping it with MyBatis. My table is defined as;</p>
  
  <pre><code>CREATE TABLE `Hierarchy` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `parentId` int(11) NULL DEFAULT NULL,
    `name` varchar(45) NOT NULL
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  </code></pre>
  
  <p>I tried to do an association in MyBatis with;</p>
  
  <pre><code>@Select(SELECT_ALL)
      @Results(value = {
              @Result(property = "id", column = "id"),
              @Result(property = "children", column = "parentId",
                      jdbcType = JdbcType.NUMERIC,
                      many = @Many(select = "selectById")),
              @Result(property = "name", column = "name")
      })
      List&lt;Hierarchy&gt; selectAll();
  </code></pre>
  
  <p>My class has;</p>
  
  <pre><code>private Integer id;
  private Integer parentId;
  private String name;
  private List&lt;Hierarchy&gt; children;
  </code></pre>
  
  <p>I pretty quickly realized this wouldn't work, since it's going to wind up associating backwards, and I get children back multiple times in the result set. So what's the answer? Do I have to iterate after I do the select and populate my children that way?</p>
  
  <p>I tried a few approaches to that, but they all seem horribly inefficient, and I'm finding it hard to handle forward-references of parent id's without iterating the list twice.</p>
  
  <p>So, has anyone pulled this off before? What's the trick?</p>