Search code examples
mybatis

MyBatis Parent Child relation


this is my class.. i kept it simple.

public void DummyClass {
   public int id;
   public List<DummyClass> dummyList;

   getter / setter...
}

Assume i have a table (DummyTable) with 2 columns id, parentid and i have a number of rows for example:

ID, PARENTID
1, 1 (the entry is parent)
2, 1 (the entry has parent with id 1)
3, 2 (the entry has parent with id 2)
4, 2 ..
5, 3 ..
6, 6 (the entry is parent)
7, 6 (the entry has parent with 6)

can someone tell me how it looks like in mybatis with annotation. i tried it like this:

public interface DummyMapper {

 final String SelectAll = "Select * from DummyTable";
 final String SelectDummy = "Select * from DummyTable where parentid = #{id}"; 

        @Select(SelectAll)
        @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "dummyList", column = "id", javaType = java.util.List.class, many = @Many(select="getDummyChildren")
        })
        public DummyClass getAllDummies();

        @Select(SelectDummy)
        public DummyClass getDummyChildren()
    }

someone has a link to a page where it is described how to do this.. or any ideas???


Solution

  • Ok I made a mistake.

    public interface DummyMapper {
    
        final String SelectAll = "Select * from DummyTable";
        final String SelectDummy = "Select * from DummyTable where parentid = #{id}"; 
    
        @Select(SelectAll)
        @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "dummyList", column = "id", javaType = java.util.List.class, many = @Many(select="getDummyChildren")
        })
        public DummyClass getAllDummies();
    
        @Select(SelectDummy)
        public List<DummyClass> getDummyChildren(@Param("id") int id);
    }
    

    First you are right. I should use a List as a return value of getDummyChildren. Then I extended getDummyChildren by @Param("id") and int id.

    Problem solved. It worked fine for me.