码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatis 一对多查询

时间:2017-10-14 12:25:33      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:class   pojo   cti   .post   collect   color   span   通过   poj   

 

MyBatis一对多查询:

  有联合查询和嵌套查询

  联合查询是几个表联合查询,只查询一次,通过在resultMap中配置collection节点配置一对多的类即可;

  嵌套查询是先查一个表,根据这个表中的结果的外键id,再去另一个表中查询数据,也是通过collection,但是另一个表的查询通过selec节点配置

  1.1 联合查询

技术分享

    <resultMap type="Post" id="postResultMap">
        <id column="id" property="id"/>
        <collection column="id" property="commentList" javaType="ArrayList" ofType="Comment">
        
        </collection>
    </resultMap>
    
    <select id="selectPostById" parameterType="int" resultMap="postResultMap">    
        select * from post left join comment on post.id = comment.post_id where post.id = #{id}
    </select>


console:

  ==> Preparing: select * from post left join comment on post.id = comment.post_id where post.id = ?   ==> Parameters: 1(Integer)   <== Total: 3   com.roxy.mybatis.pojo.Post@4abdb505
技术分享

  1.2 嵌套查询

技术分享
    <resultMap type="Post" id="postResultMap">
        <id column="id" property="id"/>
        <collection column="id" property="commentList" javaType="ArrayList" ofType="Comment"
        select="com.roxy.mybatis.mapper.CommentMapper.selectCommentByPostId">
     </collection>
    </resultMap>
    
    <select id="selectPostById" parameterType="int" resultMap="postResultMap">
        select * from post where id = #{id}
    </select>

  
   <select id="selectCommentByPostId" parameterType="int" resultMap="commentResultMap">
        select * from comment where post_id = #{postId}
    </select>


console:
  ==>  Preparing: select * from post where id = ?
  ==> Parameters: 1(Integer)
  <==      Total: 1
  
  ==>  Preparing: select * from comment where post_id = ?
  ==> Parameters: 1(Integer)
  <==      Total: 3

  com.roxy.mybatis.pojo.Post$$EnhancerByCGLIB$$ac65a46b@2d127a61

技术分享

MyBatis 一对多查询

标签:class   pojo   cti   .post   collect   color   span   通过   poj   

原文地址:http://www.cnblogs.com/roxy/p/7665664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!