<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.et.mybatis.dyncsql.xml.DyncSqlMapper">
<!-- 使用if -->
<select id="queryArcticleByCon" parameterType="map" resultType="map">
select * from arcticle where 1=1
<!-- 根据传入的参数是否满足条件 来决定是否追加if中的sql -->
<if test="title!=null">
and title=#{title}
</if>
<if test="content!=null">
and content=#{content}
</if>
<if test="userid!=null">
and userid=#{userid}
</if>
</select>
<!-- 使用where -->
<select id="queryArcticleByConUseWhere" parameterType="map" resultType="map">
select * from arcticle
<!--
where标签会自动 给条件添加where关键字
当追加的第一条sql出现了 and关键字 会自动去掉一个and
非第一条sql 不会去掉其中的and
-->
<where>
<if test="title!=null">
and title=#{title}
</if>
<if test="content!=null">
and content=#{content}
</if>
<if test="userid!=null">
and userid=#{userid}
</if>
</where>
</select>
<!-- 使用choose when -->
<select id="queryArcticleByConUseCaseWhen" parameterType="map" resultType="map">
select * from arcticle
<!--
mybatis未提供 ifelse的用法
使用 choose when替代
只能满足when条件中的任意一个条件
-->
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<otherwise>
content=#{content}
</otherwise>
</choose>
</where>
</select>
<!-- 使用set -->
<update id="updateArcticle">
update arcticle
<!-- 给sql语句添加关键字 set
并且去掉最后一个,
-->
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="content!=null">
content=#{content},
</if>
<if test="userid!=null">
userid=#{userid},
</if>
</set>
where id=6;
</update>
<!-- 使用set -->
<update id="updateArcticleByTrim">
update arcticle
<!--
可以使用trim来实现set和where的功能
prefix就是在追加的sql语句之前添加内容
prefixOverrides 就是在sql语句之前去掉某些内容
suffix 就在在sql语句末尾 添加内容
suffixOverrides 就是在sql语句末尾去掉某些内容
set的实现 prefix="set" suffixOverrides=","
where的实现 prefix="where" prefixOverrides="AND"
-->
<trim prefix="set" suffixOverrides=",">
<if test="title!=null">
title=#{title},
</if>
<if test="content!=null">
content=#{content},
</if>
<if test="userid!=null">
userid=#{userid},
</if>
</trim>
where id=6;
</update>
<select id="queryByForEach">
select * from arcticle
<where>
<!--
collection表示传入的集合的key值
item表示每次循环后 添加的变量 该变量存储的是当前被循环的list中的值
open表示循环开始前追加的前缀
open表示循环结束后追加的后缀
separator表示添加元素后 追加的分隔符
List<String> idList=new ArrayList<String>();
idList.add(3,4,5);
for(String varId:idList){
}
where id in(3,4,5,6)
-->
<foreach collection="idList" item="varId"
open="id in(" close=")" separator=","
>
#{varId}
</foreach>
</where>
</select>
</mapper>
mybatis动态sql
最新推荐文章于 2023-05-22 08:15:55 发布