使用POJO的嵌套集合

时间:2013-11-16 00:07:02

标签: java mybatis

我正在尝试按照此博客here中列出的相同方法来避免N + 1问题。 我创建了5个具有多对一关系的类,如下所示:

Trunk - >分支1 - >分支2 - >分支3 - >叶子

我正在尝试构建我的XML映射器,该映射器符合但在运行时失败,并且在“com.mytest.branch1类”中没有属性“Branch2”

我已将XML映射器定义为

<mapper namespace="com.mytest.test">
  <resultMap id="resultTest" type="com.mytest.test.trunk">
     <id property="TrunkID" column="TRUNK_ID" />
     <collection property="Branch1" column="BRANCH_1_ID" javaType="ArrayList" ofType="com.mytest.test.branch1">
       <id property="branch1ID" column="BRANCH_1_ID">
       <collection property="Branch2" column="BRANCH_2" javaType="ArrayList" ofType="com.mytest.test.branch2">
         <id property="branch2ID" column="BRANCH_2_ID">
         <collection property="Branch3" column="BRANCH_3" javaType="ArrayList" ofType="com.mytest.test.branch3">
           <id property="branch3ID" column="BRANCH_3_ID">
           <result property="Value" column="Value">
         </collection>
       </collection>
     </collection>
  </resultMap>
  <select id="getAllNodes" resultMap="resultTest">
    select n.TRUNK_ID,b.BRANCH_1_ID,b.BRANCH_2_ID,b.BRANCH_3_ID,b.VALUE FROM node n join branches b on n.node_id=b.node_id
  </select>
</mapper>

Class Trunk:

public class Trunk {

private int TrunkID;
private List<Branch1> Branch1;


//getters and setters
}

Class Branch1:

public class Branch1{

private int Branch1ID;
private List<Branch2> Branch2;

//getters and setters ...
}

Class Branch2:

public class Branch2{

private int Branch2ID;
private List<Branch3> Branch3;

//getters and setters ...
}

Class Branch3:

public class Branch3{

private int Branch3ID;

//getters and setters ...
}

1 个答案:

答案 0 :(得分:0)

这里有两件事。


首先,您是否尝试编译您的代码? BranchX个类(以及Trunk)也没有List个字段的名称。 它应该是这样的:

public class Trunk {
    private int TrunkID;
    private List<Branch1> listOfBranches;   // name added
} 

因此,请修复TrunkBranch1Branch2,以便按照惯例进行操作。


第二件事是嵌套的<collection>不能这样工作。
请参阅the docs。 他们说:

  

property: 要将列结果映射到的字段或属性。如果给定名称存在匹配的JavaBeans属性,那么将使用该属性。否则,MyBatis将查找给定名称的字段。

所以,如果你写

<collection property="Branch1" column="BRANCH_1_ID" javaType="ArrayList" ofType="com.mytest.test.branch1">
   <id property="branch1ID" column="BRANCH_1_ID">
   <collection property="Branch2" column="BRANCH_2" javaType="ArrayList" ofType="com.mytest.test.branch2">
    ...
   </collection>
</collection>

外部<collection>元素是Branch1的ArrayList 它有两个内在元素:

  • <id>已正确映射到branch1ID
  • 中的Branch1字段
  • <collection>应该映射到Branch2类中的Branch1字段 - 该字段不存在。

建议的解决方法是充分命名班级中的所有List字段,即:

public class Trunk {
    private int TrunkID;
    private List<Branch1> branch1;
}

public class Branch1{
    private int Branch1ID;
    private List<Branch2> branch2;
}

希望有助于了解问题所在。

相关问题