動態sql
where if
where可以自動處理第一個and。
<!-- 根據id查詢用戶信息 -->
<!-- public User findUserById(int id); -->
<select id="findUserById" parameterType="user" resultType="user">
select * from user
<!-- 當有if條件成立時,where會自動拼接查詢條件,並處理第一個and -->
<include refid="where_if_if"/>
</select>
<!-- sql片段抽取 -->
<sql id="where_if_if">
<where>
<!-- 動態拼接sql查詢條件 -->
<if test="username != null and username != ''">
and username like "%"#{username}"%"
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
</where>
</sql>
foreach
向sql傳遞數組或List,mybatis使用foreach解析
在pojo中定義list屬性ids存儲多個用戶id,並添加getter/setter方法
<select id="findUserByForeach" parameterType="queryvo" resultType="user">
select * from user
<if test="ids != null and ids.size > 0 ">
<foreach collection="ids" item="id" open="where id in (" separator=", " close=")">
#{id}
</foreach>
</if>
</select>
關聯查詢
一對一:
案例:查詢所有訂單信息,關聯查詢下單用戶信息。
- 使用resultType,定義一個新的pojo,使其繼承pojoA後包含了pojoA所有字段,在pojo中添加新的字段
- 使用resultMap,定義專門的resultMap用於映射一對一查詢結果,在pojoA中加入屬性
association:表示進行關聯查詢單條記錄
property:表示關聯查詢的結果存儲在cn.itcast.mybatis.po.Orders的user屬性中
javaType:表示關聯查詢的結果類型
<id property="id" column="uid"/>:查詢結果的uid列對應關聯對象的id屬性,這裏是<id />表示uid是關聯查詢對象的唯一標識。
<result property="username" column="username"/>:查詢結果的username列對應關聯對象的username屬性。
一對多:
案例:查詢所有用戶信息,同時關聯查詢用戶的訂單信息。
用戶信息和訂單信息爲一對多關係。
- 在User類中加入List orders屬性,同時添加get/set方法
collection部分定義了用戶關聯的訂單信息。表示關聯查詢結果集
property="orders":關聯查詢的結果集存儲在User對象的上哪個屬性。
ofType="orders":指定關聯查詢的結果集中的對象類型即List中的對象類型。此處可以使用別名,也可以使用全限定名。
<id />及<result/>的意義同一對一查詢。