mybatis 一对多查询

时间:2023-03-08 16:56:49

需求:一条数据对应多张表

ad_share_friends  主表

ad_share_image 图片表

建立实体 adShareFriends  和  adShareImage

*注意在adShareFriends 这个实体类中多添加

  private List<AdShareImage> adShareImage;

  public List<AdShareImage> getAdShareImage() {
  return adShareImage;
  }

  public void setAdShareImage(List<AdShareImage> adShareImage) {
  this.adShareImage = adShareImage;
  }

其他的按数据库字段写。

建立映射文件adShareFriendsMapper.xml 

  <resultMap id="slist" type="com.qujiali.model.AdShareFriends" >
  <id column="id_" property="id" />
  <result column="type_" property="type" />
  <result column="title_" property="title" />
  <result column="content_" property="content" />
  <result column="requirement_" property="requirement" />
  <result column="link_url" property="linkUrl" />
  <result column="reward_amount" property="rewardAmount" />
  <result column="share_company" property="shareCompany" />
  <result column="share_mode" property="shareMode" />
  <collection property="adShareImage" ofType="com.qujiali.model.AdShareImage">
  <!-- <id column="id_" property="id" /> -->
  <result column="picture_url" property="pictureUrl" />
  <result column="ad_share_id" property="adShareId" />
  </collection>
  </resultMap>
  <select id="findById" resultMap="slist" parameterType="java.lang.Long" >
  SELECT
    *
  FROM (
    select
    g.*,
    f.picture_url
    from
    ad_share_friends g
    LEFT JOIN ad_share_image f
    ON g.id_ = f.ad_share_id ) a
    WHERE a.id_ = #{id}
  </select>

其他类照常写