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標簽的方式相同

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM