java代码生成:
实体类: public class CompanyInfo { private Long id; /* * 父级企业编码 * */ private String parentCode; /** * 子节点 */ private List<CompanyInfo> childList; } service中: public static List<CompanyInfo> listToTree(List<CompanyInfo> list) { //用递归找子。 List<CompanyInfo> treeList = new ArrayList<CompanyInfo>(); for (CompanyInfo tree : list) { //如果根目录的parentId为-1 if (tree.getParentId() == -1 ) { treeList.add(findChildren(tree, list)); } } return treeList; } private static CompanyInfo findChildren(CompanyInfo tree, List<CompanyInfo> list) { for (CompanyInfo node : list) { if (node.getParentId().longValue() == tree.getId().longValue()) { if (tree.getChildren() == null) { tree.setChildren(new ArrayList<CompanyInfo>()); } tree.getChildren().add(findChildren(node, list)); } } return tree; }mybatis生成:
实体类 public class CompanyInfo { private Long id; /* * 父级企业编码 * */ private String parentCode; /** * 子节点 */ private List<CompanyInfo> childList; } mapper.java中: List<CompanyInfo> getCompanyTreeByGroupCode(@Param("parentCode") String parentCode); mapper.xml <resultMap id="BaseTreeResultMap" type="com.xxx.CompanyInfo"> <id column="id_" property="id" jdbcType="BIGINT" /> <result column="parent_code" property="parentCode" jdbcType="VARCHAR" /> <collection column="company_code" property="childList" javaType="java.util.ArrayList" ofType="com.xxx.CompanyInfo" select="getNextNodeTree"/> </resultMap> <select id="getNextNodeTree" resultMap="BaseTreeResultMap"> SELECT * FROM com_company WHERE parent_code = #{parentCode} AND enable_ = 1 </select> <select id="getCompanyTreeByGroupCode" resultMap="BaseTreeResultMap"> SELECT * FROM com_company WHERE company_code = #{parentCode} AND enable_ = 1 </select>