Mybatis的一对多查询

例如:一个国家对应多个地区,一个地区对应多个城市,在查询国家的时候把地区及城市一并查出

//实体类,简单写一下
class Country{

    String id;
    String name;
    List<Area> areas;
    
}

class Area{

    String id;
    String name;
    String countryId;
    List<City> citys;
}

class City{

    String id;
    String name;
    String areaId;
    
}

XML配置

注意select标签的 resultType和resultMap别用错

 <!-- 国家与地区的1对多映射 --> 
<resultMap id="CountryResultMap" type="com.xxx.Country" >
   <id column="id" property="id" />
   <result column="name" property="name"  />
   <collection property="areas" ofType="com.xxx.Area" 
               select="getAreas" column="id">
   </collection>
</resultMap>

 <!-- 地区与城市的1对多映射 --> 
<resultMap id="AreaResultMap" type="com.xxx.Area" >
   <id column="id" property="id" />
   <id column="country_id" property="countryId" />
   <result column="name" property="name"  />
   <collection property="citys" ofType="com.xxx.City" 
               select="getCitys" column="id">
   </collection>
</resultMap>

<select id="selectCountryById" parameterType="java.lang.String"     
      resultMap="CountryResultMap">
  select 
        c.id,c.name
        from country c
        where  c.id = #{id}
</select>
<select id="getAreas" parameterType="java.lang.String"     
      resultMap="AreaResultMap">
  select 
        a.id,a.name,a.country_id
        from area a
        where  a.country_id = #{id}
</select>
<select id="getCitys" parameterType="java.lang.String"     
      resultType="com.xxx.City">
  select 
        t.id,t.name,t.area_id as areaId
        from city t
        where  t.area_id = #{id}
</select>

猜你喜欢

转载自blog.csdn.net/xiahuale/article/details/84244260