if标签
-
parameterType类型是pojo
-
test中的属性必须是pojo中的属性并且严格区分大小写(sql语句中不区分大小写)
-
使用NGNL语言进行查询
-
标准的判断非空形式为<if test="stuName != null and stunName != ''">,这里的stuName是某一个pojo中普通属性(不是list类型,如果是list类型就使用!=null和lst.size() > 0)
where标签
可以将if标签放置在where标签中,这样当第一个查询条件中有and时会自动去除第一个and
foreach
迭代的类型有:数组,对象数组、集合、属性(比如一个类中有List<Integer> ids属性)
迭代属性
public class User{
private List<Integer> ids;
...
}
<select id="queryUserWithObjectProperty" parameterType="user" resultType="user">
<where>
<if test="ids != null and ids.size > 0">
<foreach collection="ids" open="and id in (", close=")" item="id">
#{id}
</foreach>
</if>
</where>
</select>
上面的例子是遍历数组:
- 比如我们根据id使用in来查询,sql语句类似于select * from user where id in ('11', '22', '33');这里的11,22,33其实就是放置在一个list中,我们要遍历的就是这个list
- foreach的collection属性就是放置我们的list名称(这里的list是一个pojo中的属性),也就是该select标签的parameterType是一个pojo。
- open是遍历的前面一部分内容,由于我们遍历的只是list中的值,那么
and ID in(
这一部分就是遍历前面的内容 - close属性填写是遍历部分后面的内容
- item相当于是list中的每一个值
迭代数组
parameterType中如果是基本类型可以直接写类型形式,比如int类型的数组可以写int[],也可以统一写成array。
<select id="queryUserWithArray" parameterType="int[]" resultType="user">
select * from user
<where>
<if test="array != null and array.length > 0">
<foreach collection="array" open="and id in (", close=")" item="id">
#{id}
</foreach>
</if>
</where>
</select>
其实迭代数组与迭代属性是类似的,只是有一点不同,那就是迭代数组的时候名称必须是使用array。比如上面的例子,collection属性中就是使用的array,这个与你穿的参数名称没有关系,就是这样规定的而已。
迭代list
<select id="queryUserWithList" parameterType="list" resultType="user">
select * from user
<where>
<if test="list != null and list.size > 0">
<foreach collection="list" open="and id in (", close=")" item="id">
#{id}
</foreach>
</if>
</where>
</select>
迭代list的时候parameterType必须是list,collecton属性值必须是list。
迭代对象数组
User user1 = new User();
User user2 = new User();
User user3 = new User();
user1.setId(1);
user1.setId(2);
user1.setId(3);
User[] users = {user1, user2, user3};
<select id="queryUserWithObjectArray" parameterType="Object[]" resultType="user">
select * from user
<where>
<if test="array != null and array.length > 0">
<foreach collection="array" open="and id in (", close=")" item="user">
#{user.id}
</foreach>
</if>
</where>
</select>
- 上面说如果是使用基本类型的数组的话可以直接按照原来类型的数组来作为parameterType属性的值,比如如果是int类型参数的数组,那么可以使用parameterType=“int[]”,但是对于对象数组来说不能这样写,也不能直接写成array,而是需要写成parameterType=“Object[]”, 然后collection属性值是array。
- collection属性值是array,item的属性值是一个对象,比如这里我使用的是user对象数组,那么item应该是一个user对象
- 调用的时候使用的是#{user.id},这里是使用的user对象里面的属性
sql标签
有很多的sql是重复的,可以将其抽取出来放置在sql标签中,然后在需要使用的地方引用。
<sql id="commonSql">
select * from user
<where>
<if test="array != null and array.length > 0">
<foreach collection="array" open="and id in (", close=")" item="user">
#{user.id}
</foreach>
</if>
</where>
</sql>
<select id="queryUserWithObjectArray" parameterType="Object[]" resultType="user">
<include refid="commonSql"></include>
</select>
如果sql标签是在例外一个mapper文件中,但是在当前的mapper文件中想要引用,那么refid属性的值就需要加上namespace命名空间。