<if>元素
<select id="queryEmpsByFirstNameAndAddress" resultMap="EmpMap"> select id eid, username, birthday, sex, address from tab_emp where username like concat(#{firstName}, '%') <if test="address!=null and address!='' "> and address like concat('%',#{address}, '%') </if> </select>
<choose>、<when>、<otherwise>元素
<select id="queryEmpsByFirstNameOrAddress" resultMap="EmpMap"> select id eid,username,birthday,sex,address from tab_emp where 1=1 <choose> <when test="firstName!=null and firstName!=''"> and username like concat(#{firstName}, '%') </when> <when test="address!=null and address!='' "> and address like concat('%',#{address}, '%') </when> <otherwise> and sex='男' </otherwise> </choose> </select>
<trim>、<where>、<set>元素
<select id="selectUserByTrim" resultType="com.po.MyUser" parameterType="com.po.MyUser"> select * from user <trim prefix="where" prefixOverrides="and |or"> <if test="uname !=null and uname!=''"> and uname like concat('%',#{uname},'%') </if> <if test="usex !=null and usex!=''"> and usex = #{usex} </if> </trim> </select>
<!-- 使用where元素,根据条件动态查询用户信息 --> <select id="selectUserByWhere" resultType="com.po.MyUser" parameterType="com.po.MyUser"> select * from user <where> <if test="uname !=null and uname!=''"> and uname like concat('%',#{uname},'%') </if> <if test="usex !=null and usex!=''"> and usex = #{usex} </if> </where> </select> -Dfile.encoding=UTF-8
<!-- 使用set元素,动态修改一个用户 --> <update id="updateUserBySet" parameterType="com.po.MyUser"> update user <set> <if test="uname != null">uname=#{uname},</if> <if test="usex != null">usex=#{usex}</if> </set> where uid = #{uid} </update>
<foreach>元素
<select id="selectUserByForeach" resultType="com.po.MyUser" parameterType="List"> select * from user where uid in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
<bind>元素
<!-- 使用bind元素进行模糊查询 --> <select id="selectUserByBind" resultType="com.po.MyUser" parameterType="com.po.MyUser"> <!-- bind中uname是com.po.MyUser的属性名 --> <bind name="paran_uname" value="'%' + uname + '%'"/> select * from user where uname like #{paran_uname} </select>
${}与#{} 在mybatis中,${}是直接拼接,#{}是相当于占位符