Where标签的使用
一般来说,使用mybatis在xml中编写sql用不到<where>标签,但如果你的sql中需要使用 'IN' 表示需要包含那些数据的时候就有用了
例如:
select * from employ where emp_id in ('543653jlkj63','b7hjh64hk77hk64','fduaiygifs5h437')
这就表示我需要查询到 employ 表中emp_id为'543653jlkj63','b7hjh64hk77hk64','fduaiygifs5h437'这三个的值
但是在代码中应该如何传递呢? 我总不能每次都要写一个for循环,然后一个一个插入到集合中再返回吧
List<String> ids = this.employeeMapper.getIds(searchModel);
//查询员工信息
List<EmployeeVO> list = new ArrayList<>();
for (String id : ids) {
//每次查到一个员工就插入到list中
EmployeeVO vo = this.employeeMapper.getByIds(ids);
list.add(vo);
}
这样子不是不行,你有没有想过mysql的性能,如果一百个人同时调这个接口,分页每次查15人,那么数据库就要承担1500次的查询,就会导致接口反应很慢
为什么不使用mybatis中的<foreach>标签呢?
我们可以这么写:
//查询分页后的员工id
List<String> ids = this.employeeMapper.getIds(params);
PageInfo page = new PageInfo<>(ids);
//查询员工信息
List<EmployeeVO> list = new ArrayList<>();
//如果查到的ids集合不为空,就查
if (CollUtil.isNotEmpty(ids)) list = this.employeeMapper.getByIds(ids);
直接将list集合给到mybatis处理
List<EmployeeVO> getByIds(@Param("ids") List<String> ids);
xml:
<select id="getByIds" resultType="com.kakarote.hrm.entity.VO.EmployeeVO">
SELECT
*
FROM employee whe
<where>
<foreach collection="ids" item="id" open=" AND whe.emp_id IN(" separator="," close=")">
#{id}
</foreach>
</where>
ORDER BY whe.sort DESC,whe.job_number ASC
</select>
foreach中各个属性的作用:
for (String id : ids) {
//每次查到一个员工就插入到list中
EmployeeVO vo = this.employeeMapper.getByIds(ids);
list.add(vo);
}
collection : 要被 foreach 标签循环解析的对象。也就是上面代码块中的ids对象
item : 集合中元素迭代时的别名,该参数为必选。 也就是上面ids中的每一次for循环拿到的 'id',这个id会被mybatis放入到一个容器中,可以理解为是 emp_id in (....) 就是放在这个括号中
open : foreach 代码的开始符号,一般是 ”(“,和 close=“)” 合用。常用在 in(),values() 时。该参数可选。这里有一个点,就是在open后面
open=" AND whe.emp_id IN(" separator="," close=")" 我们可以加上and条件作为sql拼接,这里的意思就是
SELECT
*
FROM employee whe
where
##这里的id1,2,3就表示ids中的每一个数据,且是用逗号分隔的
AND whe.emp_id IN("id1 , id2 , id3 , id4 , id5")
ORDER BY whe.sort DESC,whe.job_number ASC
同理,这个也可以放到查询字段中,使用起来还是很灵活的,在使用case when的时候也能使用
说了foreach标签,就不得不说choose标签了
<choose>
这个就相当于java中的switch语句用法
String sex = "man";
if(sex != "man"){
sout("woman");
}else{
sout("man");
}
如果使用mybatis实现
<choose>
<when test= "sex != "" and sex != null">
<choose>
<when test="sex != '男'">
AND sex= '女'
</when>
<otherwise>
AND sex= '男'
</otherwise>
</choose>
</when>
<otherwise>
AND sex!= '沃尔玛购物袋'
</otherwise>
</choose>
这样就不用再代码中写过多的判断,导致代码不简洁
<if>
主要用作非空判断,如果前端没有传递这个值,那么就不添加此条件
<if test="sex != null and sex != ''">
AND sex = #{sex}
</if>