zoukankan      html  css  js  c++  java
  • MyBatis 一对多查询

     

    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

    复制代码
  • 相关阅读:
    有趣的面试题 11 单向链表
    CLR via C# 读书笔记 13 前台线程和后台线程
    c# 使用 new 操作符构造新对象中做了一些什么 (简单版)
    CLR via C# 读书笔记 11 何时使用线程或者线程池
    CLR via C# 读书笔记 31 一种单实例应用程序的实现(信号量)
    延时加载lazyload
    [评论]为什么中国的程序员技术偏低
    关于陈列设计和一些细节的体验
    滚动
    JavaScript 的 parseInt 取整
  • 原文地址:https://www.cnblogs.com/roxy/p/7665664.html
Copyright © 2011-2022 走看看