mybatis复杂查询
时间: 2023-06-29 17:17:34 浏览: 130
复杂的查询
Mybatis支持各种复杂查询,以下是一些示例:
1. 多条件查询
```
<select id="selectUsersByNameAndAge" parameterType="map" resultType="User">
select * from users where name = #{name} and age = #{age}
</select>
```
2. 嵌套查询
```
<select id="selectUsersWithOrders" resultMap="userWithOrders" >
select * from users
<where>
id in (
select user_id from orders
)
</where>
</select>
<resultMap id="userWithOrders" type="User">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="orders" ofType="Order">
<id property="id" column="id"/>
<result property="name" column="name"/>
</collection>
</resultMap>
```
3. 左连接查询
```
<select id="selectUsersWithOrders" resultMap="userWithOrders" >
select * from users left join orders on users.id = orders.user_id
</select>
<resultMap id="userWithOrders" type="User">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="orders" ofType="Order">
<id property="id" column="id"/>
<result property="name" column="name"/>
</collection>
</resultMap>
```
4. 动态SQL查询
```
<select id="selectUsers" parameterType="User" resultMap="user">
select * from users
<where>
<if test="id != null">
id = #{id}
</if>
<if test="name != null">
and name = #{name}
</if>
</where>
</select>
<resultMap id="user" type="User">
<result property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
```
这些只是一些示例,Mybatis还支持更多复杂的查询语句,具体使用方法可以查看官方文档。
阅读全文