mybaits 递归层级(父子)查询

实体:chargeItem
属性:ics_charge_item_pk //主键
ics_charge_item_name //名称
parent_charge_item_pk //上级主键

递归查询,查询出来的DTO

//返回的结果实体

ChargeItemDTO

private Long ics_charge_item_pk;   //主键
private String ics_charge_item_name ;//名称
private String parent_charge_item_pk;//上级pk
private List children = new ArrayList;//子数据

mybaits xml配置文件

//1.定义返回resultMap
<resultMap id="chargeItemSelectMap" type="com.splbilling.app.dto.IcsChargeItemSelectDTO">
        <id column="ics_charge_item_pk" jdbcType="BIGINT" property="chargeItemPk"/>
<result column="charge_item_name" jdbcType="VARCHAR" property="chargeItemName"/>
        <collection property="children" select="getSubChargeItem" column="{parentPk=ics_charge_item_pk}">collection>
resultMap>
2.定义查询父的方法
  <select id="getAllChargeItems" resultMap="chargeItemSelectMap">
        SELECT ics_charge_item_pk,charge_item_name
        FROM ics_charge_item
        WHERE parent_charge_item_pk IS NULL
    select>
3.定义查询子的方法
<select id="getSubChargeItem" resultMap="chargeItemSelectMap" parameterType="java.util.Map">
        SELECT ics_charge_item_pk,charge_item_name
        FROM ics_charge_item
        WHERE parent_charge_item_pk = #{parentPk}
select>

注:
1.定义返回的resultMap 里面的 collection 里的column的parentPk = ics_charge_item_pk
2.定义两个方法 方法一:查询最上级的对象 ;方法二:查询子对象

你可能感兴趣的:(mybatis)