本篇文章介绍MyBatis较为常用的两个知识点,一个是动态语句,一个是${}参数。
动态语句:
提供where、set、if、trim、choose等标签,我们以if为例,加入我们想通过条件组合的形式查询学生数据,如单独查姓名、性别、年龄,也可以两两组合,也可以三个组合:
List<Student> searchByCondition3(Student stu);
<select id="searchByCondition3" resultType="entity.Student">
select * from student where 1=1
<if test="name!=null and name!=''">
and name=#{name}
</if>
<if test="gender!=null and gender!=''">
and gender=#{gender}
</if>
<if test="age!=null and age!=0">
and age=#{age}
</if>
</select>
测试类:
Student stu = new Student();
//stu.setName("小红");
// stu.setGender("女");
stu.setAge(20);
List<Student> list = studentDao.searchByCondition3(stu);
for (Student s : list) {
System.out.println(s.getName());
}
#{}和${}:
#{}传参的形式,我们一直在使用,它会判断Java中的类型,如果是字符串,为注入到SQL中的变量自动添加SQL语法中所要求的单引号:’’,但是在有些场景下,它的这一特性,反而解决不了不了问题,如:
List<Student> searchLike(@Param("name") String name);
<select id="searchLike" resultType="entity.Student">
select * from student where name like '%#{name}%'
</select>
如果此时还用#{},测试时候传入“小"字符串,则会出现SQL效果如下,是不符合SQL语法的:
select * from student where name like '%'小'%'
改用${}:
<select id="searchLike" resultType="entity.Student">
select * from student where name like '%${name}%'
</select>
则生成正常的SQL如下:
select * from student where name like '%小%'