动态SQL是mybatis的强大特性之一,也是优于其他ORM框架的一个重要原因
1.<if
https://blog.csdn.net/zitian246/article/details/109170111 <if中的大坑。
当if条件符合时才会拼接sql语句,注意where 1 = 1是因为当条件成立时 where 后面不能直接根 and 需要在and前 加 true 或者 1=1
<!-- 如果 <if test="name !=null and name!=''"> name 不是null 或者 空串 进行sql 连接-->
<select id="findStudentByNameAndSex" resultType="Student">
select id,name,age,sex,height,s_address from student_tb where 1=1
<if test="name !=null and name!=''">
and name like #{name}
</if>
<if test="sex !=null and sex!=''">
and sex = #{sex}
</if>
2.<where>
很明显上个代码过于臃肿,我们可以用<where>标签替代sql语句中的where,避免where1 = 1
<where 标签作用就是 将 内部的 if进行拼接 并且 在sql中增加 where 字段 ,删除首个满足条件的where 后的and ,where标签所有的if 都不成立则 不添加where
<!--
<where 标签作用就是 将 内部的 if进行拼接 并且 在sql增加 where 字段 ,删除首个满足条件的where 后的and ,where标签所有的if 都不成立则 不添加where
-->
<select id="findStudentByNameAndSex" resultType="Student">
select id,name,age,sex,height,s_address from student_tb
<where>
<if test="name !=null and name!=''">
and name like #{name}
</if>
<if test="sex !=null and sex!=''">
and sex = #{sex}
</if>
</where>
3.<foreach>不常用
<foreach>标签是为解决mybatis接受集合参数设置的,适用场景如下:
select * from student where id in(43,44,58,59);
注意:
Parameter 'ids' not found. Available parameters are [array] 参数不能是数组
arameter 'ids' not found. Available parameters are [collection, list] 参数不能是 list集合
解决方案:既然要传一个id列表,上述清空也报错,那么将id列表用集合存储,然后将其封装成一个对象即可。
public class IdsData {
//将ids集合设置到类中
List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
@Override
public String toString() {
return "IdsData{" +
"ids=" + ids +
'}';
}
}
测试
// 获取 sqlSession mysql连接
// 默认情况 关闭自动提交-----------》开启事务
sqlSession = sqlSessionFactory.openSession(true);
// 通过sqlSession 获取IStudentDao 的实现类
IStudentDao iStudentDao = sqlSession.getMapper(IStudentDao.class);
// 根据id 列表进行集合查询
// Parameter 'ids' not found. Available parameters are [array] 参数不能是数组
// arameter 'ids' not found. Available parameters are [collection, list] 参数不能是 list
List<Integer> ids = new ArrayList<Integer>();
ids.add(2);
ids.add(4);
// ids.add(103);
IdsData idsData = new IdsData();
idsData.setIds(ids);
List<Student> studentList = iStudentDao.findAllStudentByIds(idsData);
for (Student studentItem:studentList){
System.out.println("studentItem:"+studentItem);
}
sql
<select id="findAllStudentByIds" resultType="Student">
select id,name,age,sex,height,s_address from student_tb
<where>
<if test="ids!=null and ids.size()!=0">
<foreach collection="ids" open="id in (" close=")" separator="," item="id">
#{id}
</foreach>
</if>
</where>
</select>
-
collection:为接受ids的变量名
-
open:表示以什么字段开始
-
close:表示以什么字段结束
-
item:为遍历集合中的元素
-
separator:为切分集合到的标记
4.<include>标签
有些重复次数太多的sql语句,如果每次都写,显得过于麻烦与臃肿,我们可以通过<sql>完成语句的声明,通过<include> 标签进行应用拼接
<!-- <sql>抽离重复代码 <include>进行引用拼接-->
<sql id="findAllStudentsql">
select * from student_tb
</sql>
<select id="findAllStudent" resultType="Student">
<include refid="findAllStudentsql"></include> where id >40
</select>