根据不同条件,需要执行不同的sql命令
MyBatis中动态sql是在mapper.xml中添加逻辑判断
<select id="selByEnameOrEmpNo" resultType="emp">
select * from emp where 1=1
-- OGNL表达式,直接写key或者对象的属性,不需要添加任何特殊符号(在接口内参数前加上@param(key)注解
<if test="ename!=null and ename!=''">and ename=#{ename}</if>
<if test="empno!=null and empno!=''">and empno=#{empno}</if>
</select>
<where>
当编写where标签时,去掉内容中第一个是and,则会去掉第一个and
如果where标签内有内容,将生成where关键字,没有则不生成
<select id="selByEnameOrEmpNo" resultType="emp">
select * from emp
<where>
<if test="ename!=null and ename!=''">and ename=#{ename}</if>
<if test="empno!=null and empno!=''">and empno=#{empno}</if>
</where>
</select>
<choose><when><otherwise> ——只要有一个条件成立,其他都不执行(类似于含有break的switch case)
<select id="selByEnameOrEmpNo" resultType="emp">
select * from emp
<where>
<choose>
<when test="ename!=null and ename!=''">and ename=#{ename}</when>
<when test="empno!=null and empno!=''">and empno=#{empno}</when>
</choose>
</where>
</select>
<set> 用在SQL中set从句
去掉最后一个,
如果set标签内有内容,会生成set关键字,没有则不会生成
<update id="upd">
update emp
<set>
empno=#{empno},
<if test="ename!=null and ename!=''">ename=#{ename},</if>
</set>
<where>
empno=#{empno}
</where>
</update>
<trim>标签
prefix属性指在前面加
prefixOverrides属性指去掉前面指定部分(先删除再加前缀)
suffix属性指在后面加
suffixOverrides属性指删除后面指定部分(先删除再加后缀)
但是注意在插入前后缀时会插入一个空格
<select id="selByEnameOrEmpNo" resultType="emp">
select * from emp
<trim prefix="where" prefixOverrides="and">
and ename=#{ename}
</trim>
</select>
<bind>标签
<select id="selByEnameOrEmpNo" resultType="emp">
<bind name="sal" value="'$'+sal"></bind>
select * from emp where sal=#{sal}
</select>
其中传入的sal会按照$加上sal的值进行传递
<foreach>标签
循环参数内容,还具备在内容的前后添加内容,还具备添加分隔符功能
适用场景:in查询,批量新增
<select id="selByEnameOrEmpNo" parameterType="list" resultType="emp">
select * from emp where empno in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
sql标签
<select id="sel" resultMap="emp">
select
<include refid="mysql"></include>
from emp
</select>
<sql id="mysql">
sal,ename
</sql>
网友评论