時間:2024-02-05 12:47作者:下載吧人氣:16
1.什么是動態(tài)SQL
傳統(tǒng)的使用JDBC的方法,相信大家在組合復(fù)雜的的SQL語句的時候,需要去拼接,稍不注意哪怕少了個空格,都會導(dǎo)致錯誤。Mybatis的動態(tài)SQL功能正是為了解決這種問題, 其通過 if, choose, when, otherwise, trim, where, set, foreach標簽,可組合成非常靈活的SQL語句,從而提高開發(fā)人員的效率。
SQL語句不固定, 會根據(jù)前臺用戶的操作而進行變化的SQL語句, 可以被稱之為動態(tài)SQL. 在MyBatis中, 提供了一組標簽, 用于方便的實現(xiàn)動態(tài)SQL, 不需要通過java代碼拼接字符串了.
###2.動態(tài)sql中的標簽
1. <if>
用于條件判斷, test屬性表示判斷結(jié)果, 要求是一個boolean.
2.<where>
用于維護where子句, 通常配合一起使用. 如下功能:
a)當沒有條件時, 不會創(chuàng)建WHERE關(guān)鍵字;
b)當有條件時, 會自動生成WHERE關(guān)鍵字;
c)會自動去掉第一個條件的and/or關(guān)鍵字.
3.<choose><when><otherwise>
功能類似于switch…case…default, 表示多分支判斷, 只能成立一個條件
<mapper namespace="com.bjsxt.mapper.UserMapper"> <select id="selByCondition" resultType="user"> select * from tb_user <where> <if test="id != null"> and id=#{id} </if> <if test="username != null and username != ''"> and username=#{username} </if> <if test="age != null"> and age <> #{age} </if> <choose> <when test="birthday != null and birthday != ''"> and birthday = #{birthday} </when> <otherwise> and birthday is null </otherwise> </choose> </where> </select> </mapper>
網(wǎng)友評論