Mybatis+Element 通过递归实现Cascader 级

2018-07-10  本文已影响0人  超人有点忙

To iterate is human,to recurse divine.—— L. Peter Deutsch

迭代是人,递归是神。

每当我用到递归的时候都会想起来这句话,每次也会提醒自己面对问题的时候能用递归的时候绝不用迭代。希望未来的日子里,能对递归有越来越深刻的理解。

1.问题

前台显示: image.png
前台数据结构: image.png
数据库: image.png
以上是我们前台显示以及数据库表和前台的数据结构。

2.解决思路

一开始直接取完了值交给前台去构建数据结构,发现需要很多层的循环,于是才想到了运用递归,后来发现mybatis可以直接递归查询。
mapper.xml

<resultMap id="getSelf" type="com.junlai.shtic.data.biz.pojo.CascaderVo">
    <id column="ID" jdbcType="DECIMAL" property="id" />
    <result column="PARENT_ID" jdbcType="DECIMAL" property="parentId" />
    <result column="NAME" jdbcType="VARCHAR" property="label" />
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description" />
    <result column="CAS_LEVEL" jdbcType="DECIMAL" property="casLevel" />
    <result column="LIST_ORDER" jdbcType="DECIMAL" property="listOrder" />
    <result column="CAS_VALUE" jdbcType="VARCHAR" property="value" />
    <collection column="ID" property="children" select="getChildren" />
  </resultMap>

  <select id="getChildren" parameterType="java.lang.Long" resultMap="getSelf">
    select * from tbl_test_cascader where parent_id=#{parentId}
  </select>

getChildren 查询语句是递归的入口,它的参数就是parentId,第一次传入"0L"(查询根结点),然后collection中的 colum="id" 就会作为参数在次调用查询语句。
bean:

public class CascaderVo {
    private Long id;

    private Long parentId;

    private Long casLevel;

    private String label;

    private Long listOrder;

    private String value;

    public Long getListOrder() {
        return listOrder;
    }

    public void setListOrder(Long listOrder) {
        this.listOrder = listOrder;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Set<CascaderVo> getChildren() {
        return children;
    }

    public void setChildren(Set<CascaderVo> children) {
        this.children = children;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Long getCasLevel() {
        return casLevel;
    }

    public void setCasLevel(Long casLevel) {
        this.casLevel = casLevel;
    }

    private String description;

    private Set<CascaderVo> children = new HashSet<CascaderVo>();


    @Override
    public String toString() {
        return "{" +
                "value:" + value + "," +
                "label:" + label + "," +
                children + "}";


    }



}
上一篇 下一篇

猜你喜欢

热点阅读