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了
当时我就卡在这里,一直找不到问题。
总结一下
想想也没啥好总结的,主要是为了记录下,防止下次还出现这样的问题学编程要是不会总结,那跟咸鱼又有什么区别~
相关文章推荐
- 单链表基本操作的实现
- COJ 1687:Set
- Oracle的rownum原理和使用
- pymysql写入数据失败
- Android Service自启动注意事项分析
- CloudTest 事务监控:千呼万唤始出来
- 关于分布式事务、两阶段提交、一阶段提交、Best Efforts 1PC模式和事务补偿机制的研究
- 关于分布式事务、两阶段提交、一阶段提交、Best Efforts 1PC模式和事务补偿机制的研究
- 关于分布式事务、两阶段提交、一阶段提交、Best Efforts 1PC模式和事务补偿机制的研究
- 关于分布式事务、两阶段提交、一阶段提交、Best Efforts 1PC模式和事务补偿机制的研究
- 关于分布式事务、两阶段提交、一阶段提交、Best Efforts 1PC模式和事务补偿机制的研究
- java调用JNI总结
- 服务器时间的转换和截取
- 生活之为何要十跪父母亲
- JMS入门(五)--消息头
- 随机抽奖
- redis学习笔记
- 洪涝有源淹没算法及淹没结果分析
- python之import机制
- SVM初探