MyBatis 基础知识总结 3动态sql
Posted GooReey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis 基础知识总结 3动态sql相关的知识,希望对你有一定的参考价值。
动态sql,顾名思义,就是动态的在xml中拼接sql语句。
1、where
<select id="getUserById" resultType="com.guor.bean.User">
SELECT * FROM user
<where>
<if test="position != null">
AND position like #{position}
</if>
<if test="school != null">
AND school like #{school}
</if>
</where>
</select>
注:where元素只有至少一个条件存在时,才会有where,而且,如果开头是and或者or时,where元素会自动将其舍弃。
2、trim
其实where也可以用trim来改写:
<select id="getUserById" resultType="com.guor.bean.User">
SELECT * FROM user
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="position != null">
AND position like #{position}
</if>
<if test="school != null">
AND school like #{school}
</if>
</trim>
</select>
3、set
set元素会动态前置set关键字,同时也会删除无关的逗号。
<update id="updateUserById">
update user
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="address != null">ddress=#{ddress}</if>
</set>
where id=#{id}
</update>
set也可以用trim进行改写:
<update id="updateUserById">
update user
<trim prefix="SET" suffixOverrides=",">
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="address != null">ddress=#{ddress}</if>
</trim>
where id=#{id}
</update>
4、if
<select id="getUserById" resultType="com.guor.bean.User">
SELECT * FROM user WHERE 1 = 1
<if test="position != null">
AND position like #{position}
</if>
</select>
5、choose、when、otherwish
<select id="getUsersById" resultType="com.guor.bean.User">
SELECT * FROM user WHERE 1 = 1
<choose>
<when test="position != null">
AND position like #{position}
</when>
<when test="department != null and department.name != null">
AND department_name like #{department.name}
</when>
<otherwise>
AND department_name = '公司'
</otherwise>
</choose>
</select>
6、foreach
<select id="selectUserById" resultType="com.guor.bean.User">
SELECT id,name,age,sex,address,school FROM user u
WHERE id in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。
当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
7、bind
<select id="selectUserByDept" resultType="com.guor.bean.User">
<bind name="dept" value="'%' + _department.getId() + '%'" />
SELECT * FROM user
WHERE dept_id = #{dept}
</select>
8、连接多数据库
<insert id="getCurrentTime">
<if test="_databaseId == 'oracle'">
select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual
</if>
<if test="_databaseId == 'mysql'">
select now() as Systemtime
</if>
</insert>
往期精彩内容:
以上是关于MyBatis 基础知识总结 3动态sql的主要内容,如果未能解决你的问题,请参考以下文章