Mybatis动态 SQL

tech2024-11-06  23

if
<select id="findByCondition" parameterType="user" resultType="user"> select * from user <where> <if test="id!=0"> and id=#{id} </if> <if test="username!=null"> and username=#{username} </if> </where> </select>
foreach
<select id="findByIds" parameterType="list" resultType="user"> select * from user <where> <foreach collection="list" open="id in(" close=")" item="id" separator=","> #{id} </foreach> </where> </select>

foreach标签的属性含义如下:

collection:代表要遍历的集合元素,注意编写时不要写#{}open:代表语句的开始部分close:代表结束部分item:代表遍历集合的每个元素,生成的变量名sperator:代表分隔符
choose
<select id="queryUserById" parameterType="user" resultType="user"> select * from user <where> <choose> <when test="id==1"> and username="zhangsan" </when> <when test="id==2"> and username="lisi" </when> <otherwise> and username="wangwu" </otherwise> </choose> </where> </select>

choose相当于java中的switch,when相当于其中的case,otherwise相当于其中的的default.

set

注意每一个if标签后的逗号!!!

<update id="updateUser" parameterType="user"> update user <set> <if test="username!=null"> username=#{username}, </if> <if test="password!=null"> password=#{password}, </if> <if test="birthday!=null"> birthday=#{birthday}, </if> </set> <where> id=#{id} </where> </update>
最新回复(0)