美文网首页
resultMap递归查询(目录树)

resultMap递归查询(目录树)

作者: smallpinkp_795f | 来源:发表于2019-03-15 13:42 被阅读0次

简言:

Mybatis在处理简单的一对多时,在“一”的实体类中添加“多”的List集合,此时使用resultType的话会暴露出两个问题
1.查询出的结果,“一”实体中其他属性还好对应,就算是属性和字段名不同还可以使用别名,但是List属性的每一项又是个实体,不好对应
2.注意到List是个集合,也就是需要<select>标签多次执行查询,resultType显然不支持,resultMap中的<collection>标签就可以实现多次查询


解释<collection>标签的五个属性:

<collection column="" property="" javaType="" ofType="" select="">

column:有承上启下的作用,接收“父查询”对应字段的查询结果,向“子级查询”传递此结果
property:对应实体类中的List字段
JavaType:一般为java.util.ArrayList
ofType:子查询的输出类型
select:标记子查询,对应子查询的id,----注意只有select属性还不行,Mapper接口中还必须要声明----

前面说了这么多都是铺垫,现在开始来到目录树

步骤一:

建立目录树表:id是主键唯一编号,classify是目录名,father_catalog_id为上一级目录的id编号,或许你可能会问为什么不指向它的下一级目录,因为父目录不一定只有一个子目录啊,那这个字段你可能要放个数组,问题就复杂了 (O_O)


catalogs
步骤二:

建立实体类(省略了get,set方法):前两个属性没有什么好说的,至于为什么不添加father_catalog_id字段对应的属性是因为Mapper接口中方法返回的数据中我不想看到这个查询结果,就这么任性 : ) 重点是next属性,List<Catalog>修饰,父目录可以对应多个子目录用List没有争议吧,Catalog是因为子目录和父目录一样都是Catalog类实例

public class Catalog {
    private int id;
    private String classify;
    private List<Catalog> next;
}
步骤三:

建立Mapper接口:这里我将兴建两个方法,第一个方法是查询所有的目录树,第二个方法是根据id查询对应的目录树

public interface CatalogMapper {
//    查询所有目录树
    List<Catalog> listCatalog();
//    根基id查询对应的目录树
    Catalog getCatalog(int id);
}
步骤四:

建立Maper.xml文件:上面的铺垫说了那么多到这儿应该知道要使用resultMapper了吧,首先添加<resultMapper>标签

<resultMapper id="treeResultMapper" type="com.hgc.entity.CatalogMapper">
  <id property="id" column="id">
  <result property="classify" column="classify">
  <!--collection标签的属性可以去百度一下-->
  <collection property="next" ofType="com.hgc.entity.CatalogMapper" select="listNextCatalog" column="id" javaType="java.util.ArrayList">
</resultMapepr>

接下来编写<select>查询
先实现查询所有目录

<!--sql语句根据具体的数据库修改,查询的条件是father_catalog_id=0,也就是查询的是根目录-->
<select id="listCatalog" resultMap="treeResultMapper">
  select * from public."catalog" where father_catalog_id=0
</select>
<!--collection标签中的子查询,同样的select标签中的id也要在Mapper接口中声明-->
<select id="listNextCatalog" resultMap="treeResultMapper">
  select * from public."catalog" where father_catalog_id=#{id}
</select>

修改Mapper接口

public interface CatalogMapper {
//    查询所有目录树
    List<Catalog> listCatalog();
//    根基id查询对应的目录树
    Catalog getCatalog(int id);
//    递归查询子目录
    List<Catalog> listNextCatalog();
}
接下来实现根据id查询出目录树

在Mapper.xml中添加方法的映射

<select id="getCatalog" resultMap="treeResultMap">
  select * from public."catalog" where id=#{id}
</select>

相关文章

网友评论

      本文标题:resultMap递归查询(目录树)

      本文链接:https://www.haomeiwen.com/subject/cbtlmqtx.html