mybatis多表联查怎么写
时间: 2023-11-08 08:05:52 浏览: 76
MyBatis多表联查可以通过使用嵌套查询或者使用MyBatis提供的关联查询功能来实现。
1. 嵌套查询
在Mapper.xml文件中,可以使用select标签嵌套其他select标签来实现多表联查。例如:
```
<select id="getUserOrders" resultMap="userOrderMap">
select * from user
<where>
<if test="userId != null">
and user.id = #{userId}
</if>
</where>
<foreach collection="orders" item="order" open="and (" close=")" separator="or">
<if test="order.status != null">
order.status = #{order.status}
</if>
</foreach>
and exists (
select 1 from order where order.user_id = user.id
)
</select>
```
2. 关联查询
MyBatis提供了关联查询功能,可以通过定义resultMap来实现多表联查。例如:
```
<resultMap id="userOrderMap" type="User">
<id property="id" column="user_id"/>
<result property="username" column="username"/>
<collection property="orders" ofType="Order">
<id property="id" column="order_id"/>
<result property="status" column="status"/>
</collection>
</resultMap>
<select id="getUserOrders" resultMap="userOrderMap">
select * from user
left join order on user.id = order.user_id
<where>
<if test="userId != null">
and user.id = #{userId}
</if>
<foreach collection="orders" item="order" open="and (" close=")" separator="or">
<if test="order.status != null">
order.status = #{order.status}
</if>
</foreach>
</where>
</select>
```
阅读全文