动态SQL
ResultMap 应用
https://blog.csdn.net/YIPUTILIU/article/details/108157923
if
内含 test 属性 接收条件式 满足则将 相关内容拼接到 sql语句中
<select id="selAll" resultType="com.one.bean.Flower">
select * from flower where 1=1
<if test="id !=null and id !=''" >
and id = #{id}
</if>
<if test="name !=null and name !=''">
and name = #{name}
</if>
</select>
where
作用:
1.若where中返回内容 以and开头 将之去除
2.若where中 有内容 则 添加where 关键字
//所有 动态SQL 拼接 都是 先去除再添加
where 常与if配合使用
<select id="selAll" resultType="com.one.bean.Flower">
select * from flower
<where>
<if test="id !=null and id !=''" >
and id = #{id}
</if>
<if test="name !=null and name !=''">
and name = #{name}
</if>
</where>
</select>
set
作用 :
1.去除所包含语句的最后一个 逗号 — “,”
2.若包含内容 则 添加set 关键字
<update id="updFlower" >
update flower
<set>
id = #{id},<!--防止下面判定全空 不生成关键字 致使语句错误 -->
<if test="name !=null and name !=''">
name = #{name},
</if>
<if test="price !=null and price !=''">
price = #{price},
</if>
</set>
where id = #{id}
</update>
choose when otherwise
作用 :
1.多个条件只想执行一个 只要有一个符合 便不再向下执行
2.if 标签是逐个判断 choose是选择一个(when)
//可类比与 switch 语句
<select id="selChoose" resultType="com.one.bean.Flower">
select * from flower
<choose>
<when test="id !=null and id !=''">
and id =#{id}
</when>
<when test="name !=null and name !=''">
and name =#{name}
</when>
<otherwise>
where production = 'shal'
</otherwise>
</choose>
</select>
上述语句的具体含义是
若 有 id 则以id为查询条件
----无 则判断name是否存在
--------是 则以name为查询条件
--------否 默认查询 产地为“ ” 的结果
bind
作用:
1.对参数重新赋值 适用于模糊查询
<select id="selBind" resultType="com.one.bean.Flower">
select * from flower
<where>
<if test="name !=null and name !=''">
<!--name 参数重新赋值 -->
<bind name="name" value="'%'+name+'%'"/>
and name = #{name}
</if>
</where>
</select>
foreach
作用:
1.可在sql语句中遍历集合对象
2.生成内容 并可以添加前后缀 支持在内容间添加分隔符
<select id="selIn" parameterType="list" resultType="com.one.bean.Flower">
<!--select * from flower where id in (1,2,3,4)-->
select * from flower where id in
<foreach collection="list" item="curr" open="(" close=")" separator=",">
#{curr}
</foreach>
</select>
属性解释
collection : 可为 list(对应参数 List )array(对应参数为数组)
参数若为Map 则 取值为传入参数的名称
index :索引
item : 循环变量 (集合中一个元素)
open:完事了 前面添什么
close: 后面添什么
separator :每次循环,以什么符号分割 ()
trim
作用:
- 可对所包含的sql语句进行 添加 去除操作
- 仅能在语句最前或最后才能操作
基本属性 :
prefix 在前面添加指定内容
prefixOverrides 去除前面指定内容
suffix 在后面添加指定内容
suffixOverrieds 去除后面指定内容
<select id="trim">
select *
<trim prefix="from" suffixOverrieds=",">
flower,
</trim>
</select>
注:总是先去除 后添加的
sql 与 include
作用
1.对于某些频繁使用的sql片段可以用SQL标签定义
需要时 用include 标签 引用 id即可
<sql id="is">
id,name,price,production
</sql>
<select id="selAll">
select
<include refid="is"></include>
from flower
</select>