MyBatis多對多的兩種處理方式

weixin_34050427發表於2018-01-30

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>

相關文章