MyBatis中如何动态拼接Sql字符串呢?
MyBatis简介
MyBatis拥有非常强大的动态SQL处理能力下文笔者讲述动态sql的相关简介说明,如下所示:
if
<select id="findUserWithUserName" parameterType="User" resultType="User"> SELECT * FROM User WHERE state = 'ACTIVE' <if test="userName != null"> AND userName like #{userName} </if> </select>当没有传递userName信息时,则不传入此参数
choose,when,otherwise
<select id="findUserWithUserName" parameterType="User" resultType="User"> SELECT * FROM User WHERE <choose> <when test="userName != null"> AND userName like #{userName} </when> <when test="lastName != null "> AND userName like #{lastName} </when> <otherwise> </otherwise> </choose> </select>
set
<update id="updateUserInfoById" parameterType="User"> update User <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email}</if> </set> where id=#{id} </update> 同上的问题,优化后 <update id="updateUserInfoById" parameterType="User"> update User <trim prefix="where" prefixOverrides=","> <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email}</if> </set> where id=#{id} </trim> </update>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。