美文网首页
MyBatis多对多的两种处理方式

MyBatis多对多的两种处理方式

作者: 又双叒叕苟了一天 | 来源:发表于2018-01-30 20:18 被阅读0次

    1.将一方作为成员加入多方

    一次性查出
    mapper.xml

    <select id="findOrder"   resultMap="odermap">
      select orders.id, orders.user_id as userId, orders.number, 
      orders.createtime as createTime,orders.note,
      user.username, user.birthday, user.sex, user.address, user.id as uid
      from orders
      left join user
      on orders.user_id=user.id 
    </select>
    
    <resultMap type="order" id="odermap">
      <id column="id" property="id"/>
      <result column="userId" property="userId"/>
      <result column="number" property="number"/>
      <result column="createtime" property="createTime"/>
      <result column="note" property="note"/>
      <association property="user" javaType="user">
        <id column="uid" property="id"/>
        <result column="username" property="username"/>
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
      </association>
    </resultMap> 
    

    2.新建类继承一方并将多方存入list
    一次性查出
    mapper.xml

    <select id="findUserAndOrders" resultMap="findUserAndOrdersMap">
      select user.*,orders.id as oid,user_id,number,createtime,note from user left join orders on user.id=orders.user_id where orders.user_id is not null   </select>
    
    <resultMap type="UserAndOrders" id="findUserAndOrdersMap">
      <id column="id" property="id"/>
      <result column="username" property="username"/>
      <result column="birthday" property="birthday"/>
      <result column="sex" property="sex"/>
      <result column="address" property="address"/>
      <collection property="orders" ofType="order">
        <id column="id" property="id"/>
        <result column="user_id" property="userId"/>
        <result column="number" property="number"/>
        <result column="createtime" property="createTime"/>
        <result column="note" property="note"/>
      </collection>
    </resultMap>
    

    分多次查出

    <select id="findUserAndOrderById" resultMap="findUserAndOrdersByIdMap">
      select distinct user.* from user left join orders on user.id=orders.user_id where orders.user_id is not null and user.id=#{id}
    </select>   
    
    <select id="findOrder" resultType="order">      
      select * from orders where user_id=#{user_id}
    </select>   
    
    <resultMap type="UserAndOrders" id="findUserAndOrdersByIdMap">
      <id column="id" property="id"/>
      <result column="username" property="username"/>
      <result column="birthday" property="birthday"/>
      <result column="sex" property="sex"/>
      <result column="address" property="address"/>
      <collection property="orders" select="findOrder" column="user_id=id" ofType="order">
      </collection>
    </resultMap>
    

    相关文章

      网友评论

          本文标题:MyBatis多对多的两种处理方式

          本文链接:https://www.haomeiwen.com/subject/wyqhzxtx.html