Mybatis动态标签
1. if标签
动态条件判断
<select id="findByCondition" resultType="user" parameterType="user">
select * from user where 1=1
<if test="username!=null">
and username=#{username}
</if>
</select>
2.where标签
动态where
<select id="findByCondition" resultType="com.one.mybatis.domain.User" parameterType="com.one.mybatis.domain.User">
select * from user
<where>
<if test="username!=null">
username=#{username}
</if>
</where>
</select>
3. foreach标签
动态遍历
<select id="findByIds" parameterType="list" resultType="com.one.mybatis.domain.User">
select * from user where id in
<foreach collection="list" open="(" close=")" item="id" separator=",">
#{id}
</foreach>
</select>
其中:
- collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合
- item :表示在迭代过程中每一个元素的别名
- index :表示在迭代过程中每次迭代到的位置(下标)
- open :前缀
- close :后缀
- separator :分隔符,表示迭代时每个元素之间以什么分隔
4. choose标签
<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
SELECT * from STUDENT WHERE 1=1
<where>
<choose>
<when test="Name!=null and student!='' ">
AND name LIKE CONCAT(CONCAT('%', #{student}),'%')
</when>
<when test="hobby!= null and hobby!= '' ">
AND hobby = #{hobby}
</when>
<otherwise>
AND AGE = 15
</otherwise>
</choose>
</where>
</select>
6. set标签
使用 set+if 标签修改后,如果某项为 null 则不进行更新,而是保持数据库原值。避免因为多于的,出现sql语句语法问题
<update id="updateStudent" parameterType="Object">
UPDATE STUDENT
<set>
<if test="name!=null and name!='' ">
NAME = #{name},
</if>
<if test="hobby!=null and hobby!='' ">
MAJOR = #{major},
</if>
<if test="hobby!=null and hobby!='' ">
HOBBY = #{hobby}
</if>
</set>
WHERE ID = #{id};
</update>
7.trim标签
格式化sql,属性有:
- prefix:在trim标签内sql语句加上前缀
- suffix:在trim标签内sql语句加上后缀
- prefixOverrides:指定去除多余的前缀内容,如:prefixOverrides=“AND | OR”,去除trim标签内sql语句多余的前缀"and"或者"or"。
- suffixOverrides:指定去除多余的后缀内容
<!--将where提取出来,并加上“1=1”的查询条件 -->
select * from student where 1=1
<trim suffixOverrides=",">
<if test="name != null and name != ''">
and NAME = #{name}
</if>
<if test="hobby != null and hobby != ''">
and HOBBY = #{hobby}
</if>
</trim>