MyBatis动态SQL简介
1)动态sql是Mybatis强大特性之一,极大的简化我们拼装SQL的操作
2)动态SQL元素和使用JSTL或其他类似基于XML的文本处理器相似
3)MyBatis采用功能强大的基于OGNL的表达式来简化操作
If
choose{when,otherwise}
trim{where,set}
foreach
4)OGNL( Object Graph Navigation Language )对象图导航语言,这是一种强大的表达式语言,通过它可以非常方便fa的来操作对象属性。类似于EL,SqEL等
访问对象属性:
person.name
调用方法:
person.getNam()
调用静态属性/方法:
@java.lang.Math@PI
@java.util.UUID@randomUUID()
调用构造方法: new com.atguigu.bean.Person(‘admin’).name
运算符: +,-*,/,%
逻辑运算符: in,not in,>,>=,<,<=,==,!=
注意:xml中特殊符号如”,>,<等这些都需要使用转义字符
if where
1)if 用于完成简单的判断
2)where用于解决SQL语句 中where关键字以及条件中第一个and或者or的问题
<select id = "listemp" resultType="com.dahua.pojo.emp">
select id,name,pwd from emp
<where>
<if test=" id!=null">
and id = #{id}
</if>
</where>
</select>
choose(when,otherwise)
1)choose主要是用于分支判断,类似于java中的switc case,只会满足所有分支中的一个`
<select id = "listemp" resultType="com.dahua.pojo.emp">
select id,name,pwd from emp
<where>
<choows>
<when test="id!=null">
id = #{id}
</when>
<when test="name!=null">
name = #{name}
</when>
<when test="pwd!=null">
pwd = #{pwd}
</when>
</choose>
</where>
</select>
foreach
1)foreach 主要用户循环迭代
collection :要迭代的集合
item:当前从集合中迭代出的元素
open:开始字符
coloes:结束字符
separator:元素与元素之间的分隔符
index:
迭代的是List集合:index表示当前元素的下标
迭代的是Map集合:index表示的当前元素的key
<select id = "listemp" resultType="com.dahua.pojo.emp">
select id,name,pwd from emp where id in
<foeach collection="ids" item="e_id" open="(" close=")" separator=",">
#{e_id}
</foreach>
</select>
sql
1)sql标签是用于抽取可重用的sql片段,将相同的,使用频繁的SQL片段抽取出来,单独定义,方便多次应用
2)抽取SQL:
<sql id = selectSQL>
select id,name,pwd from emp
</sql>
3)引用sql
<include refid="selectSql"></include>