Part 1
choose标签
在mybatis中没有else标签,如果想使用这样的效果,可以使用when otherwise这一对标签来实现if——else所实现的功能。
<select id="listProduct" resultType="Product">
SELECT * FROM product_
<where>
<choose>
<when test="name != null">
and name like concat('%',#{name},'%')
</when>
<when test="price !=null and price != 0">
and price > #{price}
</when>
<otherwise>
and id >1
</otherwise>
</choose>
</where>
</select>
上面配置信息的作用:如果name=null,同时price=null或者price=0时,查询product_中所有id>1的Product。
Part 2
foreach标签
foreach标签通常用于in的SQL语法中,下列配置信息拼接成的SQL语句是:SELECT * FROM product_ WHERE ID in(1,3,5)。意思是查找product_中ID是1、3、5的Product。
SELECT * FROM product_
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
--------------------------手动分割线---------------------------------
代码块:
List<Integer> ids = new ArrayList();
ids.add(1);
ids.add(3);
ids.add(5);
List<Product> ps = session.selectList("listProduct",ids);
其中:item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置。
collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list(我们这里传入的就是一个List)。
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array。
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可。
详见:https://www.cnblogs.com/xiemingjun/p/9800999.html
Part 3
bind标签
bind标签就像是再做一次字符串拼接,方便后续使用。比如之前学习的模糊查找使用bind标签之后的配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="c.vaefun.pojo">
<!-- 本来的模糊查询方式 -->
<!-- <select id="listProduct" resultType="Product"> -->
<!-- select * from product_ where name like concat('%',#{0},'%') -->
<!-- </select> -->
<select id="listProduct" resultType="Product">
<bind name="likename" value="'%' + name + '%'" />
select * from product_ where name like #{likename}
</select>
</mapper>
可以看出,<bindname="likename"value="'%' + name + '%'"/>这一句就是给“'%' + name + '%'”取了一个别名likename。该标签的引用方便后期的维护及代码管理。