Mybatis 一对多关联查询(两种方法)

实体对象里定义的集合图片

private List<CompanyImagesModel> companyImages;
 
一、
1、定义 resultMap :
<!-- 图片 -->
<resultMap id=" BaseResultMap_images" type="com.healthengine.model.CompanyModel"      extends="BaseResultMap" >
      <!-- 添加一对多的关联对象 -->
        <collection property=" companyImages" column="companyImagesId"   ofType="com.healthengine.model.CompanyImagesModel">
      <id column="question_images_id" property="companyImagesId" jdbcType="BIGINT" />
    <result column="company_id" property="companyId" jdbcType="BIGINT" />
    <result column="type" property="type" jdbcType="INTEGER" />
    <result column="image_path" property="imagePath" jdbcType="VARCHAR" />
       </collection>   
</resultMap>
2.sql查询
<!--   查看公司信息关联图片 -->
  <select id="selectModelAndImagesByPrimaryKey" resultMap=" BaseResultMap_images" parameterType="java.lang.Long" >
    select
    <include refid="Base_Column_List_images" />, img.company_images_id, img.company_id, img.image_path, img.type,
    SUBSTRING(city.merger_name,4) as city_name,city.parent_id as city_parentId
    from tb_company c
   left join tb_company_images img on c.company_id = img.company_id and img.flag=1
    LEFT JOIN tb_city city on c.city_id = city.city_id
    where c.flag=1 and  c.company_id = #{companyId,jdbcType=BIGINT}
  </select>

二、
<!--   关联图片表 -->
private List<CompanyImagesModel> picture;

1、定义 resultMap :
  <resultMap id=" BaseResultMap_leftJoin_images" type="com.healthengine.model.CompanyModel" extends="BaseResultMap" >
        <collection property="picture" column="{ companyId=company_id, picture_view_path_pre=picture_view_path_pre}" select="com.healthengine.mapper.CompanyImagesModelMapper. selectByInformationId" >
        </collection>   
  </resultMap>
2.sql查询:
<!--   根据会员Id查看公司详情 -->
  <select id="selectByMemberId" resultMap=" BaseResultMap_leftJoin_images" parameterType="java.util.Map" >
    select
    <include refid="Base_Column_List_images" />, city.name as city_name,
  #{picture_view_path_pre} as picture_view_path_pre
    FROM tb_company c 
    LEFT JOIN tb_city city on c.city_id = city.city_id
    where c.flag=1 and  c.member_id = #{memberId,jdbcType=BIGINT}
  </select>
3.圖片表sql
  <select id=" selectByInformationId" resultMap="BaseResultMap" parameterType="java.util.Map" >
    select
    <include refid="Base_Column_List_images" />, CONCAT(#{ picture_view_path_pre},img.image_path) as imagePath,
    img.image_path  as localHead_Path
    from tb_company_images img
    where img.flag=1 and  img.company_id = #{ companyId,jdbcType=BIGINT} 
  </select>
companyIdpicture_view_path_pre需要的参数需要从第一个Mapper.xml里传过来。

猜你喜欢

转载自qihaibo1989.iteye.com/blog/2354597
今日推荐