MyBatis if标签的用法
生活随笔
收集整理的這篇文章主要介紹了
MyBatis if标签的用法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
<!--4.1.1 在WHERE條件中使用if需求:實現(xiàn)一個用戶管理高級查詢功能,根據(jù)輸入的條件去檢索用戶信息。這個功能還需要支持以下三種情況:當(dāng)只有輸入用戶名時,需要根據(jù)用戶名進行模糊查詢;當(dāng)只有輸入郵箱時,根據(jù)郵箱進行完全匹配;當(dāng)同時輸入用戶名與郵箱時用這兩個條件去查詢匹配的用戶。<if>便簽有一個必填的屬性test,test的屬性值是一個符合OGNL要求的判斷表達式,表達式的結(jié)果可以是true或者false,初次之外所有的的非0值都為true,只有0為false。且有如下規(guī)則:1.判斷條件property!=null或者property==null:適用于任何類型的字段,用于判斷屬性值是否為空2.判斷條件property!=''或者property=='':僅適用于String類型的字段,用于判斷是否為空字符串3.and和or:當(dāng)有多個判斷條件時,適用and或or進行連接,嵌套的判斷可以適用小括號分組。--><!--不能滿足需求的代碼,標(biāo)記下模糊匹配的寫法--><select id="selectByUser" resultType="tk.mybatis.simple.model.SysUser">selectid,use_name userName,user_password userPassword,user_email userEmail,user_info userInfo,head_img headImg,create_time createTimefrom sys_userwhereuser_name like concat('%',#{userName},'%') anduer_email=#{userEmail}</select><!--改進后的代碼--><select id="selectByUser" resultType="tk.mybatis.simple.model.SysUser">selectid,use_name userName,user_password userPassword,user_email userEmail,user_info userInfo,head_img headImg,create_time createTimefrom sys_userwhere1=1<if test="userName!=null and userName!=''">and user_name like concat('%',#{userName},'%')</if><if test="userEmail!=null and userEmail!=''">and user_email = #{userEmail}</if></select><!--4.1.3 在UPDATE更新列中使用if需求:只更新有變化的字段,需要注意,更新的時候不能將原來的值但沒有發(fā)生變化的字段更新為空或null。--><!--需求實現(xiàn)的代碼--><update id="updateByIdSelective">update sys_userset<if test="userName!=null and userName!=''">user_name=#{userName},</if><if test="userEmail!=null and userEmail!=''">user_email=#{userEmail},</if><if test="userInfo!=null and userInfo!=''">user_info=#{userInfo},</if><if test="headImg!=null">head_img=#{headImg},</if><if test="createTime!=null">create_time=#{createTime},</if>id=#{id}where id=#{id}</update><!--4.1.3 在INSERT動態(tài)插入列中使用if需求:在數(shù)據(jù)庫中插入數(shù)據(jù)的時候,如果某一列的參數(shù)值不為空,就使用傳入的值,如果傳入的參數(shù)為空,就使用數(shù)據(jù)庫中的默認(rèn)值(通常是空),而不使用傳入的空值。--><insert id="insert2" useGeneratedKeys="true" keyProperty="id">INSERT INTO sys_user(id,user_name,user_password,<if test="userEmail!=null and uerEmail!=''">user_email,</if>user_info,head_img,create_time)VALUES(#{id},#{userName},#{userPassword},<if test="userEmail!=null and uerEmail!=''">#{userEmail},</if>#{userInfo},#{headImg,jdbcType=BLOB},#{createTime,jdbcType=TIMESTAMP})</insert>
?
?
From《MyBatis從入門到精通》
轉(zhuǎn)載于:https://www.cnblogs.com/junjie2019/p/10570215.html
總結(jié)
以上是生活随笔為你收集整理的MyBatis if标签的用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大连海参多少钱啊?
- 下一篇: Docker镜像优化