参考资料:1、mybatis动态SQL中的动态标签
2、MyBatis动态SQL(认真看看, 以后写SQL就爽多了)
一、mybatis的动态标签
1.1、if 标签
常常放在条件查询where后的,部分条件中。
1.1.1、 可以进行非空判断(属性test中只有一个字段)
<select id="selectByAll" resultType="com.xuecheng.domain.Tab1">
SELECT * FROM tab1
where size = 11
<if test="id != null">
and id = #{id}
</if>
</select>
可能会报错:org.apache.ibatis.reflection.ReflectionException
解决办法有两种:
1、在参数前加注解
public List<Tab1> selectByAll(@Param("id") int id);
2、在标签test属性中,用_parameter
<if test="_parameter != null">
and id = #{id}
</if>
1.1.2、 可以进行非空判断(属性test中只有两个字段)
<select id= "findActiveBlogLike"
resultType= "Blog" >
SELECT * FROM BLOG WHERE state = 'ACTIVE'
<if test= "title != null" >
AND title like #{title}
</ if >
<if test= "author != null and author.name != null" >
AND author_name like #{author.name}
</ if >
</select>
2.2、include标签<include id =" ">
有SQL语句被多次使用后,可以用该标签。其中的属性refid的值是指向<sql id=" ">
标签的属性id值
2.3、 choose 标签
choose when otherwise 标签可以帮我们实现 if else 的逻辑。一个 choose 标签至少有一个 when, 最多一个otherwise。
<select id="selectByIdOrName" resultType="xuecheng.domain.Student" parameterType="xuecheng.domain.Student">
select
*
from student
where 1=1
<choose>
<when test="studentId != null">
and student_id=#{studentId}
</when>
<when test="name != null and name != ''">
and name=#{name}
</when>
<otherwise>
and 1=2
</otherwise>
</choose>
</select>
2.4、 trim 标签
where 标签和 set 标签 都只是trim 标签的一种
2.4.1、trim标签的属性
prefix: 当 trim 元素包含有内容时, 增加 prefix 所指定的前缀
prefixOverrides: 当 trim 元素包含有内容时, 去除 prefixOverrides 指定的 前缀
suffix: 当 trim 元素包含有内容时, 增加 suffix 所指定的后缀
suffixOverrides: 当 trim 元素包含有内容时, 去除 suffixOverrides 指定的后缀
2.5、 foreach 标签
2.5.1、foreach 标签的几个属性
ollection: 必填, 集合/数组/Map的名称.
item: 变量名。 即从迭代的对象中取出的每一个值
index: 索引的属性名。 当迭代的对象为 Map 时, 该值为 Map 中的 Key.
open: 循环开头的字符串
close: 循环结束的字符串
separator: 每次循环的分隔符
2.5.2、可以批量插入
插入数据是:同一个类型的集合/数组
2.5.3、可以用在where in 后面
2.6、 bind 标签
bind 标签是通过 OGNL 表达式去定义一个上下文的变量, 这样方便我们使用。
注意:在 MySQL 中, 该函数支持多参数, 但在 Oracle 中只支持两个参数。 那么我们可以使用 bind 来让该 SQL 达到支持两个数据库的作用
<if test="name != null and name !=''">
<bind name="nameLike" value="'%'+name+'%'"/>
and name like #{nameLike}
</if>