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

时间:2022-06-10 14:28:10

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

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标签的方式相同