您的位置:首页 > 数据库

mybatis的动态sql语句

2017-11-11 18:08 288 查看
具体教程在mybatis的官网中有,这里只是一些小例子。

动态sql语句在test中使用的是OGNL表达式

trim

在条件前添加where,条件后删除and

<select id="findEmps" resultMap="empMap" >
select * from emp
<!--
prefix 给sql语句增加前缀
prefixOverrides 覆盖前缀
suffix 给sql语句增加后缀
suffixOverrides 覆盖后缀
-->
<trim prefix="where" suffixOverrides="and" >
<if test="lastName!=null and lastName.trim!=''">
ename like #{lastName} and
</if>
<if test="job!=null">
job = #{job} and
</if>
<if test="salary!=null and salary>100">
salary > #{salary}
</if>
</trim>
</select>

where

<!--where 增加where关键字 去除前面多余的and -->
<select id="findEmpsByWhere" resultMap="empMap" >
select * from emp
<where>
<if test="lastName!=null && lastName.trim!=''">
ename like #{lastName}
</if>
<if test="job!=null">
and job = #{job}
</if>
<if test="salary!=null and salary>100">
and salary > #{salary}
</if>
</where>
</select>

set

用于update语句

<update id="updateEmp">
update emp
<set>
<if test="lastName!=null and lastName.trim()!=''">
ename = #{lastName},
</if>
<if test="job!=null">
job = #{job},
</if>
<if test="salary>100">
salary = #{salary}
</if>
</set>
<if test="empno!=null">
where empno = #{empno}
</if>
</update>

foreach

      <sql id="empSql">
          select * from emp
      </sql>
<select id="findEmpsByEmpnos" resultMap="empMap">
<!--
原来的sql语句格式为insert into emp values(....),(...),(....)
而且这里使用了sql语句的引用include,这样重复的sql语句片段就不需要写多次
 -->
<include refid="empSql"/>
where empno in
<!--(1,2,3) collection要么写list,要么使用@Param取别名,这里就是取别名 -->
<foreach collection="empnos" item="empno" open=" ("
close=")" separator=",">
#{empno}
</foreach>
</select>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: