1. Mybatis 动态SQL
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,也就是可以根据用户提供的参数,动态决定查询语句依赖的查询条件或SQL语句的内容。
1.1 where 和 if 标签
<!-- 根据条件查询 -->
<select id="queryUserByCondition" parameterType="com.hn.pojo.User" resultType="com.hn.pojo.User">
select * from user
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="username != null and username != ''">
and username = #{username}
</if>
<if test="birthday != null ">
and birthday = #{birthday}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
<if test="address != null and address != ''">
and address = #{address}
</if>
</where>
</select>
if
就是简单的条件判断,如果有多个查询条件,我们可以利用if
标签来实现某些简单的的条件选择where
主要是用来简化 SQL 语句中 where 中的条件判断的,能够智能的处理and, or
,不必担心多余导致语法错误
- 测试代码及运行结果如下
/**
* 测试多条件查询
*/
@Test
public void testQueryUserByCondition() {
User user = new User();
user.setSex("男");
user.setAddress("湖南省永州市");
List<User> users = userMapper.queryUserByCondition(user);
for (User u : users) {
System.out.println(u);
}
}
通过上图中的查询语句我们不难发现,
where
标签帮我们在自动添加了 where 以及去掉了第一个条件前面的逻辑运算符and
1.2 foreach 标签
<!-- 根据id集合查询 -->
<select id="queryUserByIds" resultType="com.hn.pojo.User">
select * from user
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" item="id" open="and id in (" separator="," close=")">
#{id}
</foreach>
</if>
</where>
</select>
foreach
主要用在构建in
条件中,它可以在 SQL 语句中进行迭代一个集合。foreach
主要有以下集合属性
connection
:表示要 foreach 的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。item
:集合中元素迭代时的别名,该参数为必选。index
:在 list 和数组中,index 是元素的序号,在 map 中,index 是元素的 key,该参数可选。open
:foreach 代码的开始符号,一般是和 close=")" 合用。常用在 in(),values() 时,该参数可选。separator
:元素之间的分隔符,例如在 in() 的时候,separator="," 会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如 in(3,4,) 这样,该参数可选。close
:foreach 代码的关闭符号,一般是和 open="(" 合用。常用在 in(),values() 时,该参数可选。- 注意,SQL 语句中的参数符号
#{id}
应该与item="id"
保持一致,也就是说,item 属性如果把临时变量声明为item
的话,那么使用时就必须写成#{item}
。
- 测试代码及运行结果如下
/**
* 测试根据 id 集合查询
*/
@Test
public void testQueryUserByIds() {
List ids = new ArrayList();
ids.add(2);
ids.add(3);
ids.add(4);
QueryVo vo = new QueryVo();
vo.setIds(ids);
List<User> users = userMapper.queryUserByIds(vo);
for (User u : users) {
System.out.println(u);
}
}