原因:MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么 的痛苦,确保不能忘了空格或在列表的最后省略逗号。
动态查询
1.where
当where标签中有内容时,会动态的添加 where关键字。如果 where后面以and / or开头,会删除这些关键字
例:<where>
<if test=''>
SQL语句:
<select id="findStudents" parameterType="Student" resultType="Student">
select
id,no,name,gender
from student
<where>
<if test="no!=null">
no = #{no}
</if>
<if test="name!=null">
and name = #{name}
</if>
<if test="gender!=null">
and gender = #{gender}
</if>
</where>
</select>
测试:
public class TestStudent1 {
@Test
public void finds(){
SqlSession sqlSession = MyBatisUtil.getSqlSeesion();
StudentDao1 studentDao1 = sqlSession.getMapper(StudentDao1.class);
/*
有三个查询条件,把查询条件封装在学生对象中
第一次点击菜单查询 学号,姓名,性别都为空
*/
Student student = new Student();
/*student.setNo(101);
student.setGender("男");*/
student.setName("李四");
List<Student> students = studentDao1.findStudents(student);
System.out.println(students);
sqlSession.close();
}
}
2. trim
trim prefix="添加指定的前缀" prefixOverrides="覆盖指定的前缀"
<select id="findStudents" parameterType="Student" resultType="Student" >
select
id,no,name,gender
from student
<trim prefix="where" prefixOverrides="and|or">
<choose>
<when test="name!=null">
name = #{name}
</when>
<otherwise>
name = '张三'
</otherwise>
</choose>
and no <![CDATA[ < ]]> 105
</trim>
</select>
3. set标签
set元素可以把最后一个逗号去掉。 set标签中如果有成立的,就会添加set标签如果以逗号结尾,就会删除结尾的逗号
<update id="updateStudent" parameterType="Student">
update student
<trim prefix="set" suffixOverrides=",">
<if test="no!=null">
no=#{no},
</if>
<if test="name!=null">
name=#{name},
</if>
<if test="gender!=null">
gender=#{gender},
</if>
<if test="grade!=null">
gradeid=#{grade.id}
</if>
</trim>
where id = #{id}
</update>
4. foreach
foreach 元素的属性主要有 item,index,collection,open,separator,close。
- item 表示集合中每一个元素进行迭代时的别名
- index 指定一个名字,用于 表示在迭代过程中,每次迭代到的位置
- open 表示该语句以什么开始
- separator 表示在每次进行迭代之间以什么符号作为分隔符
- close 表示以什么结束
在使用 foreach 的时候最关键的也是最容易出错的就是 collection 属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的。
如果传入的是单参数且参数类型是一个 List 的时候,collection 属 性值为 list
如果传入的是单参数且参数类型是一个 array 数组的时候, collection 的属性值为 array
<select id="findStudents1" resultType="Student">
select
id,no,name,gender
from student where no in
<foreach collection="list" item="no" open="(" separator="," close=")">
#{no}
</foreach>
</select>
<select id="findStudents2" resultType="Student">
select
id,no,name,gender
from student where no in
<foreach collection="array" item="no" open="(" separator="," close=")">
#{no}
</foreach>
</select>
特殊符号转义
转义字符 | 特殊字符 | 符合说明 |
< | < | 小于 |
> | > | 大于 |
' | ‘ | 单引号 |
" | "" | 双引号 |
& | & | and |