1. 程式人生 > >MyBatis關聯查詢,一對多關聯查詢

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

log www. 相同 bubuko pre img ref sele 傳遞

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

技術分享圖片

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

  • 單步查詢,利用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標簽的方式相同

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