您的位置:首页 > 其它

Mybatis <where> <if> <set> <trim> <choose>标签

2017-09-16 22:24 721 查看
默认表格  student

字段名称

字段类型

大小

说明

no

CHAR

10

主键

name

VARCHAR2

8

 

sex

CHAR

2

默认值为男,只能输入男或女

<where> <if>  

<if>标签单独使用,如下

<select id="selectSudent" parameterType="String" resultType="java.util.List">
SELECT * FROM student
<if test="name!=null and name!=''">
WHERE
name like CONCAT('%',#{name},'%')
</if></select>

如果name为空或空串 则进行全部查询,效率会下降

当进行多条件下查询是,<where> <if>  可以提高查询速度 和优化查询语句

<select id="selectSudent" parameterType="String" resultType="java.util.List">
SELECT name,sex FROM student
<where>
<if test="name!=null and name!=''">
     name like CONCAT('%',#{name},'%')
</if> <if test="sex!=null and sex!=''"> AND sex=#{sex} </if> </where></select>

<set> <if>

使用

<update id="updateStudent" parameterType="com.frank.Student">
UPDATE student
<set>
<if test="name!=null and name!=''">
name= #{name},
</if>
<if test="sex!=null and sex!=''">
sex=#{sex}
</if>
</set>
WHERE no=#{no}
</update>


<trim> <if>

我个人感觉<trim>标签就是<where><set>结合 他同时具有两者的功能

<select id="selectSudent" parameterType="String" resultType="java.util.List">
SELECT name,sex FROM student
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="name!=null and name!=''">
name like CONCAT('%',#{name},'%')
</if>
<if test="sex!=null and sex!=''">
AND sex=#{sex}

4000
</if>
</trim>
</select>


<update id="updateStudent" parameterType="com.frank.Student">
UPDATE student
<trim prefix="SET" suffixOverrides=",">
<if test="name!=null and name!=''">
name= #{name},
</if>
<if test="sex!=null and sex!=''">
sex=#{sex}
</if>
</trim>
WHERE no=#{no}
</update>


<choose> 应用场景 多选一 跟switch 功能性差不多

<select id="selectSudent" parameterType="String">
SELECT name,sex FROM student
<choose>
<when test="name!=null and name!=''">
WHERE name like CONCAT('%',#{name},'%')
</when>
<when test="sex!=null and sex!=''">
WHERE sex=#{sex}
</when>
<otherwise>
//do something
</otherwise>
</choose>
</select>


<select id="selectSudent" parameterType="String">
SELECT name,sex FROM student
<where>
<choose>
<when test="name!=null and name!=''">
name like CONCAT('%',#{name},'%')
</when>
<when test="sex!=null and sex!=''">
AND sex=#{sex}//这里我不是太明白为什么要加 AND 有知道的小伙伴告诉我一下 谢谢啦  </when>
<otherwise>
//do something
</otherwise>
</choose>
</where>
</select>

还有<foreache> 标签  不过我个人还是觉得sqlSessionTemplate进行批处理比较好一点  各位觉得呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis 标签 if where