MyBatis關聯查詢,一對多關聯查詢

------------------------------------抄筆記------------------------------------

MyBatis關聯查詢,一對多關聯查詢

實體關係圖,一個國家對應多個城市

在這裏插入圖片描述

一對多關聯查詢可用三種方式實現:

單步查詢,利用collection標籤爲級聯屬性賦值;
分步查詢:
利用association標籤進行分步查詢;
利用collection標籤進行分步查詢

1.單步查詢

利用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>

2.分步查詢

利用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標籤的方式相同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章