嵌套查询

<resultMap type="com.foo.bean.BlogInfo" id="BlogInfo">
    <id column="blog_id" property="blogId" />
    <result column="title" property="title" />
    <association property="author" column="blog_author_id"
      javaType="com.foo.bean.Author" select="com.foo.bean.AuthorMapper.selectByPrimaryKey">
    </association>
    <collection property="posts" column="blog_id" ofType="com.foo.bean.Post"
      select="com.foo.bean.PostMapper.selectByBlogId">
    </collection>
  </resultMap>

  <select id="queryBlogInfoById" resultMap="BlogInfo" parameterType="java.math.BigDecimal">
    SELECT
    B.BLOG_ID,
    B.TITLE,
    B.AUTHOR_ID AS BLOG_AUTHOR_ID
    FROM LOULUAN.BLOG B
    where B.BLOG_ID = #{blogId,jdbcType=DECIMAL}
  </select>
此方法的缺点:要进行n+1将查询

重新定义BlogInfo的结果映射 resultMap 

<resultMap type="com.foo.bean.BlogInfo" id="BlogInfo">
    <id column="blog_id" property="blogId"/>
    <result column="title" property="title"/>
    <association property="author" column="blog_author_id" javaType="com.foo.bean.Author">
      <id column="author_id" property="authorId"/>
      <result column="user_name" property="userName"/>
      <result column="password" property="password"/>
      <result column="email" property="email"/>
      <result column="biography" property="biography"/>
    </association>
    <collection property="posts" column="blog_post_id" ofType="com.foo.bean.Post">
      <id column="post_id" property="postId"/>
      <result column="blog_id" property="blogId"/>
      <result column="create_time" property="createTime"/>
      <result column="subject" property="subject"/>
      <result column="body" property="body"/>
      <result column="draft" property="draft"/>
    </collection>

  </resultMap>
对应的sql语句如下:
<select id="queryAllBlogInfo" resultMap="BlogInfo">
      SELECT 
       B.BLOG_ID,
       B.TITLE,
       B.AUTHOR_ID AS BLOG_AUTHOR_ID,
       A.AUTHOR_ID,
       A.USER_NAME,
       A.PASSWORD,
       A.EMAIL,
       A.BIOGRAPHY,
       P.POST_ID,
       P.BLOG_ID   AS BLOG_POST_ID ,
     P.CREATE_TIME,
       P.SUBJECT,
       P.BODY,
       P.DRAFT
  FROM BLOG B
  LEFT OUTER JOIN AUTHOR A
    ON B.AUTHOR_ID = A.AUTHOR_ID
  LEFT OUTER JOIN POST P
    ON P.BLOG_ID = B.BLOG_ID
  </select>
此方法是从数据库中将数据全部查询出来,然后对返回的结果集在内存中进行组装、赋值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值