Mybatis-常见问题解答

1.resultType 和 resultMap 的区别

resultType 是<select>标签的一个属性,适合简单对象(POJO、JDK 自带类型:
Integer、String、Map 等),只能自动映射,适合单表简单查询。
<select id="selectAuthor" parameterType="int" resultType="com.X.domain.Author"> 
       select author_id authorId, author_name authorName from author where author_id = #{authorId} 
</select>
resultMap 是一个可以被引用的标签,适合复杂对象,可指定映射关系,适合关联
复合查询
<resultMap id="BlogWithAuthorResultMap" type="com.X.domain.associate.BlogAndAuthor"> 
    <id column="bid" property="bid" jdbcType="INTEGER"/> 
   <result column="name" property="name" jdbcType="VARCHAR"/> 
    <!-- 联合查询,将 author 的属性映射到 ResultMap -->
   <association property="author" javaType="com.X.domain.Author">
     <id column="author_id" property="authorId"/> 
     <result column="author_name" property="authorName"/> 
   </association> 
</resultMap>

2、collection 和 association 的区别?

association:一对一
<!-- 另一种联合查询(一对一)的实现,但是这种方式有“N+1”的问题 --> 
<resultMap id="BlogWithAuthorQueryMap" type="com.X.domain.associate.BlogAndAuthor"> 
   <id column="bid" property="bid" jdbcType="INTEGER"/>
   <result column="name" property="name" jdbcType="VARCHAR"/> 
   <association property="author" javaType="com.X.domain.Author" 
      column="author_id" 
      select="selectAuthor"/> 
<!-- selectAuthor 定义在下面 -->
</resultMap>
collection:一对多、
一对多
<!-- 查询文章带评论的结果(一对多) --> 
<resultMap id="BlogWithCommentMap" type="com.X.domain.associate.BlogAndComment"
    extends="BaseResultMap" > 
     <collection property="comment" ofType="com.X.domain.Comment"> 
        <id column="comment_id" property="commentId" /> 
        <result column="content" property="content" />
     </collection> 
</resultMap>

多对多

<!-- 按作者查询文章评论的结果(多对多) --> 
<resultMap id="AuthorWithBlogMap" type="com.X.domain.associate.AuthorAndBlog" > 
      <id column="author_id" property="authorId" jdbcType="INTEGER"/> 
      <result column="author_name" property="authorName" jdbcType="VARCHAR"/> 
      <collection property="blog" ofType="com.X.domain.associate.BlogAndComment"> 
          <id column="bid" property="bid" /> 
          <result column="name" property="name" /> 
          <result column="author_id" property="authorId" /> 
          <collection property="comment" ofType="com.X.domain.Comment"> 
              <id column="comment_id" property="commentId" /> 
              <result column="content" property="content" /> 
      </collection> </collection> 
</resultMap>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值