MyBatis关联查询,一对多关联查询

实体关系图,一个国家对应多个城市

一对多关联查询可用三种方式实现:

  • 单步查询,利用collection标签为级联属性赋值;
  • 分步查询:
    • 利用association标签进行分步查询;
    • 利用collection标签进行分步查询

单步查询

利用collection标签实现一对多单步关联查询:

  • 指定进行关联查询的Java Bean字段,即collection标签的 property 属性;
  • 指定集合中的Java Bean类型,即collection标签的 ofType属性;

 实体类

public class CountryPlus {
    Long id;
    String name;
    Date lastUpdate;
    List<City> cityList;
}

 

public class City {
    Long id;
    String name;
    Long countryId;
    Date lastUpdate;
}

 

查询标签

复制代码

    <select id="selectCountryPlusById" resultMap="countryPlusResultMap">
        select country.country_id as country_id,
                country,
                country.last_update as last_update,
                city_id,
                city,
                city.country_id as city_country_id,
                city.last_update as city_last_update
        from country left join city on  country.country_id = city.country_id
        where country.country_id=#{id}
    </select>

复制代码

 

resultMap

复制代码

    <resultMap id="countryPlusResultMap" type="canger.study.chapter04.bean.CountryPlus">
        <id column="country_id" property="id"/>
        <result column="country" property="name"/>
        <result column="last_update" property="lastUpdate"/>
        <collection property="cityList" ofType="canger.study.chapter04.bean.City">
            <id column="city_id" property="id"/>
            <result column="city" property="name"/>
            <result column="city_country_id" property="countryId"/>
            <result column="city_last_update" property="lastUpdate"/>
        </collection>
    </resultMap>

复制代码

 分步查询

利用collection标签进行分步查询

  • 指定collection标签的 property 属性;
  • 通过select属性指定下一步查询使用的 statement id;
  • 通过column属性向下一步查询传递参数,传递多个参数的方法见MyBatis关联查询,一对一关联查询中的分步查询;

select标签

    <select id="selectCountryPlusByIdStep" resultMap="countryPlusResultMapStep">
        select *
        from country
        where country_id=#{id}
    </select>

resultMap标签

复制代码

    <resultMap id="countryPlusResultMapStep" type="canger.study.chapter04.bean.CountryPlus">
        <id column="country_id" property="id"/>
        <result column="country" property="name"/>
        <result column="last_update" property="lastUpdate"/>
        <collection property="cityList"
                     select="canger.study.chapter04.mapper.CityMapper.selectCityByCountryId"
                     column="country_id">
        </collection>
    </resultMap>

复制代码

利用association标签进行分步查询

  和使用collection标签的方式相同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值