myBatis xml if、where、if-else?、foreach 心得
MyBatis 的強大特性之一便是它的動態(tài) SQL。如果你有使用 JDBC 或其它類似框架的經(jīng)驗,你就能體會到根據(jù)不同條件拼接 SQL 語句的痛苦。例如拼接時要確保不能忘記添加必要的空格,還要注意去掉列表最后一個列名的逗號。利用動態(tài) SQL 這一特性可以徹底擺脫這種痛苦。
雖然在以前使用動態(tài) SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射語句中的強大的動態(tài) SQL 語言得以改進這種情形。
動態(tài) SQL 元素和 JSTL 或基于類似 XML 的文本處理器相似。在 MyBatis 之前的版本中,有很多元素需要花時間了解。MyBatis 3 大大精簡了元素種類,現(xiàn)在只需學(xué)習(xí)原來一半的元素便可。MyBatis 采用功能強大的基于 OGNL 的表達式來淘汰其它大部分元素。
if
mapper中編寫sql,使用<if test = ' '> </if>,可以使你的接口很便捷
舉個栗子:
select * from student <if test = " id != null ">where student.id =#{id} </if>一個<if>標簽還是不夠用的,你單獨使用<if>的時候肯定還會遇到這樣的問題
select * from student where <if test = " id != null "> student.id = #{id} </if> <if test = " name != null and name != '' "> and student.name = #{name} </if>如果當你的id為空時,name前面的and是沒有必要的,運行會拋異常
或者當這兩個<if>都為空時,只剩一個空的where,還是會報錯
where
select * from student <where> <if test = " id != null ">and student.id = #{id} </if> <if test = " name != null and name != '' ">and student.name = #{name} </if> </where>- where 元素只會在至少有一個子元素的條件返回 SQL 子句的情況下才去插入WHERE子句。而且,若語句的開頭為AND或OR,where 元素也會將它們?nèi)コ?/li>
if-else =>> choose, when, otherwise
首先,在myBatis中是不支持if-else的,想要是用if-else的話,可以使用choose代替。
choose,when,otherwise有點像Java中的switch
栗子:
<select id="findActiveBlogLike"resultType="Blog">SELECT * FROM BLOG WHERE state = ‘ACTIVE’<choose><when test="title != null">AND title like #{title}</when><when test="author != null and author.name != null">AND author_name like #{author.name}</when><otherwise>AND featured = 1</otherwise></choose></select>關(guān)于mybatis的動態(tài)sql,建議查看,中文哦官方文檔
轉(zhuǎn)載于:https://www.cnblogs.com/lanaiwanqi/p/10445647.html
總結(jié)
以上是生活随笔為你收集整理的myBatis xml if、where、if-else?、foreach 心得的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序代码大全 - 小程序开发福利
- 下一篇: python stringstrip方法