當 where 中的條件使用的 if 標籤較多時,這樣的組合可能會導致錯誤。當 java 代碼按如下方法調用時:
@Test
public void select_test_where() {
User user = new User();
user.setUsername(null);
user.setSex(1);
List<User> userList = this.dynamicSqlMapper.getUsertList_where(user);
for (User u : userList ) {
System.out.println(u.toString());
}
}
如果上面例子,參數 username 為 null,將不會進行列 username 的判斷,則會直接導“WHERE AND”關鍵字多餘的錯誤 SQL。
這時可以使用 where 動態語句來解決。“where”標籤會知道如果它包含的標籤中有返回值的話,它就插入一個‘where’。此外,如果標籤返回的內容是以 AND 或OR 開頭的,則它會剔除掉。
上面例子修改為:
<select id="getUserList_whereIf" resultMap="resultMap_User" parameterType="com.zaixian.pojo.User">
SELECT u.user_id,
u.username,
u.sex,
u.birthday
FROM User u
<where>
<if test="username !=null ">
u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')
</if>
<if test="sex != null and sex != '' ">
AND u.sex = #{sex, jdbcType=INTEGER}
</if>
<if test="birthday != null ">
AND u.birthday = #{birthday, jdbcType=DATE}
</if>
</where>
</select>
where 主要是用來簡化 sql 語句中 where 條件判斷,自動地處理 AND/OR 條件。
<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
select * from t_blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</where>
</select>
where 元素的作用是會在寫入 where 元素的地方輸出一個 where,另外一個好處是你不需要考慮 where 元素裏面的條件輸出是什麼樣子的,MyBatis 會智能的幫處理,如果所有的條件都不滿足那麼 MyBatis 就會查出所有的記錄,如果輸出後是 and 開頭的,MyBatis 會把第一個and忽略,當然如果是 or 開頭的,MyBatis 也會把它忽略;此外,在 where 元素中你不需要考慮空格的問題,MyBatis 會智能的幫你加上。像上述例子中,如果 title=null, 而 content != null,那麼輸出的整個語句會是 select * from t_blog where content = #{content},而不是 select * from t_blog where and content = #{content},因為 MyBatis 會自動地把首個 and / or 給忽略。
上一篇:
mybaits if標籤語句
下一篇:
Mybatis set標籤
