您的位置:首页 > 其它

Mybatis 嵌套查询(高级结果映射)

2016-03-09 10:46 573 查看

需求说明

有三张表,省级表,市级表,区级表。

需要做一个关联嵌套查询

public class Province {//省份
private String code;
private String name;
private List<City> cities;
}


public class City {//城市
private String code;
private String name;
private List<Area> district;
}


public class Area {//区域
private String code;
private String name;
}


这里我省略了实体类的构造方法。通过实体类是可以看出表结构,和表之间的关联关系的。

//这是在MybatisXml文件中做的关联映射
<resultMap type="com.ea.bic.model.vo.Area" id="AreaMap">//区
<id column="id" property="code"/>
<result column="areaname" property="name"/>
</resultMap>

<resultMap type="com.ea.bic.model.vo.City" id="cityMap">//市
<id column="cid" property="code"/>
<result column="citname" property="name"/>
<collection property="district" ofType="com.ea.bic.model.vo.Area" resultMap="AreaMap" />
</resultMap>

<resultMap type="com.ea.bic.model.vo.Province"  id="ProvinceMap">//省
<id column="pid" property="code" />
<result column="proname" property="name" />
<collection property="cities" ofType="com.ea.bic.model.vo.City" resultMap="cityMap" />
<!--两种方式的不同之处在这里,自己分析就可以知道-->
</resultMap>


接下来就是SQL

<select id="findAreaList"  resultMap="ProvinceMap">
t_province.id pid,
t_province.areaName proname,
t_city.id cid,
t_city.areaName citname,
t_district.id id,
t_district.areaName areaname
FROM
t_area t_district
INNER JOIN t_area t_city ON t_district.parent_id = t_city.id
INNER JOIN t_area t_province ON t_city.parent_id = t_province.id
</select>


列名的别名 一定要与配置的映射一致,不然你懂得。

后来为了这个查询的效率更高一点,我把三张表整成了一张视图。

然后SQL就成了这样

<select id="findAreaList"  resultMap="ProvinceMap">
select
t.id id,
t.areaName areaname,
t.cid cid,
t.citName citname,
t.pid pid,
t.proname from t_area_full t
</select>


数据的接收就用List来接收就OK了

当时我就卡在这里,一直找不到问题。

总结一下

想想也没啥好总结的,主要是为了记录下,防止下次还出现这样的问题

学编程要是不会总结,那跟咸鱼又有什么区别~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: