動態sql修改、list引數查詢、
阿新 • • 發佈:2022-03-07
<update id="updateUser" parameterType="com.dy.entity.User"> update user <set> <if test="name != null">name = #{name},</if> <if test="password != null">password = #{password},</if> <if test="age != null">age = #{age},</if> </set> <where> <if test="id != null"> id = #{id} </if> and deleteFlag = 0; </where> </update>
2foreach: 你有for, 我有foreach, 不要以為就你才屌!
java中有for, 可通過for迴圈, 同樣, mybatis中有foreach, 可通過它實現迴圈,迴圈的物件當然主要是java容器和陣列。
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
3 choose: 我選擇了你,你選擇了我!
Java中有switch, mybatis有choose。
<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>
4 動態SQL解析原理
我們在使用mybatis的時候,會在xml中編寫sql語句。比如這段動態sql程式碼:
<update id="update" parameterType="org.format.dynamicproxy.mybatis.bean.User"> UPDATE users <trim prefix="SET" prefixOverrides=","> <if test="name != null and name != ''"> name = #{name} </if> <if test="age != null and age != ''"> , age = #{age} </if> <if test="birthday != null and birthday != ''"> , birthday = #{birthday} </if> </trim> where id = ${id} </update>
6 where, 有了我,SQL語句拼接條件神馬的都是浮雲!
咱們通過where改造一下上面的例子:
<select id="findUserById" resultType="user"> select * from user <where> <if test="id != null"> id=#{id} </if> and deleteFlag=0; </where> </select>